Manage API keys

This page describes how to create, edit, and restrict API keys. For informationabout 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 beenbound to a service account.

Standard API keys

Standard API keys provide a way to associate a request with a project forbilling and quota purposes. When you use a standard API key (an API key that hasnot been bound to a service account) to access an API, the API key doesn'tidentify aprincipal. Without a principal, therequest can't use Identity and Access Management (IAM) to check whether the caller isauthorized to perform the requested operation.

Standard API keys can be used with any API that accepts API keys, unless APIrestrictions have been added to the key. Standard API keys can't be used withservices 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 ofthe service account to a request. When you use an API key that has been bound toa service account to access an API, your request is processed as if you used thebound service account to make the request.

The only API that supports bound API keys isaiplatform.googleapis.com.

Caution: API keys bound to service accounts are designed to accelerate theinitial experience for developers exploring Google Cloud APIs. Don't use themin production environments. Instead, plan to migrate to more secure alternativessuch asIAM policies andshort-lived service account credentials,following least-privilege security practices. Read more aboutthe risks of API keys bound to service accounts.

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

Note: Requests authenticated by API keys bound to service accounts aren'trecorded inservice account usage metrics.

API key components

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

String
The API key string is an encrypted string, for example,AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe. When you use an API key toaccess an API, you always use the key's string. API keys don't have anassociated JSON file.
ID
The API key ID is used by Google Cloud administrative tools to uniquelyidentify the key. The key ID can't be used to access APIs. The key ID can befound in the URL of the key's edit page in the Google Cloud console. You can alsoget 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'semail 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:

    gcloudauthapplication-defaultlogin

    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:

    gcloudauthapplication-defaultlogin

    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:

    gcloudauthapplication-defaultlogin

    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:

  • API Keys Admin (roles/serviceusage.apiKeysAdmin)
  • Restrict an API key to specific APIs by using the Google Cloud console:Service Usage Viewer (roles/serviceusage.serviceUsageViewer)

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

You might also be able to get the required permissions throughcustom roles or otherpredefined roles.

Enable key binding to service accounts

Before you canbind an API key to a service account, youfirst need to set theconstraints/iam.managed.disableServiceAccountApiKeyCreation organizationpolicy constraint tofalse. Changing the organization policy requires anassociatedorganization 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 theOrganization policies page.

    Go to Organization policies

  2. Switch to the organization, folder, or project you want to change thepolicies for.

  3. In theFilter box, enterBlock service, and then click the filternameBlock service account API key bindings.

  4. ClickManage policy.

  5. In thePolicy source section, selectOverride parent's policy.

  6. ClickAdd a rule, and setEnforcement toOff.

  7. ClickDone.

  8. Optional: ClickTest changes to give you insight on how the proposedpolicy might cause compliance violations or disruptions.

  9. ClickSet policy.

gcloud

  1. Create a file namedspec.yaml, with the following content:

    name:SCOPE/SCOPE_ID/policies/iam.managed.disableServiceAccountApiKeyCreationspec:rules:-enforce:false

    Provide the following values:

    • SCOPE: Eitherorganizations,folders, orprojects.

    • SCOPE_ID: Depending onSCOPE, the ID ofthe organization, folder, or project to which the organization policyapplies.

  2. Run the followinggcloud command to allow binding of API keys to serviceaccounts:

    gcloudorg-policiesset-policyspec.yaml\--update-maskspec

Create an API key

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

Console

  1. In the Google Cloud console, go to theCredentials page:

    Go to Credentials

  2. ClickCreate credentials, and then selectAPI 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 thenclickSelect a service account to select the service account you wantto 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. ClickCreate. TheAPI key created dialog displays the string foryour newly created key.

gcloud

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

ReplaceDISPLAY_NAME with a descriptive name for your key.

gcloudservicesapi-keyscreate\--display-name=DISPLAY_NAME

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

gcloudbetaservicesapi-keyscreate\--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.

#include"google/cloud/apikeys/v2/api_keys_client.h"#include"google/cloud/location.h"google::api::apikeys::v2::KeyCreateApiKey(google::cloud::apikeys_v2::ApiKeysClientclient,google::cloud::Locationlocation,std::stringdisplay_name){google::api::apikeys::v2::CreateKeyRequestrequest;request.set_parent(location.FullName());request.mutable_key()->set_display_name(std::move(display_name));// As an example, restrict the API key's scope to the Natural Language API.request.mutable_key()->mutable_restrictions()->add_api_targets()->set_service("language.googleapis.com");// Create the key, blocking on the result.autokey=client.CreateKey(request).get();if(!key)throwstd::move(key.status());std::cout <<"Successfully created an API key: " <<key->name() <<"\n";// For authenticating with the API key, use the value in `key->key_string()`.// The API key's resource name is the value in `key->name()`. Use this to// refer to the specific key in a `GetKey()` or `DeleteKey()` RPC.return*key;}

Java

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

importcom.google.api.apikeys.v2.ApiKeysClient;importcom.google.api.apikeys.v2.ApiTarget;importcom.google.api.apikeys.v2.CreateKeyRequest;importcom.google.api.apikeys.v2.Key;importcom.google.api.apikeys.v2.LocationName;importcom.google.api.apikeys.v2.Restrictions;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateApiKey{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(Developer): Before running this sample,//  1. Replace the variable(s) below.//  2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc//  3. Make sure you have the necessary permission to create API keys.StringprojectId="GOOGLE_CLOUD_PROJECT_ID";createApiKey(projectId);}// Creates an API key.publicstaticvoidcreateApiKey(StringprojectId)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the `apiKeysClient.close()` method on the client to safely// clean up any remaining background resources.try(ApiKeysClientapiKeysClient=ApiKeysClient.create()){Keykey=Key.newBuilder().setDisplayName("My first API key")// Set the API key restriction.// You can also set browser/ server/ android/ ios based restrictions.// For more information on API key restriction, see:// https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions.setRestrictions(Restrictions.newBuilder()// Restrict the API key usage by specifying the target service and methods.// The API key can only be used to authenticate the specified methods in the service..addApiTargets(ApiTarget.newBuilder().setService("translate.googleapis.com").addMethods("translate.googleapis.com.TranslateText").build()).build()).build();// Initialize request and set arguments.CreateKeyRequestcreateKeyRequest=CreateKeyRequest.newBuilder()// API keys can only be global..setParent(LocationName.of(projectId,"global").toString()).setKey(key).build();// Make the request and wait for the operation to complete.Keyresult=apiKeysClient.createKeyAsync(createKeyRequest).get(3,TimeUnit.MINUTES);// For authenticating with the API key, use the value in "result.getKeyString()".// To restrict the usage of this API key, use the value in "result.getName()".System.out.printf("Successfully created an API key: %s",result.getName());}}}

Python

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

fromgoogle.cloudimportapi_keys_v2fromgoogle.cloud.api_keys_v2importKeydefcreate_api_key(project_id:str,suffix:str)->Key:"""    Creates and restrict an API key. Add the suffix for uniqueness.    TODO(Developer):    1. Before running this sample,      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc    2. Make sure you have the necessary permission to create API keys.    Args:        project_id: Google Cloud project id.    Returns:        response: Returns the created API Key.    """# Create the API Keys client.client=api_keys_v2.ApiKeysClient()key=api_keys_v2.Key()key.display_name=f"My first API key -{suffix}"# Initialize request and set arguments.request=api_keys_v2.CreateKeyRequest()request.parent=f"projects/{project_id}/locations/global"request.key=key# Make the request and wait for the operation to complete.response=client.create_key(request=request).result()print(f"Successfully created an API key:{response.name}")# For authenticating with the API key, use the value in "response.key_string".# To restrict the usage of this API key, use the value in "response.name".returnresponse

REST

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

Replace the following values:

  • DISPLAY_NAME: Optional. A descriptive name for yourkey.
  • PROJECT_ID: Your Google Cloud project ID or name.
curl-XPOST\-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 followingcommand:

curl-XPOST\-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 theAPI Keys API documentation.

Important: Copy your key string and keep it secure. Use API key restrictions tolimit how the key can be used.

Apply API key restrictions

API keys are unrestricted by default. Unrestricted keys are insecure becausethey can be used by anyone from anywhere. For production applications, youshould set bothapplication restrictions andAPI restrictions.

Add application restrictions

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

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

OptionApplication typeNotes
WebsitesWeb applicationsSpecifies the websites that can use the key.
IP addressesApplications called by specific serversSpecifies 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 appsAndroid applicationsSpecifies the Android application that can use the key.
iOS appsiOS applicationsSpecifies the iOS bundles that can use the key.

Websites

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

You can substitute a wildcard character (*) for the subdomain or the path, butyou 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 aport number, then only requests using that port are matched. If you don'tspecify a port number, then requests from any port number are matched.

The following table shows some example scenarios and browser restrictions:

ScenarioRestrictions
Allow a specific URLAdd 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 siteYou must set two URLs in theallowedReferers list.
  1. URL for the domain, without a subdomain, and with a wildcard for the path. For example:
    example.com/*
  2. 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 theallowedReferers list to allow an entire domain:

  1. URL for the domain, without a trailing slash. For example:
    www.example.com
    sub.example.com
    example.com
  2. 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 theCredentials page:

    Go to Credentials

  2. Click the name of the API key that you want to restrict.

  3. In theApplication restrictions section, selectHTTP referrers.

  4. For each restriction that you want to add, clickAdd an item, enterthe restriction, and clickDone.

  5. ClickSave 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 getthe 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 torestrict.
    • ALLOWED_REFERRER_1: Your HTTP referrerrestriction.

      You can add as many restrictions as needed; use commas to separatethe restrictions. You must provide all referrer restrictions with theupdate command; the referrer restrictions provided replace any existingreferrer restrictions on the key.

    gcloudservicesapi-keysupdateKEY_ID\--allowed-referrers="ALLOWED_REFERRER_1"

Java

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

importcom.google.api.apikeys.v2.ApiKeysClient;importcom.google.api.apikeys.v2.BrowserKeyRestrictions;importcom.google.api.apikeys.v2.Key;importcom.google.api.apikeys.v2.Restrictions;importcom.google.api.apikeys.v2.UpdateKeyRequest;importcom.google.protobuf.FieldMask;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassRestrictApiKeyHttp{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(Developer): Before running this sample,//  1. Replace the variable(s) below.StringprojectId="GOOGLE_CLOUD_PROJECT_ID";// ID of the key to restrict. This ID is auto-created during key creation.// This is different from the key string. To obtain the key_id,// you can also use the lookup api: client.lookupKey()StringkeyId="key_id";restrictApiKeyHttp(projectId,keyId);}// Restricts an API key. To restrict the websites that can use your API key,// you add one or more HTTP referrer restrictions.publicstaticvoidrestrictApiKeyHttp(StringprojectId,StringkeyId)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the `apiKeysClient.close()` method on the client to safely// clean up any remaining background resources.try(ApiKeysClientapiKeysClient=ApiKeysClient.create()){// Restrict the API key usage to specific websites by adding them// to the list of allowed_referrers.Restrictionsrestrictions=Restrictions.newBuilder().setBrowserKeyRestrictions(BrowserKeyRestrictions.newBuilder().addAllowedReferrers("www.example.com/*").build()).build();Keykey=Key.newBuilder().setName(String.format("projects/%s/locations/global/keys/%s",projectId,keyId))// Set the restriction(s).// For more information on API key restriction, see:// https://cloud.google.com/docs/authentication/api-keys.setRestrictions(restrictions).build();// Initialize request and set arguments.UpdateKeyRequestupdateKeyRequest=UpdateKeyRequest.newBuilder().setKey(key).setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build()).build();// Make the request and wait for the operation to complete.Keyresult=apiKeysClient.updateKeyAsync(updateKeyRequest).get(3,TimeUnit.MINUTES);// For authenticating with the API key, use the value in "result.getKeyString()".System.out.printf("Successfully updated the API key: %s",result.getName());}}}

Python

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

fromgoogle.cloudimportapi_keys_v2fromgoogle.cloud.api_keys_v2importKeydefrestrict_api_key_http(project_id:str,key_id:str)->Key:"""    Restricts an API key. To restrict the websites that can use your API key,    you add one or more HTTP referrer restrictions.    TODO(Developer): Replace the variables before running this sample.    Args:        project_id: Google Cloud project id.        key_id: ID of the key to restrict. This ID is auto-created during key creation.            This is different from the key string. To obtain the key_id,            you can also use the lookup api: client.lookup_key()    Returns:        response: Returns the updated API Key.    """# Create the API Keys client.client=api_keys_v2.ApiKeysClient()# Restrict the API key usage to specific websites by adding them to the list of allowed_referrers.browser_key_restrictions=api_keys_v2.BrowserKeyRestrictions()browser_key_restrictions.allowed_referrers=["www.example.com/*"]# Set the API restriction.# For more information on API key restriction, see:# https://cloud.google.com/docs/authentication/api-keysrestrictions=api_keys_v2.Restrictions()restrictions.browser_key_restrictions=browser_key_restrictionskey=api_keys_v2.Key()key.name=f"projects/{project_id}/locations/global/keys/{key_id}"key.restrictions=restrictions# Initialize request and set arguments.request=api_keys_v2.UpdateKeyRequest()request.key=keyrequest.update_mask="restrictions"# Make the request and wait for the operation to complete.response=client.update_key(request=request).result()print(f"Successfully updated the API key:{response.name}")# Use response.key_string to authenticate.returnresponse

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 getthe ID by using thekeys.listmethod. The ID is listed in theuid field of the response.

    ReplacePROJECT_ID with your Google Cloud projectID or name.

    curl-XGET\-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 requestreturns along-running operation; you must poll the operation toknow when the operation completes and get the operation status.

    Replace the following values:

    • ALLOWED_REFERRER_1: Your HTTP referrerrestriction.

      You can add as many restrictions as needed; use commas to separatethe restrictions. You must provide all referrer restrictions with therequest; the referrer restrictions provided replace any existingreferrer restrictions on the key.

    • PROJECT_ID: Your Google Cloud project ID orname.

    • KEY_ID: The ID of the key that you want torestrict.

    curl-XPATCH\-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 usingthe 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 orcron jobs) that are allowed to use your API keys. You can specify IP addressesin the following formats:

  • IPv4 (198.51.100.1)

  • IPv6 (2001:db8::1)

  • A subnet using CIDR notation (198.51.100.0/24,2001:db8::/64)

Internal IP addresses andlocalhost aren't supported.

Note:Private Google Access uses internalIP addresses by design. To restrict API key usage to a specific network whenusing Private Google Access,set up a VPC Service Controls perimeterinstead.

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

Console

  1. In the Google Cloud console, go to theCredentials page:

    Go to Credentials

  2. Click the name of the API key that you want to restrict.

  3. In theApplication restrictions section, selectIP addresses.

  4. For each IP address that you want to add, clickAdd an item, enterthe address, and clickDone.

  5. ClickSave 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 getthe 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 torestrict.
    • ALLOWED_IP_ADDR_1: Your allowed IP address.

      You can add as many IP addresses as needed; use commas to separatethe addresses.

    gcloudservicesapi-keysupdateKEY_ID\--allowed-ips="ALLOWED_IP_ADDR_1"

Java

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

importcom.google.api.apikeys.v2.ApiKeysClient;importcom.google.api.apikeys.v2.Key;importcom.google.api.apikeys.v2.Restrictions;importcom.google.api.apikeys.v2.ServerKeyRestrictions;importcom.google.api.apikeys.v2.UpdateKeyRequest;importcom.google.protobuf.FieldMask;importjava.io.IOException;importjava.util.Arrays;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassRestrictApiKeyServer{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(Developer): Before running this sample,//  1. Replace the variable(s) below.StringprojectId="GOOGLE_CLOUD_PROJECT_ID";// ID of the key to restrict. This ID is auto-created during key creation.// This is different from the key string. To obtain the key_id,// you can also use the lookup api: client.lookupKey()StringkeyId="key_id";restrictApiKeyServer(projectId,keyId);}// Restricts the API key based on IP addresses. You can specify one or more IP addresses// of the callers, for example web servers or cron jobs, that are allowed to use your API key.publicstaticvoidrestrictApiKeyServer(StringprojectId,StringkeyId)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the `apiKeysClient.close()` method on the client to safely// clean up any remaining background resources.try(ApiKeysClientapiKeysClient=ApiKeysClient.create()){// Restrict the API key usage by specifying the IP addresses.// You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.Restrictionsrestrictions=Restrictions.newBuilder().setServerKeyRestrictions(ServerKeyRestrictions.newBuilder().addAllAllowedIps(Arrays.asList("198.51.100.0/24","2000:db8::/64")).build()).build();Keykey=Key.newBuilder().setName(String.format("projects/%s/locations/global/keys/%s",projectId,keyId))// Set the restriction(s).// For more information on API key restriction, see:// https://cloud.google.com/docs/authentication/api-keys.setRestrictions(restrictions).build();// Initialize request and set arguments.UpdateKeyRequestupdateKeyRequest=UpdateKeyRequest.newBuilder().setKey(key).setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build()).build();// Make the request and wait for the operation to complete.Keyresult=apiKeysClient.updateKeyAsync(updateKeyRequest).get(3,TimeUnit.MINUTES);// For authenticating with the API key, use the value in "result.getKeyString()".System.out.printf("Successfully updated the API key: %s",result.getName());}}}

Python

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

fromgoogle.cloudimportapi_keys_v2fromgoogle.cloud.api_keys_v2importKeydefrestrict_api_key_server(project_id:str,key_id:str)->Key:"""    Restricts the API key based on IP addresses. You can specify one or more IP addresses of the callers,    for example web servers or cron jobs, that are allowed to use your API key.    TODO(Developer): Replace the variables before running this sample.    Args:        project_id: Google Cloud project id.        key_id: ID of the key to restrict. This ID is auto-created during key creation.            This is different from the key string. To obtain the key_id,            you can also use the lookup api: client.lookup_key()    Returns:        response: Returns the updated API Key.    """# Create the API Keys client.client=api_keys_v2.ApiKeysClient()# Restrict the API key usage by specifying the IP addresses.# You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.server_key_restrictions=api_keys_v2.ServerKeyRestrictions()server_key_restrictions.allowed_ips=["198.51.100.0/24","2000:db8::/64"]# Set the API restriction.# For more information on API key restriction, see:# https://cloud.google.com/docs/authentication/api-keysrestrictions=api_keys_v2.Restrictions()restrictions.server_key_restrictions=server_key_restrictionskey=api_keys_v2.Key()key.name=f"projects/{project_id}/locations/global/keys/{key_id}"key.restrictions=restrictions# Initialize request and set arguments.request=api_keys_v2.UpdateKeyRequest()request.key=keyrequest.update_mask="restrictions"# Make the request and wait for the operation to complete.response=client.update_key(request=request).result()print(f"Successfully updated the API key:{response.name}")# Use response.key_string to authenticate.returnresponse

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 getthe ID by using thekeys.listmethod. The ID is listed in theuid field of the response.

    ReplacePROJECT_ID with your Google Cloud project IDor name.

    curl-XGET\-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 requestreturns along-running operation; you must poll the operation toknow 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 separatethe restrictions. You must provide all IP addresses with therequest; the referrer restrictions provided replace any existingIP address restrictions on the key.

    • PROJECT_ID: Your Google Cloud project ID orname.

    • KEY_ID: The ID of the key that you want torestrict.

    curl-XPATCH\-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 theREST 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 providethe 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 nameand certificate fingerprint by using the following HTTP headers:

  • X-Android-Package
  • X-Android-Cert
Note: Bypassing this restriction is straightforward. If you usethis restriction, you should also add API restrictions and monitor usagecarefully.

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

Console

  1. In the Google Cloud console, go to theCredentials page:

    Go to Credentials

  2. Click the name of the API key that you want to restrict.

  3. In theApplication restrictions section, selectAndroid apps.

  4. For each Android app that you want to add, clickAdd an item and enterthe package name and SHA-1 certificate fingerprint, then clickDone.

  5. ClickSave 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 getthe 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 torestrict.
    • SHA1_FINGERPRINT andPACKAGE_NAME: The appinformation for an Android app that can use the key.

      You can add as many apps as needed; use additional--allowed-application flags.

    gcloudservicesapi-keysupdateKEY_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.

importcom.google.api.apikeys.v2.AndroidApplication;importcom.google.api.apikeys.v2.AndroidKeyRestrictions;importcom.google.api.apikeys.v2.ApiKeysClient;importcom.google.api.apikeys.v2.Key;importcom.google.api.apikeys.v2.Restrictions;importcom.google.api.apikeys.v2.UpdateKeyRequest;importcom.google.protobuf.FieldMask;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassRestrictApiKeyAndroid{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(Developer): Before running this sample,//  1. Replace the variable(s) below.StringprojectId="GOOGLE_CLOUD_PROJECT_ID";// ID of the key to restrict. This ID is auto-created during key creation.// This is different from the key string. To obtain the key_id,// you can also use the lookup api: client.lookupKey()StringkeyId="key_id";restrictApiKeyAndroid(projectId,keyId);}// Restricts an API key based on android applications.// Specifies the Android application that can use the key.publicstaticvoidrestrictApiKeyAndroid(StringprojectId,StringkeyId)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the `apiKeysClient.close()` method on the client to safely// clean up any remaining background resources.try(ApiKeysClientapiKeysClient=ApiKeysClient.create()){// Restrict the API key usage by specifying the allowed android applications.Restrictionsrestrictions=Restrictions.newBuilder().setAndroidKeyRestrictions(AndroidKeyRestrictions.newBuilder().addAllowedApplications(AndroidApplication.newBuilder()// Specify the android application's package name and SHA1 fingerprint..setPackageName("com.google.appname").setSha1Fingerprint("0873D391E987982FBBD30873D391E987982FBBD3").build()).build()).build();Keykey=Key.newBuilder().setName(String.format("projects/%s/locations/global/keys/%s",projectId,keyId))// Set the restriction(s).// For more information on API key restriction, see:// https://cloud.google.com/docs/authentication/api-keys.setRestrictions(restrictions).build();// Initialize request and set arguments.UpdateKeyRequestupdateKeyRequest=UpdateKeyRequest.newBuilder().setKey(key).setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build()).build();// Make the request and wait for the operation to complete.Keyresult=apiKeysClient.updateKeyAsync(updateKeyRequest).get(3,TimeUnit.MINUTES);// For authenticating with the API key, use the value in "result.getKeyString()".System.out.printf("Successfully updated the API key: %s",result.getName());}}}

Python

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

fromgoogle.cloudimportapi_keys_v2fromgoogle.cloud.api_keys_v2importKeydefrestrict_api_key_android(project_id:str,key_id:str)->Key:"""    Restricts an API key based on android applications.    Specifies the Android application that can use the key.    TODO(Developer): Replace the variables before running this sample.    Args:        project_id: Google Cloud project id.        key_id: ID of the key to restrict. This ID is auto-created during key creation.            This is different from the key string. To obtain the key_id,            you can also use the lookup api: client.lookup_key()    Returns:        response: Returns the updated API Key.    """# Create the API Keys client.client=api_keys_v2.ApiKeysClient()# Specify the android application's package name and SHA1 fingerprint.allowed_application=api_keys_v2.AndroidApplication()allowed_application.package_name="com.google.appname"allowed_application.sha1_fingerprint="0873D391E987982FBBD30873D391E987982FBBD3"# Restrict the API key usage by specifying the allowed applications.android_key_restriction=api_keys_v2.AndroidKeyRestrictions()android_key_restriction.allowed_applications=[allowed_application]# Set the restriction(s).# For more information on API key restriction, see:# https://cloud.google.com/docs/authentication/api-keysrestrictions=api_keys_v2.Restrictions()restrictions.android_key_restrictions=android_key_restrictionkey=api_keys_v2.Key()key.name=f"projects/{project_id}/locations/global/keys/{key_id}"key.restrictions=restrictions# Initialize request and set arguments.request=api_keys_v2.UpdateKeyRequest()request.key=keyrequest.update_mask="restrictions"# Make the request and wait for the operation to complete.response=client.update_key(request=request).result()print(f"Successfully updated the API key:{response.name}")# Use response.key_string to authenticate.returnresponse

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 getthe ID by using thekeys.listmethod. The ID is listed in theuid field of the response.

    ReplacePROJECT_ID with your Google Cloud projectID or name.

    curl-XGET\-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 requestreturns along-running operation; you must poll the operation toknow when the operation completes and get the operation status.

    Replace the following values:

    • SHA1_FINGERPRINT_1 andPACKAGE_NAME_1: The appinformation for an Android app that can use the key.

      You can add the information for as many apps as needed; use commas toseparate theAndroidApplicationobjects. You must provide all applications with the request; theapplications provided replace any existing allowed applications on thekey.

    • PROJECT_ID: Your Google Cloud project ID orname.

    • KEY_ID: The ID of the key that you want torestrict.

    curl-XPATCH\-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 theREST 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 thebundle ID of each app.

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

Note: Bypassing this restriction is straightforward. If you usethis restriction, you should also add API restrictions and monitor usagecarefully.

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

Console

  1. In the Google Cloud console, go to theCredentials page:

    Go to Credentials

  2. Click the name of the API key that you want to restrict.

  3. In theApplication restrictions section, selectiOS apps.

  4. For each iOS app that you want to add, clickAdd an item and enterthe bundle ID, then clickDone.

  5. ClickSave 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 getthe 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 torestrict.
    • ALLOWED_BUNDLE_ID: The bundle ID of an iOS appthat you want to be able to use this API key.

      You can add as many bundle IDs as needed; use commas to separate theIDs.

    gcloudservicesapi-keysupdateKEY_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.

importcom.google.api.apikeys.v2.ApiKeysClient;importcom.google.api.apikeys.v2.IosKeyRestrictions;importcom.google.api.apikeys.v2.Key;importcom.google.api.apikeys.v2.Restrictions;importcom.google.api.apikeys.v2.UpdateKeyRequest;importcom.google.protobuf.FieldMask;importjava.io.IOException;importjava.util.Arrays;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassRestrictApiKeyIos{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(Developer): Before running this sample,//  1. Replace the variable(s) below.StringprojectId="GOOGLE_CLOUD_PROJECT_ID";// ID of the key to restrict. This ID is auto-created during key creation.// This is different from the key string. To obtain the key_id,// you can also use the lookup api: client.lookupKey()StringkeyId="key_id";restrictApiKeyIos(projectId,keyId);}// Restricts an API key. You can restrict usage of an API key to specific iOS apps// by providing the bundle ID of each app.publicstaticvoidrestrictApiKeyIos(StringprojectId,StringkeyId)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the `apiKeysClient.close()` method on the client to safely// clean up any remaining background resources.try(ApiKeysClientapiKeysClient=ApiKeysClient.create()){// Restrict the API key usage by specifying the bundle ID(s)// of iOS app(s) that can use the key.Restrictionsrestrictions=Restrictions.newBuilder().setIosKeyRestrictions(IosKeyRestrictions.newBuilder().addAllAllowedBundleIds(Arrays.asList("com.google.gmail","com.google.drive")).build()).build();Keykey=Key.newBuilder().setName(String.format("projects/%s/locations/global/keys/%s",projectId,keyId))// Set the restriction(s).// For more information on API key restriction, see:// https://cloud.google.com/docs/authentication/api-keys.setRestrictions(restrictions).build();// Initialize request and set arguments.UpdateKeyRequestupdateKeyRequest=UpdateKeyRequest.newBuilder().setKey(key).setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build()).build();// Make the request and wait for the operation to complete.Keyresult=apiKeysClient.updateKeyAsync(updateKeyRequest).get(3,TimeUnit.MINUTES);// For authenticating with the API key, use the value in "result.getKeyString()".System.out.printf("Successfully updated the API key: %s",result.getName());}}}

Python

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

fromgoogle.cloudimportapi_keys_v2fromgoogle.cloud.api_keys_v2importKeydefrestrict_api_key_ios(project_id:str,key_id:str)->Key:"""    Restricts an API key. You can restrict usage of an API key to specific iOS apps    by providing the bundle ID of each app.    TODO(Developer): Replace the variables before running this sample.    Args:        project_id: Google Cloud project id.        key_id: ID of the key to restrict. This ID is auto-created during key creation.            This is different from the key string. To obtain the key_id,            you can also use the lookup api: client.lookup_key()    Returns:        response: Returns the updated API Key.    """# Create the API Keys client.client=api_keys_v2.ApiKeysClient()# Restrict the API key usage by specifying the bundle ID(s) of iOS app(s) that can use the key.ios_key_restrictions=api_keys_v2.IosKeyRestrictions()ios_key_restrictions.allowed_bundle_ids=["com.google.gmail","com.google.drive"]# Set the API restriction.# For more information on API key restriction, see:# https://cloud.google.com/docs/authentication/api-keysrestrictions=api_keys_v2.Restrictions()restrictions.ios_key_restrictions=ios_key_restrictionskey=api_keys_v2.Key()key.name=f"projects/{project_id}/locations/global/keys/{key_id}"key.restrictions=restrictions# Initialize request and set arguments.request=api_keys_v2.UpdateKeyRequest()request.key=keyrequest.update_mask="restrictions"# Make the request and wait for the operation to complete.response=client.update_key(request=request).result()print(f"Successfully updated the API key:{response.name}")# Use response.key_string to authenticate.returnresponse

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 getthe ID by using thekeys.listmethod. The ID is listed in theuid field of the response.

    ReplacePROJECT_ID with your Google Cloud projectID or name.

    curl-XGET\-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 requestreturns along-running operation; you must poll the operation toknow when the operation completes and get the operation status.

    Replace the following values:

    • ALLOWED_BUNDLE_ID: The bundle ID of an iOS appthat can use the key.

      You can add the information for as many apps as needed; use commas toseparate the bundle IDs. You must provide all bundle IDs with therequest; the bundle IDs provided replace any existing allowedapplications on the key.

    • PROJECT_ID: Your Google Cloud project ID orname.

    • KEY_ID: The ID of the key that you want torestrict.

    curl-XPATCH\-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 RESTAPI, seeAdding iOS restrictionsin the API Keys API documentation.

Add API restrictions

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

Note: Before you can specify an API for an API restriction, the APImust be enabled for your project. To enable an API, go to theAPI dashboard.

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

Console

  1. In the Google Cloud console, go to theCredentials page:

    Go to Credentials

  2. Click the name of the API key that you want to restrict.

  3. In theAPI restrictions section, clickRestrict key.

  4. Select all APIs that your API key will be used to access.

  5. ClickSave 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 getthe 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 torestrict.
    • 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 servicenames provided replace any existing services on the key.

    You can find the service name by searching for the API on theAPI dashboard. Servicenames are strings likebigquery.googleapis.com.

    gcloudservicesapi-keysupdateKEY_ID\--api-target=service=SERVICE_1--api-target=service=SERVICE_2

Java

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

importcom.google.api.apikeys.v2.ApiKeysClient;importcom.google.api.apikeys.v2.ApiTarget;importcom.google.api.apikeys.v2.Key;importcom.google.api.apikeys.v2.Restrictions;importcom.google.api.apikeys.v2.UpdateKeyRequest;importcom.google.protobuf.FieldMask;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassRestrictApiKeyApi{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(Developer): Before running this sample,//  1. Replace the variable(s) below.StringprojectId="GOOGLE_CLOUD_PROJECT_ID";// ID of the key to restrict. This ID is auto-created during key creation.// This is different from the key string. To obtain the key_id,// you can also use the lookup api: client.lookupKey()StringkeyId="key_id";restrictApiKeyApi(projectId,keyId);}// Restricts an API key. Restrictions specify which APIs can be called using the API key.publicstaticvoidrestrictApiKeyApi(StringprojectId,StringkeyId)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the `apiKeysClient.close()` method on the client to safely// clean up any remaining background resources.try(ApiKeysClientapiKeysClient=ApiKeysClient.create()){// Restrict the API key usage by specifying the target service and methods.// The API key can only be used to authenticate the specified methods in the service.Restrictionsrestrictions=Restrictions.newBuilder().addApiTargets(ApiTarget.newBuilder().setService("translate.googleapis.com").addMethods("translate.googleapis.com.TranslateText").build()).build();Keykey=Key.newBuilder().setName(String.format("projects/%s/locations/global/keys/%s",projectId,keyId))// Set the restriction(s).// For more information on API key restriction, see:// https://cloud.google.com/docs/authentication/api-keys.setRestrictions(restrictions).build();// Initialize request and set arguments.UpdateKeyRequestupdateKeyRequest=UpdateKeyRequest.newBuilder().setKey(key).setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build()).build();// Make the request and wait for the operation to complete.Keyresult=apiKeysClient.updateKeyAsync(updateKeyRequest).get(3,TimeUnit.MINUTES);// For authenticating with the API key, use the value in "result.getKeyString()".System.out.printf("Successfully updated the API key: %s",result.getName());}}}

Python

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

fromgoogle.cloudimportapi_keys_v2fromgoogle.cloud.api_keys_v2importKeydefrestrict_api_key_api(project_id:str,key_id:str)->Key:"""    Restricts an API key. Restrictions specify which APIs can be called using the API key.    TODO(Developer): Replace the variables before running the sample.    Args:        project_id: Google Cloud project id.        key_id: ID of the key to restrict. This ID is auto-created during key creation.            This is different from the key string. To obtain the key_id,            you can also use the lookup api: client.lookup_key()    Returns:        response: Returns the updated API Key.    """# Create the API Keys client.client=api_keys_v2.ApiKeysClient()# Restrict the API key usage by specifying the target service and methods.# The API key can only be used to authenticate the specified methods in the service.api_target=api_keys_v2.ApiTarget()api_target.service="translate.googleapis.com"api_target.methods=["transate.googleapis.com.TranslateText"]# Set the API restriction(s).# For more information on API key restriction, see:# https://cloud.google.com/docs/authentication/api-keysrestrictions=api_keys_v2.Restrictions()restrictions.api_targets=[api_target]key=api_keys_v2.Key()key.name=f"projects/{project_id}/locations/global/keys/{key_id}"key.restrictions=restrictions# Initialize request and set arguments.request=api_keys_v2.UpdateKeyRequest()request.key=keyrequest.update_mask="restrictions"# Make the request and wait for the operation to complete.response=client.update_key(request=request).result()print(f"Successfully updated the API key:{response.name}")# Use response.key_string to authenticate.returnresponse

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 getthe ID by using thekeys.listmethod. The ID is listed in theuid field of the response.

    ReplacePROJECT_ID with your Google Cloud projectID or name.

    curl-XGET\-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 along-running operation; you must poll theoperation to know when the operation completes and get the operationstatus.

    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 servicenames provided replace any existing services on the key.

      You can find the service name by searching for the API on theAPI dashboard. Servicenames are strings likebigquery.googleapis.com.

    • PROJECT_ID: Your Google Cloud project ID orname.

    • KEY_ID: The ID of the key that you want torestrict.

    curl-XPATCH\-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 RESTAPI, 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 withfrom its string.

ReplaceKEY_STRING with the key string you need projectinformation for.

gcloud

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

gcloudservicesapi-keyslookupKEY_STRING

Java

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

importcom.google.api.apikeys.v2.ApiKeysClient;importcom.google.api.apikeys.v2.LookupKeyRequest;importcom.google.api.apikeys.v2.LookupKeyResponse;importjava.io.IOException;publicclassLookupApiKey{publicstaticvoidmain(String[]args)throwsIOException{// TODO(Developer): Before running this sample,//  1. Replace the variable(s) below.//  2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc//  3. Make sure you have the necessary permission to view API keys.// API key string to retrieve the API key name.StringapiKeyString="API_KEY_STRING";lookupApiKey(apiKeyString);}// Retrieves name (full path) of an API key using the API key string.publicstaticvoidlookupApiKey(StringapiKeyString)throwsIOException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the `apiKeysClient.close()` method on the client to safely// clean up any remaining background resources.try(ApiKeysClientapiKeysClient=ApiKeysClient.create()){// Initialize the lookup request and set the API key string.LookupKeyRequestlookupKeyRequest=LookupKeyRequest.newBuilder().setKeyString(apiKeyString).build();// Make the request and obtain the response.LookupKeyResponseresponse=apiKeysClient.lookupKey(lookupKeyRequest);System.out.printf("Successfully retrieved the API key name: %s",response.getName());}}}

Python

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

fromgoogle.cloudimportapi_keys_v2deflookup_api_key(api_key_string:str)->None:"""    Retrieves name (full path) of an API key using the API key string.    TODO(Developer):    1. Before running this sample,      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc    2. Make sure you have the necessary permission to view API keys.    Args:        api_key_string: API key string to retrieve the API key name.    """# Create the API Keys client.client=api_keys_v2.ApiKeysClient()# Initialize the lookup request and set the API key string.lookup_key_request=api_keys_v2.LookupKeyRequest(key_string=api_key_string,# Optionally, you can also set the etag (version).# etag=etag,)# Make the request and obtain the response.lookup_key_response=client.lookup_key(lookup_key_request)print(f"Successfully retrieved the API key name:{lookup_key_response.name}")

REST

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

curl-XGET\-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, youcan create a copy of the existing API key. This operation creates a new API keywith 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 othermethods, follow the steps tocreate an API key, and thenapply the same API key restrictions to the newlygenerated API key.

  1. In the Google Cloud console, go to theCredentials 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. ClickCreate a copy.

  4. Enter a name for the new API key and confirm that the restrictions are correct.

  5. ClickCreate.

Rotate an API key

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

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

The rotation operation is available only in the Google Cloud console. To use othermethods, follow the steps tocreate an API key, and thenapply the same API key restrictions to the newlygenerated API key. After updating your applications to use the new key, youdelete the old key.

  1. In the Google Cloud console, go to theCredentials page:

    Go to Credentials

  2. Click the name of the API key that you want to rotate to open its details page.

  3. ClickRotate key.

  4. Enter a name for the new API key and confirm that the restrictions are correct.

  5. ClickCreate.

  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 thedetails page for the new key. In thePrevious 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 within30 days of deleting the key. After 30 days, you cannot undelete the API key.

Console

  1. In the Google Cloud console, go to theCredentials page:

    Go to Credentials

  2. ClickRestore deleted credentials.

  3. Find the deleted API key that you want to undelete, and clickRestore.

    Undeleting an API key may take a few minutes to propagate. Afterpropagation, 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 getthe 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.

    gcloudservicesapi-keysundeleteKEY_ID

    Replace the following values:

    • KEY_ID: The ID of the key that you want toundelete.

Java

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

importcom.google.api.apikeys.v2.ApiKeysClient;importcom.google.api.apikeys.v2.Key;importcom.google.api.apikeys.v2.UndeleteKeyRequest;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassUndeleteApiKey{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// Project ID or project number of the Google Cloud project.StringprojectId="YOUR_PROJECT_ID";// The API key id to undelete.StringkeyId="YOUR_KEY_ID";undeleteApiKey(projectId,keyId);}// Undeletes an API key.publicstaticvoidundeleteApiKey(StringprojectId,StringkeyId)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.try(ApiKeysClientapiKeysClient=ApiKeysClient.create()){// Initialize the undelete request and set the argument.UndeleteKeyRequestundeleteKeyRequest=UndeleteKeyRequest.newBuilder().setName(String.format("projects/%s/locations/global/keys/%s",projectId,keyId)).build();// Make the request and wait for the operation to complete.KeyundeletedKey=apiKeysClient.undeleteKeyAsync(undeleteKeyRequest).get(3,TimeUnit.MINUTES);System.out.printf("Successfully undeleted the API key: %s",undeletedKey.getName());}}}

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 getthe ID by using thekeys.listmethod, with theshowDeleted query parameter set totrue.The key ID is listed in theuid field of the response.

    ReplacePROJECT_ID with your Google Cloud projectID or name.

    curl-XGET\-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-XPOST\-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 requestreturns along-running operation; you must poll the operation toknow when the operation completes and get the operation status.

    Replace the following values:

    • PROJECT_ID: Your Google Cloud project ID orname.
    • KEY_ID: The ID of the key that you want torestrict.

Determine the API key type

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

Console

  1. In the Google Cloud console, go to theCredentials page:

    Go to Credentials

    If the API key is bound to a service account, the service accountidentifier 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 getthe 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.

    gcloudservicesapi-keysdescribeKEY_ID

    If the API key is bound to a service account, theserviceAccountEmailfield is displayed.

Poll long-running operations

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

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

ReplaceOPERATION_NAME with the operation name returnedby the long-running operation. For example,operations/akmf.p7-358517206116-cd10a88a-7740-4403-a8fd-979f3bd7fe1c.

curl-XGET\-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 limitis 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

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 2025-12-15 UTC.