Search code examples
google-app-enginegoogle-cloud-platformgoogle-oauthgoogle-authenticationrest

Google Cloud Platform REST API: Acquiring Access Token and API Key


I wish to use the Google Cloud Platform (GCP) REST API locally, starting with the apps.services.versions.instances.list method.

The route works when I use "Try this API" here, but how would I use this method locally with curl?

"https://appengine.googleapis.com/v1/apps/$APPSID/services/$SERVICESID/versions/$VERSIONSID/instances?key=$YOUR_API_KEY" \
--compressed \
--header 'Accept: application/json' \
--header "Authorization: Bearer $YOUR_ACCESS_TOKEN"

#=>

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

How do I access $YOUR_API_KEY and $YOUR_ACCESS_TOKEN? I have been unable to find either in the official GCP docs.


Solution

  • You no longer need an API key. It's a legacy feature of Google APIs, provide only an access token is enough.

    In command line you can do this

     curl -H "Authorization: Bearer $(gcloud auth print-access-token)" https://....
    

    All the Google Cloud APIs are compliant with access token authentication. Few are still compliant with API keys.

    About APIKeys API

    This API has been published in beta and now closed. At least the documentation part. I don't know if this API is stable or subject to change. You can create an API key per API like this (very similar to Bartosz Pelikan answer)

    curl -H "Authorization: Bearer $(gcloud auth print-access-token)" \
       -X POST https://apikeys.googleapis.com/v1/projects/PROJECT_ID/apiKeys
    

    As you can see, I reuse the access token authentication mode