Manage API keys (original) (raw)

This page describes how to create, edit, and restrict API keys. For information about how to use API keys to access Google APIs, seeUse API keys to access APIs.

Introduction to API keys

There are two types of API keys: standard API keys, and API keys that have been bound to a service account.

Standard API keys

Standard API keys provide a way to associate a request with a project for billing and quota purposes. When you use a standard API key (an API key that has not been bound to a service account) to access an API, the API key doesn't identify a principal. Without a principal, the request can't use Identity and Access Management (IAM) to check whether the caller is authorized to perform the requested operation.

Standard API keys can be used with any API that accepts API keys, unless API restrictions have been added to the key. Standard API keys can't be used with services that don't accept API keys, including inexpress mode.

API keys bound to a service account

API keys bound to a service account provide the identity and authorization of the service account to a request. When you use an API key that has been bound to a service account to access an API, your request is processed as if you used the bound service account to make the request.

The only API that supports bound API keys is aiplatform.googleapis.com.

Binding keys to a service account is prevented by a default organization policy constraint. To change this, seeEnable key binding to service accounts.

API key components

An API key has the following components, which let you manage and use the key:

String

The API key string is an encrypted string, for example,AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe. When you use an API key to access an API, you always use the key's string. API keys don't have an associated JSON file.

ID

The API key ID is used by Google Cloud administrative tools to uniquely identify the key. The key ID can't be used to access APIs. The key ID can be found in the URL of the key's edit page in the Google Cloud console. You can also get the key ID by using the Google Cloud CLI to list the keys in your project.

Display name

The display name is an optional, descriptive name for the key, which you can set when you create or update the key.

Bound service account

API keys that are bound to a service account include the service account's email address.

Before you begin

Complete the following tasks to use the samples on this page.

Set up authentication

Select the tab for how you plan to use the samples on this page:

Console

When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

gcloud

In the Google Cloud console, activate Cloud Shell.

Activate Cloud Shell

At the bottom of the Google Cloud console, aCloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

C++

To use the C++ samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

  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. If you're using a local shell, then create local authentication credentials for your user account:
    gcloud auth application-default login
    You don't need to do this if you're using Cloud Shell.
    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

Java

To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

  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. If you're using a local shell, then create local authentication credentials for your user account:
    gcloud auth application-default login
    You don't need to do this if you're using Cloud Shell.
    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

Python

To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

  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. If you're using a local shell, then create local authentication credentials for your user account:
    gcloud auth application-default login
    You don't need to do this if you're using Cloud Shell.
    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

REST

To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

Install the Google Cloud CLI.

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

For more information, seeAuthenticate for using REST in the Google Cloud authentication documentation.

Required roles

To get the permissions that you need to manage API keys, ask your administrator to grant you the following IAM roles on your project:

For more information about granting roles, see Manage access to projects, folders, and organizations.

You might also be able to get the required permissions through custom roles or other predefined roles.

Enable key binding to service accounts

Before you can bind an API key to a service account, you first need to set theconstraints/iam.managed.disableServiceAccountApiKeyCreation organization policy constraint to false. Changing the organization policy requires an associatedorganization resource. Projects without an organization aren't supported.

To change the policy constraint, complete the following instructions.

Console

  1. In the Google Cloud console, go to the Organization policies page.
    Go to Organization policies
  2. Switch to the organization, folder, or project you want to change the policies for.
  3. In the Filter box, enter Block service, and then click the filter name Block service account API key bindings.
  4. Click Manage policy.
  5. In the Policy source section, select Override parent's policy.
  6. Click Add a rule, and set Enforcement to Off.
  7. Click Done.
  8. Optional: Click Test changes to give you insight on how the proposed policy might cause compliance violations or disruptions.
  9. Click Set policy.

gcloud

  1. Create a file named spec.yaml, with the following content:
name: SCOPE/SCOPE_ID/policies/iam.managed.disableServiceAccountApiKeyCreation  
spec:  
  rules:  
  - enforce: false  

Provide the following values:

  1. Run the following gcloud command to allow binding of API keys to service accounts:
gcloud org-policies set-policy spec.yaml \  
    --update-mask spec  

Create an API key

To create an API key, use one of the following options:

Console

  1. In the Google Cloud console, go to the Credentials page:
    Go to Credentials
  2. Click Create credentials, and then select API key from the menu.
  3. Optional: To bind the API key to a service account, select theAuthenticate API calls through a service account checkbox and then click Select a service account to select the service account you want to bind to the key.
    For more information, seeAPI keys bound to a service account.
  4. Add API key restrictions.
    Restricting API keys is a best practice. For more information, seeApply API key restrictions.
  5. Click Create. The API key created dialog displays the string for your newly created key.

gcloud

You use thegcloud services api-keys create command to create an API key.

Replace DISPLAY_NAME with a descriptive name for your key.

 gcloud services api-keys create \
     --display-name=DISPLAY_NAME

Optional: To bind the API key to a service account, use gcloud beta instead, with the --service-account flag:

 gcloud beta services api-keys create \
     --display-name=DISPLAY_NAME \
     --service-account=SERVICE_ACCOUNT_EMAIL_ADDRESS

For more information, seeAPI keys bound to a service account.

C++

To run this sample, you must install theAPI Keys client library.

Java

To run this sample, you must install thegoogle-cloud-apikeys client library.

Python

To run this sample, you must install theAPI Keys client library.

REST

You use thekeys.create methodto create an API key. This request returns along-running operation; you must poll the operation to get the information for the new key.

Replace the following values:

curl -X POST
-H "Authorization: Bearer $(gcloud auth print-access-token)"
-H "Content-Type: application/json; charset=utf-8"
-d {'"displayName" : "DISPLAY_NAME"'}
"https://apikeys.googleapis.com/v2/projects/PROJECT/locations/global/keys"

Optional: To bind the API key to a service account instead, use the following command:

curl -X POST
-H "Authorization: Bearer $(gcloud auth print-access-token)"
-H "Content-Type: application/json; charset=utf-8"
-d {'"displayName" : "DISPLAY_NAME", "serviceAccountEmail" : "SERVICE_ACCOUNT_EMAIL"'}
"https://apikeys.googleapis.com/v2/projects/PROJECT/locations/global/keys"

For more information, seeAPI keys bound to a service account.

For more information about creating API keys using the REST API, seeCreating an API key in the API Keys API documentation.

Apply API key restrictions

API keys are unrestricted by default. Unrestricted keys are insecure because they can be used by anyone from anywhere. For production applications, you should set both application restrictions andAPI restrictions.

Add application restrictions

Application restrictions specify which websites, IP addresses, or apps can use an API key.

You can apply only one application restriction type at a time. Choose the restriction type based on your application type:

Option Application type Notes
Websites Web applications Specifies the websites that can use the key.
IP addresses Applications called by specific servers Specifies the servers or cron jobs that can use the key. This is the only restriction available if you bind your API key to a service account.
Android apps Android applications Specifies the Android application that can use the key.
iOS apps iOS applications Specifies the iOS bundles that can use the key.

Websites

To restrict the websites that can use your API key, you add one or more HTTP referrer restrictions.

You can substitute a wildcard character (*) for the subdomain or the path, but you can't insert a wildcard character into the middle of a URL. For example,*.example.com is valid, and accepts all sites ending in .example.com. However, mysubdomain*.example.com is not a valid restriction.

Port numbers can be included in HTTP referrer restrictions. If you include a port number, then only requests using that port are matched. If you don't specify a port number, then requests from any port number are matched.

The following table shows some example scenarios and browser restrictions:

Scenario Restrictions
Allow a specific URL Add a URL with an exact path. For example: www.example.com/path www.example.com/path/path Some browsers implement a referrer policy that sends only the origin URL for cross-origin requests. Users of these browsers can't use keys with page-specific URL restrictions.
Allow any URL in your site You must set two URLs in the allowedReferers list. URL for the domain, without a subdomain, and with a wildcard for the path. For example: example.com/* A second URL that includes a wildcard for the subdomain and a wildcard for the path. For example: *.example.com/*
Allow any URL in a single subdomain or naked domain You must set two URLs in the allowedReferers list to allow an entire domain: URL for the domain, without a trailing slash. For example: www.example.com sub.example.com example.com A second URL for the domain that includes a wildcard for the path. For example: www.example.com/\* sub.example.com/* example.com/*

To restrict your API key to specific websites, use one of the following options:

Console

  1. In the Google Cloud console, go to the Credentials page:
    Go to Credentials
  2. Click the name of the API key that you want to restrict.
  3. In the Application restrictions section, select HTTP referrers.
  4. For each restriction that you want to add, click Add an item, enter the restriction, and click Done.
  5. Click Save to save your changes and return to the API key list.

gcloud

  1. Get the ID of the key that you want to restrict.
    The ID is not the same as the display name or the key string. You can get the ID by using thegcloud services api-keys list commandto list the keys in your project.
  2. Use thegcloud services api-keys update commandto add HTTP referrer restrictions to an API key.
    Replace the following values:
    • KEY_ID: The ID of the key that you want to restrict.
    • ALLOWED_REFERRER_1: Your HTTP referrer restriction.
      You can add as many restrictions as needed; use commas to separate the restrictions. You must provide all referrer restrictions with the update command; the referrer restrictions provided replace any existing referrer restrictions on the key.
      gcloud services api-keys update KEY_ID \
      --allowed-referrers="ALLOWED_REFERRER_1"

Java

To run this sample, you must install thegoogle-cloud-apikeys client library.

Python

To run this sample, you must install theAPI Keys client library.

REST

  1. Get the ID of the key that you want to restrict.
    The ID is not the same as the display name or the key string. You can get the ID by using thekeys.listmethod. The ID is listed in the uid field of the response.
    Replace PROJECT_ID with your Google Cloud project ID or name.
    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. Use thekeys.patchmethod to add HTTP referrer restrictions to the API key.
    This request returns a long-running operation; you must poll the operation to know when the operation completes and get the operation status.
    Replace the following values:
    • ALLOWED_REFERRER_1: Your HTTP referrer restriction.
      You can add as many restrictions as needed; use commas to separate the restrictions. You must provide all referrer restrictions with the request; the referrer restrictions provided replace any existing referrer restrictions on the key.
    • PROJECT_ID: Your Google Cloud project ID or name.
    • KEY_ID: The ID of the key that you want to restrict.
      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      --data '{
      "restrictions" : {
      "browserKeyRestrictions": {
      "allowedReferrers": ["ALLOWED_REFERRER_1"]
      }
      }
      }' \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

For more information about adding HTTP referrer restrictions to a key using the REST API, seeAdding browser restrictionsin the API Keys API documentation.

IP addresses

You can specify the external IP addresses of the callers (such as web servers or cron jobs) that are allowed to use your API keys. You can specify IP addresses in the following formats:

Internal IP addresses and localhost aren't supported.

To restrict your API key to specific external IP addresses, use one of the following options:

Console

  1. In the Google Cloud console, go to the Credentials page:
    Go to Credentials
  2. Click the name of the API key that you want to restrict.
  3. In the Application restrictions section, select IP addresses.
  4. For each IP address that you want to add, click Add an item, enter the address, and click Done.
  5. Click Save to save your changes and return to the API key list.

gcloud

  1. Get the ID of the key that you want to restrict.
    The ID is not the same as the display name or the key string. You can get the ID by using thegcloud services api-keys list commandto list the keys in your project.
  2. Use thegcloud services api-keys update commandto add server (IP address) restrictions to an API key.
    Replace the following values:
    • KEY_ID: The ID of the key that you want to restrict.
    • ALLOWED_IP_ADDR_1: Your allowed IP address.
      You can add as many IP addresses as needed; use commas to separate the addresses.
      gcloud services api-keys update KEY_ID \
      --allowed-ips="ALLOWED_IP_ADDR_1"

Java

To run this sample, you must install thegoogle-cloud-apikeys client library.

Python

To run this sample, you must install theAPI Keys client library.

REST

  1. Get the ID of the key that you want to restrict.
    The ID is not the same as the display name or the key string. You can get the ID by using thekeys.listmethod. The ID is listed in the uid field of the response.
    Replace PROJECT_ID with your Google Cloud project ID or name.
    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. Use thekeys.patchmethod to add server (IP address) restrictions to an API key.
    This request returns a long-running operation; you must poll the operation to know when the operation completes and get the operation status.
    Replace the following values:
    • ALLOWED_IP_ADDR_1: Your allowed IP address.
      You can add as many IP addresses as needed; use commas to separate the restrictions. You must provide all IP addresses with the request; the referrer restrictions provided replace any existing IP address restrictions on the key.
    • PROJECT_ID: Your Google Cloud project ID or name.
    • KEY_ID: The ID of the key that you want to restrict.
      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      --data '{
      "restrictions" : {
      "serverKeyRestrictions": {
      "allowedIps": ["ALLOWED_IP_ADDR_1"]
      }
      }
      }' \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

For more information about adding IP address restrictions to a key using the REST API, seeAdding server restrictionsin the API Keys API documentation.

Android apps

You can restrict usage of an API key to specific Android apps. You must provide the package name and the 20-byte SHA-1 certificate fingerprint for each app.

When you use the API key in a request, you must specify the package name and certificate fingerprint by using the following HTTP headers:

To restrict your API key to one or more Android apps, use one of the following options:

Console

  1. In the Google Cloud console, go to the Credentials page:
    Go to Credentials
  2. Click the name of the API key that you want to restrict.
  3. In the Application restrictions section, select Android apps.
  4. For each Android app that you want to add, click Add an item and enter the package name and SHA-1 certificate fingerprint, then click Done.
  5. Click Save to save your changes and return to the API key list.

gcloud

  1. Get the ID of the key that you want to restrict.
    The ID is not the same as the display name or the key string. You can get the ID by using thegcloud services api-keys list commandto list the keys in your project.
  2. Use thegcloud services api-keys update commandto specify the Android apps that can use an API key.
    Replace the following values:
    • KEY_ID: The ID of the key that you want to restrict.
    • SHA1_FINGERPRINT andPACKAGE_NAME: The app information for an Android app that can use the key.
      You can add as many apps as needed; use additional--allowed-application flags.
      gcloud services api-keys update KEY_ID \
      --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_1,package_name=PACKAGE_NAME_1 \
      --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_2,package_name=PACKAGE_NAME_2

Java

To run this sample, you must install thegoogle-cloud-apikeys client library.

Python

To run this sample, you must install theAPI Keys client library.

REST

  1. Get the ID of the key that you want to restrict.
    The ID is not the same as the display name or the key string. You can get the ID by using thekeys.listmethod. The ID is listed in the uid field of the response.
    Replace PROJECT_ID with your Google Cloud project ID or name.
    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. Use thekeys.patchmethod to specify the Android apps that can use an API key.
    This request returns a long-running operation; you must poll the operation to know when the operation completes and get the operation status.
    Replace the following values:
    • SHA1_FINGERPRINT_1 andPACKAGE_NAME_1: The app information for an Android app that can use the key.
      You can add the information for as many apps as needed; use commas to separate theAndroidApplicationobjects. You must provide all applications with the request; the applications provided replace any existing allowed applications on the key.
    • PROJECT_ID: Your Google Cloud project ID or name.
    • KEY_ID: The ID of the key that you want to restrict.
      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      --data '{
      "restrictions" : {
      "androidKeyRestrictions": {
      "allowedApplications": [
      {
      "sha1Fingerprint": "SHA1_FINGERPRINT_1",
      "packageName": "PACKAGE_NAME_1"
      },
      ]
      }
      }
      }' \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

For more information about adding Android app restrictions to a key using the REST API, seeAdding Android restrictionsin the API Keys API documentation.

iOS apps

You can restrict usage of an API key to specific iOS apps by providing the bundle ID of each app.

When you use the API key in a request, you must specify the bundle ID by using the X-Ios-Bundle-Identifier HTTP header.

To restrict your API key to one or more iOS apps, use one of the following options:

Console

  1. In the Google Cloud console, go to the Credentials page:
    Go to Credentials
  2. Click the name of the API key that you want to restrict.
  3. In the Application restrictions section, select iOS apps.
  4. For each iOS app that you want to add, click Add an item and enter the bundle ID, then click Done.
  5. Click Save to save your changes and return to the API key list.

gcloud

  1. Get the ID of the key that you want to restrict.
    The ID is not the same as the display name or the key string. You can get the ID by using thegcloud services api-keys list commandto list the keys in your project.
  2. Use thegcloud services api-keys updatemethod to specify the iOS apps that can use the key.
    Replace the following values:
    • KEY_ID: The ID of the key that you want to restrict.
    • ALLOWED_BUNDLE_ID: The bundle ID of an iOS app that you want to be able to use this API key.
      You can add as many bundle IDs as needed; use commas to separate the IDs.
      gcloud services api-keys update KEY_ID \
      --allowed-bundle-ids=ALLOWED_BUNDLE_ID_1,ALLOWED_BUNDLE_ID_2

Java

To run this sample, you must install thegoogle-cloud-apikeys client library.

Python

To run this sample, you must install theAPI Keys client library.

REST

  1. Get the ID of the key that you want to restrict.
    The ID is not the same as the display name or the key string. You can get the ID by using thekeys.listmethod. The ID is listed in the uid field of the response.
    Replace PROJECT_ID with your Google Cloud project ID or name.
    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. Use thekeys.patchmethod to specify the iOS apps that can use an API key.
    This request returns a long-running operation; you must poll the operation to know when the operation completes and get the operation status.
    Replace the following values:
    • ALLOWED_BUNDLE_ID: The bundle ID of an iOS app that can use the key.
      You can add the information for as many apps as needed; use commas to separate the bundle IDs. You must provide all bundle IDs with the request; the bundle IDs provided replace any existing allowed applications on the key.
    • PROJECT_ID: Your Google Cloud project ID or name.
    • KEY_ID: The ID of the key that you want to restrict.
      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      --data '{
      "restrictions" : {
      "iosKeyRestrictions": {
      "allowedBundleIds": ["ALLOWED_BUNDLE_ID_1","ALLOWED_BUNDLE_ID_2"]
      }
      }
      }' \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

For more information about adding iOS app restrictions to a key using the REST API, seeAdding iOS restrictionsin the API Keys API documentation.

Add API restrictions

API restrictions specify which APIs can be called using the API key.

To add API restrictions, use one of the following options:

Console

  1. In the Google Cloud console, go to the Credentials page:
    Go to Credentials
  2. Click the name of the API key that you want to restrict.
  3. In the API restrictions section, click Restrict key.
  4. Select all APIs that your API key will be used to access.
  5. Click Save to save your changes and return to the API key list.

gcloud

  1. Get the ID of the key that you want to restrict.
    The ID is not the same as the display name or the key string. You can get the ID by using thegcloud services api-keys list commandto list the keys in your project.
  2. Use thegcloud services api-keys update commandto specify which services an API key can be used to access.
    Replace the following values:
    • KEY_ID: The ID of the key that you want to restrict.
    • SERVICE_1, SERVICE_2...: The service names of the APIs that the key can be used to access.
      You must provide all service names with the update command; the service names provided replace any existing services on the key.
      You can find the service name by searching for the API on theAPI dashboard. Service names are strings like bigquery.googleapis.com.
      gcloud services api-keys update KEY_ID \
      --api-target=service=SERVICE_1 --api-target=service=SERVICE_2

Java

To run this sample, you must install thegoogle-cloud-apikeys client library.

Python

To run this sample, you must install theAPI Keys client library.

REST

  1. Get the ID of the key that you want to restrict.
    The ID is not the same as the display name or the key string. You can get the ID by using thekeys.listmethod. The ID is listed in the uid field of the response.
    Replace PROJECT_ID with your Google Cloud project ID or name.
    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. Use thekeys.patchmethod to specify which services an API key can be used to access.
    This request returns a long-running operation; you must poll the operation to know when the operation completes and get the operation status.
    Replace the following values:
    • SERVICE_1, SERVICE_2...: The service names of the APIs that the key can be used to access.
      You must provide all service names with the request; the service names provided replace any existing services on the key.
      You can find the service name by searching for the API on theAPI dashboard. Service names are strings like bigquery.googleapis.com.
    • PROJECT_ID: Your Google Cloud project ID or name.
    • KEY_ID: The ID of the key that you want to restrict.
      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      --data '{
      "restrictions" : {
      "apiTargets": [
      {
      "service": "SERVICE_1"
      },
      {
      "service" : "SERVICE_2"
      },
      ]
      }
      }' \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

For more information about adding API restrictions to a key using the REST API, seeAdding API restrictionsin the API Keys API documentation.

Get project information from a key string

You can determine which Google Cloud project an API key is associated with from its string.

Replace KEY_STRING with the key string you need project information for.

gcloud

You use thegcloud services api-keys lookup command to get the project ID from a key string.

gcloud services api-keys lookup KEY_STRING

Java

To run this sample, you must install thegoogle-cloud-apikeys client library.

Python

To run this sample, you must install theAPI Keys client library.

REST

You use thelookupKey methodto get the project ID from a key string.

curl -X GET
-H "Authorization: Bearer $(gcloud auth print-access-token)"
-H "Content-Type: application/json; charset=utf-8"
"https://apikeys.googleapis.com/v2/keys:lookupKey?keyString=KEY_STRING"

Create a copy of an API key

If you need a new API key with the same restrictions as an existing API key, you can create a copy of the existing API key. This operation creates a new API key with a unique key string and ID, with the existing API key's restrictions.

The copy operation is available only in the Google Cloud console. To use other methods, follow the steps to create an API key, and thenapply the same API key restrictions to the newly generated API key.

  1. In the Google Cloud console, go to the Credentials page:
    Go to Credentials
  2. Click the name of the API key that you want to copy.
    The API key's details page opens.
  3. Click Create a copy.
  4. Enter a name for the new API key and confirm that the restrictions are correct.
  5. Click Create.

Rotate an API key

By periodically rotating your API keys, you can limit the impact of any compromised API keys.

When you rotate an API key, you create a new key with the same restrictions as the old key, and update your applications to use the new key. After all of your applications are updated, you delete the old key.

The rotation operation is available only in the Google Cloud console. To use other methods, follow the steps to create an API key, and thenapply the same API key restrictions to the newly generated API key. After updating your applications to use the new key, you delete the old key.

  1. In the Google Cloud console, go to the Credentials page:
    Go to Credentials
  2. Click the name of the API key that you want to rotate to open its details page.
  3. Click Rotate key.
  4. Enter a name for the new API key and confirm that the restrictions are correct.
  5. Click Create.
  6. Copy the key string and update your applications to use the new string.
  7. After you have updated all applications to use the new key, return to the details page for the new key. In the Previous key section, clickDelete the previous key to delete the old key.
    If you find that you deleted the old key prematurely, you canundelete it.

Undelete an API key

If you delete an API key by mistake, you can undelete (restore) that key within 30 days of deleting the key. After 30 days, you cannot undelete the API key.

Console

  1. In the Google Cloud console, go to the Credentials page:
    Go to Credentials
  2. Click Restore deleted credentials.
  3. Find the deleted API key that you want to undelete, and click Restore.
    Undeleting an API key may take a few minutes to propagate. After propagation, the undeleted API key is displayed in the API keys list.

gcloud

  1. Get the ID of the key that you want to undelete.
    The ID is not the same as the display name or the key string. You can get the ID by using thegcloud services api-keys list --show-deleted commandto list the deleted keys in your project.
  2. Use thegcloud services api-keys undelete commandto undelete an API key.
    gcloud services api-keys undelete KEY_ID
    Replace the following values:
    • KEY_ID: The ID of the key that you want to undelete.

Java

To run this sample, you must install thegoogle-cloud-apikeys client library.

REST

  1. Get the ID of the key that you want to undelete.
    The ID is not the same as the display name or the key string. You can get the ID by using thekeys.listmethod, with the showDeleted query parameter set to true. The key ID is listed in the uid field of the response.
    Replace PROJECT_ID with your Google Cloud project ID or name.
    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys?showDeleted=true"
  2. Use theundeletemethod to undelete the API key.
    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID:undelete"
    This request returns a long-running operation; you must poll the operation to know when the operation completes and get the operation status.
    Replace the following values:
    • PROJECT_ID: Your Google Cloud project ID or name.
    • KEY_ID: The ID of the key that you want to restrict.

Determine the API key type

You can determine whether the API key is bound to a service account by inspecting the key.

Console

  1. In the Google Cloud console, go to the Credentials page:
    Go to Credentials
    If the API key is bound to a service account, the service account identifier is displayed.

gcloud

  1. Get the ID of the key.
    The ID is not the same as the display name or the key string. You can get the ID by using thegcloud services api-keys list commandto list the keys in your project.
  2. Use thegcloud services api-keys describe commandto describe the API key.
    gcloud services api-keys describe KEY_ID
    If the API key is bound to a service account, the serviceAccountEmailfield is displayed.

Poll long-running operations

API Keys API methods use long-running operations. If you use the REST API to create and manage API keys, an operation object is returned from the initial method request. You use the operation name to poll the long-running operation. When the long-running request completes, polling the operation returns the data from the long-running request.

To poll a long-running API Keys API operation, you use theoperations.get method.

Replace OPERATION_NAME with the operation name returned by the long-running operation. For example,operations/akmf.p7-358517206116-cd10a88a-7740-4403-a8fd-979f3bd7fe1c.

curl -X GET
-H "Authorization: Bearer $(gcloud auth print-access-token)"
-H "Content-Type: application/json; charset=utf-8"
"https://apikeys.googleapis.com/v2/OPERATION_NAME"

Limits on API keys

You can create up to 300 API keys per project. This limit is a system limit, and can't be changed using a quota increase request. If more API keys are needed, you must use more than one project.

You can add up to 1200application restrictions to an API key.

What's next