1

I am trying to use the new Google Docs API using Google Apps Script. Since new API is not yet available as an extended service, I am trying to do it using UrlFetchApp() but failing.

Apologies for my naive attempt here:

function apiCall(){

var API_KEY = 'YOUR_API_KEY';
var username = 'YOUR_USERNAME';
var password = 'YOU_PASSWORD';

var DOC_ID = 'YOUR_DOC_ID';
var root = 'https://docs.googleapis.com/v1/documents/';
var endpoint = DOC_ID;
var query = '?key=' + API_KEY;

var params = {
 'method': 'GET',
 'muteHttpExceptions': true,
 'headers': {
    'Authorization': 'Basic ' + Utilities.base64Encode(username + ':' +      password)
  }
};

var response = UrlFetchApp.fetch(root + endpoint + query, params);
var data = response.getContentText();
var json = JSON.parse(data);

Logger.log(json);
}

I get the following response:

{error={code=401, message=Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or another valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project., status=UNAUTHENTICATED}}

Can someone point to the right direction, where I can find some documentation how to use Google Docs API in Google Apps Script.

2
  • 1
    Use OAuth. Not API key. As stated by the error message. Authorizing with OAuth for Google apis should be covered in the official Apps Script documentation on advanced API usage, and asking for links to external resources is off-topic--just use a search engine or the editor's "Help" menu. Commented Feb 16, 2019 at 16:28
  • Thank you for pointing it out. I read the offtopic help of SO and you are right asking for links is actually off-topic. I did not know that. Will be careful next time. Commented Feb 17, 2019 at 8:33

1 Answer 1

3

If you own the document then you don't need to leverage an API key. Also, instead of using Basic authentication you can leverage the built-in Bearer OAuth token as follows:

/**
 * Get `Document` resource object from Google Docs REST API.
 *
 * @param {String} docId - A Google Document Id
 *
 * @return {Document} A Document resource object. 
 */
function getDocumentResouce(docId) {
    return JSON.parse(UrlFetchApp.fetch(
            "https://docs.googleapis.com/v1/documents/" + docId,
            {
                "headers": {
                    "Authorization":"Bearer " + ScriptApp.getOAuthToken()
                }
            }  
        )
    );
}

Note: GET is the default HTTP request method used by UrlFetchApp.fetch() so you don't need to define it in the options object.


ADDENDUM

As Tanaike stated in the comments you'll need to manually add the relevant scopes (in addition to the ones you already have enabled) to your manifest JSON.

First check your project properties to get the list of existing scopes via the menu File > Project Properties > Scopes. You need to add those scopes, as well as one of the relevant document scopes (listed in the documentation) to your manifest.

The following links provide the information you'll need to manage your manifest and scopes:

https://developers.google.com/apps-script/concepts/manifests

https://developers.google.com/apps-script/concepts/scopes

Sign up to request clarification or add additional context in comments.

5 Comments

If there is only the script of apiCall() in the OP's project, I think that the scopes is not enough. It's only https://www.googleapis.com/auth/script.external_request. So how about adding the information of scopes? Those are https://www.googleapis.com/auth/documents.readonly or https://www.googleapis.com/auth/documents. Although this might be not required for OP because I'm not sure about OP's whole project, I commented here because I thought that this information might be useful for other users.
@Tanaike Excellent point! OP will need to update the manifest JSON with the appropriate scopes. I'll update my answer accordingly.
Okay so I read the documentation and since I am going to use the script for internal use within G-Suite domain, what I have understood is I am safe for now without declaring scopes in manifest. But as a good practice, I have done it still.
For another web app I am working on, this information is really helpful. Highly grateful.
@DimuDesigns how do you add a scope if it's not available in the Consent Screen? for instance, I need to add googleapis.com/auth/script.external_request, but I don't have it available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.