GitHub with Apps Script - Basic Usage Example - Easy to understand

42 views
Skip to first unread message

Alan Wells

unread,
Dec 6, 2019, 12:45:20 PM12/6/19
to Google Apps Script Community
You don't need to generate an OAuth token programmatically in order to make a request to Git Hub.  You can create an OAuth token manually from your GitHub account.  So, if you don't want to spend time trying to get an OAuth library to work, this is a simple alternative.
This example code shows how to make a basic request to GitHub in only a few lines of code, . . . no library . . . not many steps . . . no code that you may never understand, and won't know what to do with if it doesn't work.

This code example makes a basic request to GitHub to get your user account information.  You already know your own information, so it's obviously not of much use to you, except for getting some basic understanding of how to make a request to GitHub from Apps Script.  And even though the code doesn't do much, it's a starting point, and gets you some success, . . .  fast.  So, if you don't want to spend hours or days trying to get some code to work that you don't understand, only to end up in total failure, here is something simple that will get you success fast.

Much OAuth code will get an OAuth token, and store it, so that the token doesn't need to be generated again.  So, if you generate the token manually and store it, then there really isn't much difference.  This is meant to be for personal use, not an app that you would publish to the public.  But chances are, the reason you want access to GitHub is for your own use.



function getHardCodedToken_() {
 
var myOAuthToken;
 
  myOAuthToken
= "Put_Your_Token_Here";//Put your Git Hub token here
 
/*To manually create a token - Login to GitHub - Open Settings - go to Developer Settings -
    click Personal Access Tokens - Button - Generate new token - Fill in answers - get token -
    copy the token and paste it between the quotation marks in the setting for myOAuthToken -
    The token must be a string and have quotation marks at the beginning and end
  */

 
return myOAuthToken;
}

function basicAuthentication() {
 
var data,myToken,options,rslt,url;
 
  url
= 'https://api.github.com/user';//Get user information
  myToken
= getHardCodedToken_();

  options
= {    
    method
: 'get',
    muteHttpExceptions
: true,
    contentType
: "application/json",
    headers
: {
     
Authorization: "Bearer " + myToken
   
},
    responseType
: 'json'
 
}
 
  rslt
= UrlFetchApp.fetch(url,options);
 
 
//Logger.log('rslt: ' + rslt)
 
//Logger.log('typeof rslt: ' + typeof rslt)
 
  data
= JSON.parse(rslt);//Even though the returned value is an object it must be parsed into JSON
 
 
Logger.log('Number of Public Repos: ' + data.public_repos)
 
Logger.log('login: ' + data.login)
 
Logger.log('followers: ' + data.followers)
}



Reply all
Reply to author
Forward
0 new messages