The simplest way to get a token to use with a Google API is to borrow the one from Apps Script - assuming that you can persuade Apps Script to enter an authorization dialog for the scopes you need. This means that you can use this method for some APIS that also exist as Apps Script services, but you need to access the native APIS. Other methods covered are If you prefer, here's a video version of this post. The demo source code used on all video posts are on github All the demo code is available on github. Note that I'm using the same code for all these examples, so the final source on github will have evolved in some details from the writeup here. Using the apps script tokenIn this example, I want to use the Google Drive API rather than the Drive or DriveApp service.
function usingAppsScriptsToken () { // we need to provoke a drive dialog // a comment is fine for that // DriveApp.getFiles() // get some files using the appssscript token var filesMeta = getMetaFromDriveApi ( ScriptApp.getOAuthToken() ); // convert result Logger.log (JSON.stringify(filesMeta.files)); }
![]()
function getMetaFromDriveApi (accessToken) { // the API end point var endPoint = "https://www.googleapis.com/drive/v3/files"; // get 10 files matching some namee var response = UrlFetchApp.fetch ( endPoint + "?pageSize=10&q=" + encodeURIComponent( "name contains 'goa'" + " and trashed=false" ) + "&fields=" + encodeURIComponent( "files(id,mimeType,name),nextPageToken" ) , { headers: { Authorization:'Bearer ' + accessToken } }); // objectify the result return JSON.parse (response.getContentText()); } For more like this, see Google Apps Scripts snippets. Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.You want to learn Google Apps Script?Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, All formats are available from O'Reilly, Amazon and all good bookshops. You can also read a preview on O'Reilly If you prefer Video style learning I also have two courses available. also published by O'Reilly. |
Services > Desktop Liberation - the definitive resource for Google Apps Script and Microsoft Office automation > OAuth2 for Apps Script in a few lines of code > Some OAUTH2 walkthroughs >