Authenticate for using REST

This page describes how to authenticate when youmake a REST request to a Google API.

For information about how to authenticate when you use Google client libraries,seeAuthenticate using client libraries.

Before you begin

To run the samples on this page, complete the following steps:

  1. Install the Google Cloud CLI.

  2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  3. Toinitialize the gcloud CLI, run the following command:

    gcloudinit
  4. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    gcloudservicesenablecloudresourcemanager.googleapis.com iam.googleapis.com

If you don't want to use the gcloud CLI, you can skip these stepsand useservice account impersonation orthe metadata server to generate a token.

Types of credentials

You can use the following types of credentials to authenticate a REST call:

  • Yourgcloud CLI credentials.

    This approach is the easiest and most secure way to provide credentials to aREST method in a local development environment. If your user account has thenecessary Identity and Access Management (IAM) permissions for the method you want tocall, this is the preferred approach.

    Your gcloud credentials are not the same as the credentials you provide to ADC using thegcloud CLI. For more information, see gcloud CLI authentication configuration and ADC configuration.

  • Thecredentials provided to Application Default Credentials (ADC).

    This method is the preferred option for authenticating a REST call in aproduction environment, because ADC finds credentials from the resourcewhere your code is running (such as a Compute Engine virtual machine). Youcan also use ADC to authenticate in a local development environment. In thisscenario, the gcloud CLI creates a file that contains yourcredentials in your local file system.

  • Thecredentials provided by impersonating a service account.

    This method requires more setup. If you want to use your existingcredentials to obtain short-lived credentials for another service account,such as testing with a service account locally or requesting temporaryelevated privileges, use this approach.

  • Thecredentials returned by the metadata server.

    This method works only in environments with access to a metadata server. Thecredentials returned by the metadata server are the same as the credentialsthat would be found byApplication Default Credentials using theattached service account, but you explicitly request the access token fromthe metadata server and then provide it with the REST request. Querying themetadata server for credentials requires an HTTP GET request; this methoddoes not rely on the Google Cloud CLI.

  • API keys

    You can use an API key with a REST request only for APIs that accepts APIkeys. In addition, the API key must not be restricted to prevent it frombeing used with the API.

gcloud CLI credentials

To run the following example, you need theresourcemanager.projects.getpermission on the project. Theresourcemanager.projects.get permission isincluded in a variety of roles—for example, theBrowser role (roles/browser).

  1. Use thegcloud auth print-access-token commandto insert an access token generated from your user credentials.

    The following example gets details for the specified project. You can use thesame pattern for any REST request.

    Before using any of the request data, make the following replacements:

    • PROJECT_ID: Your Google Cloud project ID or name.

    To send your request, choose one of these options:

    curl

    Execute the following command:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://cloudresourcemanager.googleapis.com/v3/projects/PROJECT_ID"

    PowerShell

    Execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method GET `
    -Headers $headers `
    -Uri "https://cloudresourcemanager.googleapis.com/v3/projects/PROJECT_ID" | Select-Object -Expand Content

    The details for your project are returned.

For APIs that require a quota project, you must setone explicitly for the request. For more information, seeSet the quota project with a REST request on this page.

Application Default Credentials

To run the following example, the principal associated with the credentials youprovide to ADC needs theresourcemanager.projects.get permission on theproject. Theresourcemanager.projects.get permission is included in a varietyof roles—for example, theBrowser role (roles/browser).

  1. Provide credentials to ADC.

    If you are running on a Google Cloud compute resource, you shouldn'tprovide your user credentials to ADC. Instead, use the attached serviceaccount to provide credentials. For more information, seeSet up ADC for a resource with an attached service account.

  2. Use thegcloud auth application-default print-access-token commandto insert the access token returned by ADC into your REST request.

    The following example gets details for the specified project. You can use thesame pattern for any REST request.

    Before using any of the request data, make the following replacements:

    • PROJECT_ID: Your Google Cloud project ID or name.

    To send your request, choose one of these options:

    curl

    Execute the following command:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    "https://cloudresourcemanager.googleapis.com/v3/projects/PROJECT_ID"

    PowerShell

    Execute the following command:

    $cred = gcloud auth application-default print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method GET `
    -Headers $headers `
    -Uri "https://cloudresourcemanager.googleapis.com/v3/projects/PROJECT_ID" | Select-Object -Expand Content

    The details for your project are returned.

    If your request returns an error message about end-user credentials not being supported by this API, seeSet the quota project with a REST request on this page.

Impersonated service account

The simplest way to impersonate a service account to generate an access token is by usingthe gcloud CLI. However, if you need to generate the tokenprogrammatically, or you don't want to use the gcloud CLI, you canuse impersonation to generate a short-lived token.

For more information about impersonating a service account, seeUse service account impersonation.

  1. Review the required permissions.

    • The prinicipal you want to use to perform the impersonation must have theiam.serviceAccounts.getAccessTokenpermission on the impersonated service account (also called theprivilege-bearing service account). Theiam.serviceAccounts.getAccessToken permission is included in theService Account Token Creator role(roles/iam.serviceAccountTokenCreator). If you are using your useraccount, you need to add this permission even if you have the Owner role(roles/owner) on the project. For more information, seeSetting required permissions.
  2. Identify or create the privilege-bearing service account—the service accountyou will impersonate.

    The privilege-bearing service account must have the permissions requiredto make the API method call.

gcloud

  1. Use thegcloud auth print-access-token commandwith the--impersonate-service-account flagto insert an access token for the privilege-bearing service account intoyour REST request.

The following example gets details for the specified project. You can use thesame pattern for any REST request.

To run this example, the service account you impersonate needs theresourcemanager.projects.get permission. Theresourcemanager.projects.getpermission is included in a variety of roles—for example, theBrowser role (roles/browser).

Make the following replacements:

  • PRIV_SA: The email address of the privilege-bearingservice account. For example,my-sa@my-project.iam.gserviceaccount.com.

  • PROJECT_ID: Your Google Cloud project ID or name.

curl-XGET\-H"Authorization: Bearer$(gcloudauthprint-access-token--impersonate-service-account=PRIV_SA)"\"https://cloudresourcemanager.googleapis.com/v3/projects/PROJECT_ID"

Short-lived token

To generate a short-lived token by using service account impersonation,follow the instructions provided inCreate a short-lived access token.

Metadata server

To get an access token from the metadata server, you must make the REST callusing one of the services that has access to a metadata server:

You use a command-line tool such ascurl to get an access token, and theninsert it into your REST request.

  1. Query the metadata server for an access token:

    curl"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"\-H"Metadata-Flavor: Google"

    The request returns a response similar to the following example:

    {"access_token":"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_QtAi85nHq39HE3C2LTrCARA","expires_in":3599,"token_type":"Bearer"}
  2. Insert the access token into your REST request, making the followingreplacements:

    • ACCESS_TOKEN: The access token returned in theprevious step.
    • PROJECT_ID: Your Google Cloud project ID or name.
    curl-XGET\-H"Authorization: BearerACCESS_TOKEN"\"https://cloudresourcemanager.googleapis.com/v3/projects/PROJECT_ID"

API keys

To include an API key with a REST API call, use thex-goog-api-key HTTPheader, as shown in the following example:

curl -X POST \    -H "X-goog-api-key:API_KEY" \    -H "Content-Type: application/json; charset=utf-8" \    -d @request.json \    "https://translation.googleapis.com/language/translate/v2"

If you can't use the HTTP header, you can use thekey query parameter.However, this method includes your API key in the URL, exposing your key totheft through URL scans.

The following example shows how to use thekey query parameter with aCloud Natural Language API request fordocuments.analyzeEntities.ReplaceAPI_KEY with the key string of your API key.

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY

Set the quota project with a REST request

To call some APIs with user credentials, you must also set the project that isbilled for your usage and used to track quota. If your API call returns an errormessage saying that user credentials are not supported, or that the quotaproject is not set, you must explicitly set the quota project for the request.To set the quota project, include thex-goog-user-project header with yourrequest.

For more information about when you might encounter this issue, seeUser credentials not working.

You must have theserviceusage.services.use IAM permission fora project to be able to designate it as your billing project. Theserviceusage.services.use permission is included in the Service Usage ConsumerIAM role. If you don't have theserviceusage.services.usepermission for any project, contact your security administrator or a projectowner who can give you the Service Usage Consumer role in the project.

The following example uses the Cloud Translation API to translate the word "hello" into Spanish. The Cloud Translation API isan API that needs a quota project to be specified. To run the sample, create afile namedrequest.json with the request body content.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: The ID or name of the Google Cloud project to use as a billing project.

Request JSON body:

{  "q": "hello",  "source": "en",  "target": "es"}

To send your request, choose one of these options:

curl

Save the request body in a file namedrequest.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project:PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://translation.googleapis.com/language/translate/v2"

PowerShell

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/language/translate/v2" | Select-Object -Expand Content

The translation request succeeds. You can try the command without thex-goog-user-project HTTP header to see what happens when you do not specify the billing project.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-18 UTC.