Parit Sripakdeevong
Parit Sripakdeevong

Reputation: 51

Google App Script API cannot authenticate "Request contains an invalid argument"

I am pretty much using the sample from google's own site

https://developers.google.com/apps-script/api/how-tos/execute

The relevant part of the sample python script is replicated below

from __future__ import print_function
from googleapiclient import errors
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file as oauth_file, client, tools

def main():
    """Runs the sample.
    """
    SCRIPT_ID = 'ENTER_YOUR_SCRIPT_ID_HERE'

    # Setup the Apps Script API
    SCOPES = 'https://www.googleapis.com/auth/script.projects'
    store = oauth_file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('script', 'v1', http=creds.authorize(Http()))


if __name__ == '__main__':
    main()

I am getting the following error

  File "test.py", line 67, in <module>
    main()
  File "test.py", line 22, in main
    service = build('script', 'v1', http=creds.authorize(Http()))
  File "C:\Users\pedxs\Anaconda2\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\pedxs\Anaconda2\lib\site-packages\googleapiclient\discovery.py", line 232, in build
    raise e
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/discovery/v1/apis/script/v1/rest returned "Request contains an invalid argument.">

I had this exact code working just a week ago. line 22 uses the discovery build function, which as I understand is sending credentials to Google's API authenticator server "https://www.googleapis.com/discovery/v1/apis/script/v1/rest". I am suspecting this is a problem on Google's side because even their sample code does not work.

I have tried creating a new Google Cloud Platform and getting a new credentials.json file. I also tried authenticating with a different email account.

Upvotes: 4

Views: 7768

Answers (2)

Tanaike
Tanaike

Reputation: 201378

In your situation, there are 2 patterns.

Pattern 1:

Use authorization script at Quickstart.

Sample script:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

def main():
    # Setup the Apps Script API
    SCOPES = ['https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/drive']

    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'client_secret.json', SCOPES)
            creds = flow.run_local_server()
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('script', 'v1', credentials=creds)

    scriptId = "### script ID ###"  # Please set this
    request = {"function": "myFunction", "parameters": ["sample"], "devMode": True}
    response = service.scripts().run(body=request, scriptId=scriptId).execute()
    print(response)


if __name__ == '__main__':
    main()

Pattern 2:

If you want to use the script in your question, please modify your script as follows. This is discussed at here and here.

Sample script:

from __future__ import print_function
from googleapiclient.discovery import build
from oauth2client import file as oauth_file, client, tools

def main():
    SCOPES = ['https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/drive']

    store = oauth_file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('script', 'v1', credentials=creds)

    scriptId = "### script ID ###"  # Please set this
    request = {"function": "myFunction", "parameters": ["sample"], "devMode": True}
    response = service.scripts().run(body=request, scriptId=scriptId).execute()
    print(response)


if __name__ == '__main__':
    main()

Sample script of GAS side:

function myFunction(e) {
  return "ok: " + e;
}

Result:

You can retrieve the following response from above both scripts.

{
  "response": {
    "@type": "type.googleapis.com/google.apps.script.v1.ExecutionResponse",
    "result": "ok: sample"
  },
  "done": True
}

Note:

In my environment, I could confirm that above both patterns can be used. But if in your environment, those were not used, I apologize.

Upvotes: 1

rooook
rooook

Reputation: 11

i encountered same error.

i have used that code more than 1 year ago.

but suddenly i could not use since Feb-23.

so i adopted another method, and i used post request with oauth2.

i think you need your google service account renew.

i think something change with scope ui...

good luck!

■python code

from oauth2client import client

def request_to_gas():
    credentials = client.OAuth2Credentials(
        access_token=None,
        client_id={your_client_id},
        client_secret={your_client_secret},
        refresh_token={your_refresh_token},
        token_expiry=None,
        token_uri=GOOGLE_TOKEN_URI,
        user_agent=None,
        revoke_uri=GOOGLE_REVOKE_URI)

    credentials.refresh(httplib2.Http())  # refresh the access token


    my_url = "your_google_apps_script_web_url" 
    myheaders = {'Authorization': 'Bearer {}'.format(credentials.access_token),
                 "Content-Type": "application/json"
                 }
    response = requests.post(my_url,
                  data=json.dumps({
                                   'localdate' : '2019/02/23 12:12:12'}),
                  headers=myheaders
                  )

add thins code and publish as web app.

■google apps script code

function doPost(e) {
  var params = JSON.parse(e.postData.getDataAsString());  // ※
  var value = params.localdate;  // get python code -- 2019/02/23 12:12:12

  // here is your google apps script api
  do_something();

  var output = ContentService.createTextOutput();
  output.setMimeType(ContentService.MimeType.JSON);
  output.setContent(JSON.stringify({ message: "success!" }));

  return output;
}

Upvotes: 1

Related Questions