🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 95 (from laksa152)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

📄
INDEXABLE
CRAWLED
5 months ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH5.7 months ago (distributed domain, exempt)
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://docs.cloud.google.com/docs/authentication/api-keys
Last Crawled2025-10-22 18:18:57 (5 months ago)
First Indexednot set
HTTP Status Code200
Meta TitleManage API keys | Authentication | Google Cloud Documentation
Meta Descriptionnull
Meta Canonicalnull
Boilerpipe Text
This page describes how to create, edit, and restrict API keys. For information about how to use API keys to access Google APIs, see Use 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 in express 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, see Enable 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, a Cloud 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. 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 . 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. 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 . 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. 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 . 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, see Authenticate 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, 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 the constraints/iam.managed.disableServiceAccountApiKeyCreation organization policy constraint to false . Changing the organization policy requires an associated organization resource . Projects without an organization aren't supported. To change the policy constraint, complete the following instructions. Console In the Google Cloud console, go to the Organization policies page. Go to Organization policies Switch to the organization, folder, or project you want to change the policies for. In the Filter box, enter Block service , and then click the filter name Block service account API key bindings . Click Manage policy . In the Policy source section, select Override parent's policy . Click Add a rule , and set Enforcement to Off . Click Done . Optional: Click Test changes to give you insight on how the proposed policy might cause compliance violations or disruptions. Click Set policy . gcloud 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: SCOPE : Either organizations , folders , or projects . SCOPE_ID : Depending on SCOPE , the ID of the organization, folder, or project to which the organization policy applies. 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 In the Google Cloud console, go to the Credentials page: Go to Credentials Click Create credentials , and then select API key from the menu. Optional: To bind the API key to a service account, select the Authenticate 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, see API keys bound to a service account . Add API key restrictions. Restricting API keys is a best practice. For more information, see Apply API key restrictions . Click Create . The API key created dialog displays the string for your newly created key. gcloud You use the gcloud 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, see API keys bound to a service account . C++ To run this sample, you must install the API Keys client library . Java To run this sample, you must install the google-cloud-apikeys client library . Python To run this sample, you must install the API Keys client library . REST You use the keys.create method to create an API key. This request returns a long-running operation ; you must poll the operation to get the information for the new key. Replace the following values: DISPLAY_NAME : Optional. A descriptive name for your key. PROJECT_ID : Your Google Cloud project ID or name. 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, see API keys bound to a service account . For more information about creating API keys using the REST API, see Creating 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 and API 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 HTTP referrers 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. HTTP referrers 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 the 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 In the Google Cloud console, go to the Credentials page: Go to Credentials Click the name of the API key that you want to restrict. In the Application restrictions section, select HTTP referrers . For each restriction that you want to add, click Add an item , enter the restriction, and click Done . Click Save to save your changes and return to the API key list. gcloud 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 the gcloud services api-keys list command to list the keys in your project. Use the gcloud services api-keys update command to 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 the google-cloud-apikeys client library . Python To run this sample, you must install the API Keys client library . REST 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 the keys.list method. 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/" Use the keys.patch method 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" \ -- da ta ' { "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, see Adding browser restrictions in the API Keys API documentation. IP Addresses You can specify one or more IP addresses of the callers, such as a web server or cron job, that are allowed to use your API key. You can specify the IP addresses in any of 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 ) Using localhost is not supported for server restrictions. To restrict your API key to specific IP addresses, use one of the following options: Console In the Google Cloud console, go to the Credentials page: Go to Credentials Click the name of the API key that you want to restrict. In the Application restrictions section, select IP addresses . For each IP address that you want to add, click Add an item , enter the address, and click Done . Click Save to save your changes and return to the API key list. gcloud 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 the gcloud services api-keys list command to list the keys in your project. Use the gcloud services api-keys update command to 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 the google-cloud-apikeys client library . Python To run this sample, you must install the API Keys client library . REST 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 the keys.list method. 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/" Use the keys.patch method 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" \ -- da ta ' { "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, see Adding server restrictions in 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: X-Android-Package X-Android-Cert To restrict your API key to one or more Android apps, use one of the following options: Console In the Google Cloud console, go to the Credentials page: Go to Credentials Click the name of the API key that you want to restrict. In the Application restrictions section, select Android apps . 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 . Click Save to save your changes and return to the API key list. gcloud 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 the gcloud services api-keys list command to list the keys in your project. Use the gcloud services api-keys update command to 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 and PACKAGE_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 the google-cloud-apikeys client library . Python To run this sample, you must install the API Keys client library . REST 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 the keys.list method. 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/" Use the keys.patch method 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 and PACKAGE_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 the AndroidApplication objects. 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" \ -- da ta ' { "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, see Adding Android restrictions in 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 In the Google Cloud console, go to the Credentials page: Go to Credentials Click the name of the API key that you want to restrict. In the Application restrictions section, select iOS apps . For each iOS app that you want to add, click Add an item and enter the bundle ID, then click Done . Click Save to save your changes and return to the API key list. gcloud 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 the gcloud services api-keys list command to list the keys in your project. Use the gcloud services api-keys update method 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 the google-cloud-apikeys client library . Python To run this sample, you must install the API Keys client library . REST 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 the keys.list method. 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/" Use the keys.patch method 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" \ -- da ta ' { "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, see Adding iOS restrictions in 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 In the Google Cloud console, go to the Credentials page: Go to Credentials Click the name of the API key that you want to restrict. In the API restrictions section, click Restrict key . Select all APIs that your API key will be used to access. Click Save to save your changes and return to the API key list. gcloud 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 the gcloud services api-keys list command to list the keys in your project. Use the gcloud services api-keys update command to 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 the API 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 the google-cloud-apikeys client library . Python To run this sample, you must install the API Keys client library . REST 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 the keys.list method. 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/" Use the keys.patch method 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 the API 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" \ -- da ta ' { "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, see Adding API restrictions in 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 the gcloud 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 the google-cloud-apikeys client library . Python To run this sample, you must install the API Keys client library . REST You use the lookupKey method to 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 then apply the same API key restrictions to the newly generated API key. In the Google Cloud console, go to the Credentials page: Go to Credentials Click the name of the API key that you want to copy. The API key's details page opens. Click Create a copy . Enter a name for the new API key and confirm that the restrictions are correct. 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 then apply 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. In the Google Cloud console, go to the Credentials page: Go to Credentials Click the name of the API key that you want to rotate to open its details page. Click Rotate key . Enter a name for the new API key and confirm that the restrictions are correct. Click Create . Copy the key string and update your applications to use the new string. 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, click Delete the previous key to delete the old key. If you find that you deleted the old key prematurely, you can undelete 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 In the Google Cloud console, go to the Credentials page: Go to Credentials Click Restore deleted credentials . 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 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 the gcloud services api-keys list --show-deleted command to list the deleted keys in your project. Use the gcloud services api-keys undelete command to 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 the google-cloud-apikeys client library . REST 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 the keys.list method, 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" Use the undelete method 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 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 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 the gcloud services api-keys list command to list the keys in your project. Use the gcloud services api-keys describe command to describe the API key. gcloud services api-keys describe KEY_ID If the API key is bound to a service account, the serviceAccountEmail field 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 the operations.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 1200 application restrictions to an API key. What's next
Markdown
[Skip to main content](https://docs.cloud.google.com/docs/authentication/api-keys#main-content) [![Google Cloud Documentation](https://www.gstatic.com/devrel-devsite/prod/v59c691115ec6a53e3bf17af135bec44a3bb95c23eb778b8c9e469e221a6634ea/clouddocs/images/lockup.svg)](https://docs.cloud.google.com/) [Documentation](https://docs.cloud.google.com/docs) [Technology areas](https://docs.cloud.google.com/docs/tech-area-overviews) - [AI and ML](https://docs.cloud.google.com/docs/ai-ml) - [Application development](https://docs.cloud.google.com/docs/application-development) - [Application hosting](https://docs.cloud.google.com/docs/application-hosting) - [Compute](https://docs.cloud.google.com/docs/compute-area) - [Data analytics and pipelines](https://docs.cloud.google.com/docs/data) - [Databases](https://docs.cloud.google.com/docs/databases) - [Distributed, hybrid, and multicloud](https://docs.cloud.google.com/docs/dhm-cloud) - [Generative AI](https://docs.cloud.google.com/docs/generative-ai) - [Industry solutions](https://docs.cloud.google.com/docs/industry) - [Networking](https://docs.cloud.google.com/docs/networking) - [Observability and monitoring](https://docs.cloud.google.com/docs/observability) - [Security](https://docs.cloud.google.com/docs/security) - [Storage](https://docs.cloud.google.com/docs/storage) [Cross-product tools](https://docs.cloud.google.com/docs/cross-product-overviews) - [Access and resources management](https://docs.cloud.google.com/docs/access-resources) - [Costs and usage management](https://docs.cloud.google.com/docs/costs-usage) - [Google Cloud SDK, languages, frameworks, and tools](https://docs.cloud.google.com/docs/devtools) - [Infrastructure as code](https://docs.cloud.google.com/docs/iac) - [Migration](https://docs.cloud.google.com/docs/migration) [Console](https://console.cloud.google.com/) - [English]() - [Deutsch]() - [Español]() - [Español – América Latina]() - [Français]() - [Indonesia]() - [Italiano]() - [Português]() - [Português – Brasil]() - [中文 – 简体]() - [中文 – 繁體]() - [日本語]() - [한국어]() Sign in [![](https://docs.cloud.google.com/_static/clouddocs/images/icons/categories/devops-color.svg)](https://docs.cloud.google.com/docs/authentication) - [Google Cloud SDK](https://docs.cloud.google.com/sdk/docs) - [Authentication](https://docs.cloud.google.com/docs/authentication) [Start free](https://console.cloud.google.com/freetrial) [Guides](https://docs.cloud.google.com/sdk/docs/install-sdk) [Reference](https://docs.cloud.google.com/sdk/docs/libraries-reference) [Resources](https://docs.cloud.google.com/sdk/docs/resources) [![Google Cloud Documentation](https://www.gstatic.com/devrel-devsite/prod/v59c691115ec6a53e3bf17af135bec44a3bb95c23eb778b8c9e469e221a6634ea/clouddocs/images/lockup.svg)](https://docs.cloud.google.com/) - [Documentation](https://docs.cloud.google.com/docs) - [Guides](https://docs.cloud.google.com/sdk/docs/install-sdk) - [Reference](https://docs.cloud.google.com/sdk/docs/libraries-reference) - [Resources](https://docs.cloud.google.com/sdk/docs/resources) - [Technology areas](https://docs.cloud.google.com/docs/tech-area-overviews) - More - [Cross-product tools](https://docs.cloud.google.com/docs/cross-product-overviews) - More - [Console](https://console.cloud.google.com/) - Discover - [Google Cloud SDK overview](https://docs.cloud.google.com/sdk) - [gcloud CLI overview](https://docs.cloud.google.com/sdk/gcloud) - [Cloud Client Libraries overview](https://docs.cloud.google.com/apis/docs/cloud-client-libraries) - [Client libraries and Cloud APIs explained](https://docs.cloud.google.com/apis/docs/client-libraries-explained) - Get started - [Install the Google Cloud CLI](https://docs.cloud.google.com/sdk/docs/install-sdk) - Other CLI installation methods - [Recommended installation](https://docs.cloud.google.com/sdk/docs/install) - Other installation methods - Using Docker - [Overview](https://docs.cloud.google.com/sdk/docs/downloads-docker) - [Migrate to the :stable image](https://docs.cloud.google.com/sdk/docs/migrate-docker-images) - [Using a snap package](https://docs.cloud.google.com/sdk/docs/downloads-snap) - [Using versioned archives](https://docs.cloud.google.com/sdk/docs/downloads-versioned-archives) - [Using the installer](https://docs.cloud.google.com/sdk/docs/downloads-interactive) - Authenticate to Google Cloud - [Authentication methods at Google](https://docs.cloud.google.com/docs/authentication) - Ways to authenticate - [Authenticate for using client libraries](https://docs.cloud.google.com/docs/authentication/client-libraries) - [Authenticate for using the gcloud CLI](https://docs.cloud.google.com/docs/authentication/gcloud) - [Authenticate for using REST](https://docs.cloud.google.com/docs/authentication/rest) - [Authenticate by using service account impersonation](https://docs.cloud.google.com/docs/authentication/use-service-account-impersonation) - Application Default Credentials - Set up Application Default Credentials - [Overview](https://docs.cloud.google.com/docs/authentication/provide-credentials-adc) - [Local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment) - [Resource with an attached service account](https://docs.cloud.google.com/docs/authentication/set-up-adc-attached-service-account) - [Containerized environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-containerized-environment) - [On-premises or another cloud provider](https://docs.cloud.google.com/docs/authentication/set-up-adc-on-premises) - [Cloud-based development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-cloud-dev-environment) - [How Application Default Credentials works](https://docs.cloud.google.com/docs/authentication/application-default-credentials) - [Troubleshoot your ADC setup](https://docs.cloud.google.com/docs/authentication/troubleshoot-adc) - API keys - [Use API keys to access APIs](https://docs.cloud.google.com/docs/authentication/api-keys-use) - [Manage API keys](https://docs.cloud.google.com/docs/authentication/api-keys) - [Best practices for managing API keys](https://docs.cloud.google.com/docs/authentication/api-keys-best-practices) - [Get an ID token](https://docs.cloud.google.com/docs/authentication/get-id-token) - Tokens - [Overview](https://docs.cloud.google.com/docs/authentication/tokens) - [Token types](https://docs.cloud.google.com/docs/authentication/token-types) - [Multi-factor authentication requirement](https://docs.cloud.google.com/docs/authentication/mfa-requirement) - [Reauthentication](https://docs.cloud.google.com/docs/authentication/reauthentication) - [Authentication use cases](https://docs.cloud.google.com/docs/authentication/use-cases) - [Identity management products](https://docs.cloud.google.com/docs/authentication/identity-products) - Configure the gcloud CLI - [Initialize the gcloud CLI](https://docs.cloud.google.com/sdk/docs/initializing) - [Authorize the gcloud CLI](https://docs.cloud.google.com/sdk/docs/authorizing) - [Configure the gcloud CLI for use behind a proxy or firewall](https://docs.cloud.google.com/sdk/docs/proxy-settings) - [Manage gcloud CLI configurations](https://docs.cloud.google.com/sdk/docs/configurations) - [Manage gcloud CLI properties](https://docs.cloud.google.com/sdk/docs/properties) - [Enable accessibility features](https://docs.cloud.google.com/sdk/docs/enabling-accessibility-features) - Develop - [gcloud CLI cheat sheet](https://docs.cloud.google.com/sdk/docs/cheatsheet) - [Scripting gcloud CLI commands](https://docs.cloud.google.com/sdk/docs/scripting-gcloud) - [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices) - Manage packages in gcloud CLI - [Managing gcloud CLI components](https://docs.cloud.google.com/sdk/docs/components) - [Uninstalling the gcloud CLI](https://docs.cloud.google.com/sdk/docs/uninstall-cloud-sdk) - [AI and ML](https://docs.cloud.google.com/docs/ai-ml) - [Application development](https://docs.cloud.google.com/docs/application-development) - [Application hosting](https://docs.cloud.google.com/docs/application-hosting) - [Compute](https://docs.cloud.google.com/docs/compute-area) - [Data analytics and pipelines](https://docs.cloud.google.com/docs/data) - [Databases](https://docs.cloud.google.com/docs/databases) - [Distributed, hybrid, and multicloud](https://docs.cloud.google.com/docs/dhm-cloud) - [Generative AI](https://docs.cloud.google.com/docs/generative-ai) - [Industry solutions](https://docs.cloud.google.com/docs/industry) - [Networking](https://docs.cloud.google.com/docs/networking) - [Observability and monitoring](https://docs.cloud.google.com/docs/observability) - [Security](https://docs.cloud.google.com/docs/security) - [Storage](https://docs.cloud.google.com/docs/storage) - [Access and resources management](https://docs.cloud.google.com/docs/access-resources) - [Costs and usage management](https://docs.cloud.google.com/docs/costs-usage) - [Google Cloud SDK, languages, frameworks, and tools](https://docs.cloud.google.com/docs/devtools) - [Infrastructure as code](https://docs.cloud.google.com/docs/iac) - [Migration](https://docs.cloud.google.com/docs/migration) - [Home](https://docs.cloud.google.com/) - [Documentation](https://docs.cloud.google.com/docs) - [Application development](https://docs.cloud.google.com/docs/application-development) - [Google Cloud SDK](https://docs.cloud.google.com/sdk/docs) - [Authentication](https://docs.cloud.google.com/docs/authentication) - [Guides](https://docs.cloud.google.com/sdk/docs/install-sdk) Send feedback # Manage API keysStay organized with collections Save and categorize content based on your preferences. This page describes how to create, edit, and restrict API keys. For information about how to use API keys to access Google APIs, see [Use API keys to access APIs](https://docs.cloud.google.com/docs/authentication/api-keys-use). ## 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](https://docs.cloud.google.com/docs/authentication#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 in [express mode](https://cloud.google.com/resources/cloud-express-faqs). ### 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`. **Caution:** API keys bound to service accounts are designed to accelerate the initial experience for developers exploring Google Cloud APIs. Don't use them in production environments. Instead, plan to migrate to more secure alternatives such as [IAM](https://docs.cloud.google.com/iam/docs/grant-role-console) policies and [short-lived service account credentials](https://docs.cloud.google.com/iam/docs/service-account-creds#short-lived-credentials), following least-privilege security practices. Read more about [the risks of API keys bound to service accounts](https://docs.cloud.google.com/docs/authentication/api-keys-best-practices#service-accounts-api-keys). Binding keys to a service account is prevented by a default organization policy constraint. To change this, see [**Enable key binding to service accounts**](https://docs.cloud.google.com/docs/authentication/api-keys#enable-key-binding). **Note:** Requests authenticated by API keys bound to service accounts aren't recorded in [service account usage metrics](https://docs.cloud.google.com/iam/docs/service-account-monitoring). ### 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](https://console.cloud.google.com/?cloudshell=true) At the bottom of the Google Cloud console, a [Cloud Shell](https://docs.cloud.google.com/shell/docs/how-cloud-shell-works) 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](https://docs.cloud.google.com/sdk/docs/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](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud). 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](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud). For more information, see [Set up ADC for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-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](https://docs.cloud.google.com/sdk/docs/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](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud). 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](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud). For more information, see [Set up ADC for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-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](https://docs.cloud.google.com/sdk/docs/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](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud). 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](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud). For more information, see [Set up ADC for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-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. For more information, see [Authenticate for using REST](https://docs.cloud.google.com/docs/authentication/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](https://docs.cloud.google.com/iam/docs/roles-permissions/serviceusage#serviceusage.apiKeysAdmin) (`roles/serviceusage.apiKeysAdmin`) - Restrict an API key to specific APIs by using the Google Cloud console: [Service Usage Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/serviceusage#serviceusage.serviceUsageViewer) (`roles/serviceusage.serviceUsageViewer`) For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access). You might also be able to get the required permissions through [custom roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles) or other [predefined roles](https://docs.cloud.google.com/iam/docs/roles-overview#predefined). ### Enable key binding to service accounts Before you can [bind an API key to a service account](https://docs.cloud.google.com/docs/authentication/api-keys#api-keys-bound-sa), you first need to set the `constraints/iam.managed.disableServiceAccountApiKeyCreation` organization policy constraint to `false`. Changing the organization policy requires an associated [organization resource](https://docs.cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy#organizations). 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](https://console.cloud.google.com/iam-admin/orgpolicies/list) 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: - `SCOPE`: Either `organizations`, `folders`, or `projects`. - `SCOPE_ID`: Depending on SCOPE, the ID of the organization, folder, or project to which the organization policy applies. 2. 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](https://console.cloud.google.com/apis/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 the **Authenticate 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, see [API keys bound to a service account](https://docs.cloud.google.com/docs/authentication/api-keys#api-keys-bound-sa). 4. Add API key restrictions. Restricting API keys is a best practice. For more information, see [Apply API key restrictions](https://docs.cloud.google.com/docs/authentication/api-keys#api_key_restrictions). 5. Click **Create**. The **API key created** dialog displays the string for your newly created key. ### gcloud You use the [`gcloud services api-keys create` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/create) 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, see [API keys bound to a service account](https://docs.cloud.google.com/docs/authentication/api-keys#api-keys-bound-sa). ### C++ To run this sample, you must install the [API Keys client library](https://docs.cloud.google.com/cpp/docs/reference/apikeys/latest). ``` #include "google/cloud/apikeys/v2/api_keys_client.h" #include "google/cloud/location.h" google::api::apikeys::v2::Key CreateApiKey( google::cloud::apikeys_v2::ApiKeysClient client, google::cloud::Location location, std::string display_name) { google::api::apikeys::v2::CreateKeyRequest request; 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. auto key = client.CreateKey(request).get(); if (!key) throw std::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 the [`google-cloud-apikeys` client library](https://docs.cloud.google.com/java/docs/reference/google-cloud-apikeys/latest/overview). ``` import com.google.api.apikeys.v2.ApiKeysClient; import com.google.api.apikeys.v2.ApiTarget; import com.google.api.apikeys.v2.CreateKeyRequest; import com.google.api.apikeys.v2.Key; import com.google.api.apikeys.v2.LocationName; import com.google.api.apikeys.v2.Restrictions; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class CreateApiKey { public static void main(String[] args) throws IOException, 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. String projectId = "GOOGLE_CLOUD_PROJECT_ID"; createApiKey(projectId); } // Creates an API key. public static void createApiKey(String projectId) throws IOException, 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 (ApiKeysClient apiKeysClient = ApiKeysClient.create()) { Key key = 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. CreateKeyRequest createKeyRequest = 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. Key result = 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 the [API Keys client library](https://docs.cloud.google.com/python/docs/reference/apikeys/latest). ``` from google.cloud import api_keys_v2 from google.cloud.api_keys_v2 import Key def create_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". return response ``` ### REST You use the [`keys.create` method](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/create) to create an API key. This request returns a [long-running operation](https://docs.cloud.google.com/docs/authentication/api-keys#lro); you must poll the operation to get the information for the new key. Replace the following values: - `DISPLAY_NAME`: Optional. A descriptive name for your key. - `PROJECT_ID`: Your Google Cloud project ID or name. ``` 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, see [API keys bound to a service account](https://docs.cloud.google.com/docs/authentication/api-keys#api-keys-bound-sa). For more information about creating API keys using the REST API, see [Creating an API key](https://docs.cloud.google.com/api-keys/docs/create-manage-api-keys#create) in the API Keys API documentation. **Important:** Copy your key string and keep it secure. Use API key restrictions to limit how the key can be used. ## 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](https://docs.cloud.google.com/docs/authentication/api-keys#adding-application-restrictions) and [API restrictions](https://docs.cloud.google.com/docs/authentication/api-keys#adding-api-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 | |---|---|---| | [HTTP referrers](https://docs.cloud.google.com/docs/authentication/api-keys#http) | Web applications | Specifies the websites that can use the key. | | [IP Addresses](https://docs.cloud.google.com/docs/authentication/api-keys#ip) | 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](https://docs.cloud.google.com/docs/authentication/api-keys#android) | Android applications | Specifies the Android application that can use the key. | | [iOS apps](https://docs.cloud.google.com/docs/authentication/api-keys#ios) | iOS applications | Specifies the iOS bundles that can use the key. | #### HTTP referrers 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 the 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](https://developer.chrome.com/blog/referrer-policy-new-chrome-default/) 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](https://console.cloud.google.com/apis/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 the [`gcloud services api-keys list` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/list) to list the keys in your project. 2. Use the [`gcloud services api-keys update` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/update) to 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 the [`google-cloud-apikeys` client library](https://docs.cloud.google.com/java/docs/reference/google-cloud-apikeys/latest/overview). ``` import com.google.api.apikeys.v2.ApiKeysClient; import com.google.api.apikeys.v2.BrowserKeyRestrictions; import com.google.api.apikeys.v2.Key; import com.google.api.apikeys.v2.Restrictions; import com.google.api.apikeys.v2.UpdateKeyRequest; import com.google.protobuf.FieldMask; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class RestrictApiKeyHttp { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException, TimeoutException { // TODO(Developer): Before running this sample, // 1. Replace the variable(s) below. String projectId = "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() String keyId = "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. public static void restrictApiKeyHttp(String projectId, String keyId) throws IOException, 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 (ApiKeysClient apiKeysClient = ApiKeysClient.create()) { // Restrict the API key usage to specific websites by adding them // to the list of allowed_referrers. Restrictions restrictions = Restrictions.newBuilder() .setBrowserKeyRestrictions(BrowserKeyRestrictions.newBuilder() .addAllowedReferrers("www.example.com/*") .build()) .build(); Key key = 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. UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder() .setKey(key) .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build()) .build(); // Make the request and wait for the operation to complete. Key result = 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 the [API Keys client library](https://docs.cloud.google.com/python/docs/reference/apikeys/latest). ``` from google.cloud import api_keys_v2 from google.cloud.api_keys_v2 import Key def restrict_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-keys restrictions = api_keys_v2.Restrictions() restrictions.browser_key_restrictions = browser_key_restrictions 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 = key request.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. return response ``` ### 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 the [keys.list](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/list) method. 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 the [keys.patch](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/patch) method to add HTTP referrer restrictions to the API key. This request returns a [long-running operation](https://docs.cloud.google.com/docs/authentication/api-keys#lro); 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, see [Adding browser restrictions](https://docs.cloud.google.com/api-keys/docs/add-restrictions-api-keys#adding_browser_restrictions) in the API Keys API documentation. #### IP Addresses You can specify one or more IP addresses of the callers, such as a web server or cron job, that are allowed to use your API key. You can specify the IP addresses in any of 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`) Using `localhost` is not supported for server restrictions. To restrict your API key to specific IP addresses, use one of the following options: ### Console 1. In the Google Cloud console, go to the **Credentials** page: [Go to Credentials](https://console.cloud.google.com/apis/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 the [`gcloud services api-keys list` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/list) to list the keys in your project. 2. Use the [`gcloud services api-keys update` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/update) to 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 the [`google-cloud-apikeys` client library](https://docs.cloud.google.com/java/docs/reference/google-cloud-apikeys/latest/overview). ``` import com.google.api.apikeys.v2.ApiKeysClient; import com.google.api.apikeys.v2.Key; import com.google.api.apikeys.v2.Restrictions; import com.google.api.apikeys.v2.ServerKeyRestrictions; import com.google.api.apikeys.v2.UpdateKeyRequest; import com.google.protobuf.FieldMask; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class RestrictApiKeyServer { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException, TimeoutException { // TODO(Developer): Before running this sample, // 1. Replace the variable(s) below. String projectId = "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() String keyId = "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. public static void restrictApiKeyServer(String projectId, String keyId) throws IOException, 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 (ApiKeysClient apiKeysClient = 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. Restrictions restrictions = Restrictions.newBuilder() .setServerKeyRestrictions(ServerKeyRestrictions.newBuilder() .addAllAllowedIps(Arrays.asList("198.51.100.0/24", "2000:db8::/64")) .build()) .build(); Key key = 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. UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder() .setKey(key) .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build()) .build(); // Make the request and wait for the operation to complete. Key result = 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 the [API Keys client library](https://docs.cloud.google.com/python/docs/reference/apikeys/latest). ``` from google.cloud import api_keys_v2 from google.cloud.api_keys_v2 import Key def restrict_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-keys restrictions = api_keys_v2.Restrictions() restrictions.server_key_restrictions = server_key_restrictions 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 = key request.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. return response ``` ### 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 the [keys.list](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/list) method. 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 the [keys.patch](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/patch) method to add server (IP address) restrictions to an API key. This request returns a [long-running operation](https://docs.cloud.google.com/docs/authentication/api-keys#lro); 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, see [Adding server restrictions](https://docs.cloud.google.com/api-keys/docs/add-restrictions-api-keys#adding_server_restrictions) in 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: - `X-Android-Package` - `X-Android-Cert` **Note:** Bypassing this restriction is straightforward. If you use this restriction, you should also add API restrictions and monitor usage carefully. 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](https://console.cloud.google.com/apis/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 the [`gcloud services api-keys list` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/list) to list the keys in your project. 2. Use the [`gcloud services api-keys update` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/update) to 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` and `PACKAGE_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 the [`google-cloud-apikeys` client library](https://docs.cloud.google.com/java/docs/reference/google-cloud-apikeys/latest/overview). ``` import com.google.api.apikeys.v2.AndroidApplication; import com.google.api.apikeys.v2.AndroidKeyRestrictions; import com.google.api.apikeys.v2.ApiKeysClient; import com.google.api.apikeys.v2.Key; import com.google.api.apikeys.v2.Restrictions; import com.google.api.apikeys.v2.UpdateKeyRequest; import com.google.protobuf.FieldMask; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class RestrictApiKeyAndroid { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException, TimeoutException { // TODO(Developer): Before running this sample, // 1. Replace the variable(s) below. String projectId = "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() String keyId = "key_id"; restrictApiKeyAndroid(projectId, keyId); } // Restricts an API key based on android applications. // Specifies the Android application that can use the key. public static void restrictApiKeyAndroid(String projectId, String keyId) throws IOException, 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 (ApiKeysClient apiKeysClient = ApiKeysClient.create()) { // Restrict the API key usage by specifying the allowed android applications. Restrictions restrictions = 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(); Key key = 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. UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder() .setKey(key) .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build()) .build(); // Make the request and wait for the operation to complete. Key result = 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 the [API Keys client library](https://docs.cloud.google.com/python/docs/reference/apikeys/latest). ``` from google.cloud import api_keys_v2 from google.cloud.api_keys_v2 import Key def restrict_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-keys restrictions = api_keys_v2.Restrictions() restrictions.android_key_restrictions = android_key_restriction 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 = key request.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. return response ``` ### 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 the [keys.list](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/list) method. 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 the [keys.patch](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/patch) method to specify the Android apps that can use an API key. This request returns a [long-running operation](https://docs.cloud.google.com/docs/authentication/api-keys#lro); you must poll the operation to know when the operation completes and get the operation status. Replace the following values: - `SHA1_FINGERPRINT_1` and `PACKAGE_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 the [AndroidApplication](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys#AndroidApplication) objects. 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, see [Adding Android restrictions](https://docs.cloud.google.com/api-keys/docs/add-restrictions-api-keys#adding_android_restrictions) in 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. **Note:** Bypassing this restriction is straightforward. If you use this restriction, you should also add API restrictions and monitor usage carefully. 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](https://console.cloud.google.com/apis/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 the [`gcloud services api-keys list` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/list) to list the keys in your project. 2. Use the [`gcloud services api-keys update`](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/update) method 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 the [`google-cloud-apikeys` client library](https://docs.cloud.google.com/java/docs/reference/google-cloud-apikeys/latest/overview). ``` import com.google.api.apikeys.v2.ApiKeysClient; import com.google.api.apikeys.v2.IosKeyRestrictions; import com.google.api.apikeys.v2.Key; import com.google.api.apikeys.v2.Restrictions; import com.google.api.apikeys.v2.UpdateKeyRequest; import com.google.protobuf.FieldMask; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class RestrictApiKeyIos { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException, TimeoutException { // TODO(Developer): Before running this sample, // 1. Replace the variable(s) below. String projectId = "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() String keyId = "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. public static void restrictApiKeyIos(String projectId, String keyId) throws IOException, 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 (ApiKeysClient apiKeysClient = ApiKeysClient.create()) { // Restrict the API key usage by specifying the bundle ID(s) // of iOS app(s) that can use the key. Restrictions restrictions = Restrictions.newBuilder() .setIosKeyRestrictions(IosKeyRestrictions.newBuilder() .addAllAllowedBundleIds(Arrays.asList("com.google.gmail", "com.google.drive")) .build()) .build(); Key key = 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. UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder() .setKey(key) .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build()) .build(); // Make the request and wait for the operation to complete. Key result = 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 the [API Keys client library](https://docs.cloud.google.com/python/docs/reference/apikeys/latest). ``` from google.cloud import api_keys_v2 from google.cloud.api_keys_v2 import Key def restrict_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-keys restrictions = api_keys_v2.Restrictions() restrictions.ios_key_restrictions = ios_key_restrictions 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 = key request.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. return response ``` ### 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 the [keys.list](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/list) method. 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 the [keys.patch](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/patch) method to specify the iOS apps that can use an API key. This request returns a [long-running operation](https://docs.cloud.google.com/docs/authentication/api-keys#lro); 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, see [Adding iOS restrictions](https://docs.cloud.google.com/api-keys/docs/add-restrictions-api-keys#adding_ios_restrictions) in 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 API must be enabled for your project. To enable an API, go to the [API dashboard](https://console.cloud.google.com/apis/dashboard). 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](https://console.cloud.google.com/apis/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 the [`gcloud services api-keys list` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/list) to list the keys in your project. 2. Use the [`gcloud services api-keys update` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/update) to 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 the [API dashboard](https://console.cloud.google.com/apis/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 the [`google-cloud-apikeys` client library](https://docs.cloud.google.com/java/docs/reference/google-cloud-apikeys/latest/overview). ``` import com.google.api.apikeys.v2.ApiKeysClient; import com.google.api.apikeys.v2.ApiTarget; import com.google.api.apikeys.v2.Key; import com.google.api.apikeys.v2.Restrictions; import com.google.api.apikeys.v2.UpdateKeyRequest; import com.google.protobuf.FieldMask; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class RestrictApiKeyApi { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException, TimeoutException { // TODO(Developer): Before running this sample, // 1. Replace the variable(s) below. String projectId = "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() String keyId = "key_id"; restrictApiKeyApi(projectId, keyId); } // Restricts an API key. Restrictions specify which APIs can be called using the API key. public static void restrictApiKeyApi(String projectId, String keyId) throws IOException, 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 (ApiKeysClient apiKeysClient = 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. Restrictions restrictions = Restrictions.newBuilder() .addApiTargets(ApiTarget.newBuilder() .setService("translate.googleapis.com") .addMethods("translate.googleapis.com.TranslateText") .build()) .build(); Key key = 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. UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder() .setKey(key) .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build()) .build(); // Make the request and wait for the operation to complete. Key result = 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 the [API Keys client library](https://docs.cloud.google.com/python/docs/reference/apikeys/latest). ``` from google.cloud import api_keys_v2 from google.cloud.api_keys_v2 import Key def restrict_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-keys restrictions = 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 = key request.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. return response ``` ### 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 the [keys.list](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/list) method. 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 the [keys.patch](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/patch) method to specify which services an API key can be used to access. This request returns a [long-running operation](https://docs.cloud.google.com/docs/authentication/api-keys#lro); 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 the [API dashboard](https://console.cloud.google.com/apis/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, see [Adding API restrictions](https://docs.cloud.google.com/api-keys/docs/add-restrictions-api-keys#add-api-restrictions) in 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 the [`gcloud services api-keys lookup` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/lookup) to get the project ID from a key string. ``` gcloud services api-keys lookup KEY_STRING ``` ### Java To run this sample, you must install the [`google-cloud-apikeys` client library](https://docs.cloud.google.com/java/docs/reference/google-cloud-apikeys/latest/overview). ``` import com.google.api.apikeys.v2.ApiKeysClient; import com.google.api.apikeys.v2.LookupKeyRequest; import com.google.api.apikeys.v2.LookupKeyResponse; import java.io.IOException; public class LookupApiKey { public static void main(String[] args) throws IOException { // 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. String apiKeyString = "API_KEY_STRING"; lookupApiKey(apiKeyString); } // Retrieves name (full path) of an API key using the API key string. public static void lookupApiKey(String apiKeyString) throws IOException { // 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 (ApiKeysClient apiKeysClient = ApiKeysClient.create()) { // Initialize the lookup request and set the API key string. LookupKeyRequest lookupKeyRequest = LookupKeyRequest.newBuilder() .setKeyString(apiKeyString) .build(); // Make the request and obtain the response. LookupKeyResponse response = apiKeysClient.lookupKey(lookupKeyRequest); System.out.printf("Successfully retrieved the API key name: %s", response.getName()); } } } ``` ### Python To run this sample, you must install the [API Keys client library](https://docs.cloud.google.com/python/docs/reference/apikeys/latest). ``` from google.cloud import api_keys_v2 def lookup_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 the [`lookupKey` method](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/keys/lookupKey) to 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](https://docs.cloud.google.com/docs/authentication/api-keys#create), and then [apply the same API key restrictions](https://docs.cloud.google.com/docs/authentication/api-keys#adding-api-restrictions) to the newly generated API key. 1. In the Google Cloud console, go to the **Credentials** page: [Go to Credentials](https://console.cloud.google.com/apis/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](https://docs.cloud.google.com/docs/authentication/api-keys#create), and then [apply the same API key restrictions](https://docs.cloud.google.com/docs/authentication/api-keys#adding-api-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](https://console.cloud.google.com/apis/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, click **Delete the previous key** to delete the old key. If you find that you deleted the old key prematurely, you can [undelete it](https://docs.cloud.google.com/docs/authentication/api-keys#undelete). ## 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](https://console.cloud.google.com/apis/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 the [`gcloud services api-keys list --show-deleted` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/list) to list the deleted keys in your project. 2. Use the [`gcloud services api-keys undelete` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/undelete) to 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 the [`google-cloud-apikeys` client library](https://docs.cloud.google.com/java/docs/reference/google-cloud-apikeys/latest/overview). ``` import com.google.api.apikeys.v2.ApiKeysClient; import com.google.api.apikeys.v2.Key; import com.google.api.apikeys.v2.UndeleteKeyRequest; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class UndeleteApiKey { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException, TimeoutException { // TODO(developer): Replace these variables before running the sample. // Project ID or project number of the Google Cloud project. String projectId = "YOUR_PROJECT_ID"; // The API key id to undelete. String keyId = "YOUR_KEY_ID"; undeleteApiKey(projectId, keyId); } // Undeletes an API key. public static void undeleteApiKey(String projectId, String keyId) throws IOException, 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 (ApiKeysClient apiKeysClient = ApiKeysClient.create()) { // Initialize the undelete request and set the argument. UndeleteKeyRequest undeleteKeyRequest = UndeleteKeyRequest.newBuilder() .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId)) .build(); // Make the request and wait for the operation to complete. Key undeletedKey = 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 get the ID by using the [keys.list](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/list) method, 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 the [undelete](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/projects.locations.keys/undelete) method 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](https://docs.cloud.google.com/docs/authentication/api-keys#lro); 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](https://console.cloud.google.com/apis/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 the [`gcloud services api-keys list` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/list) to list the keys in your project. 2. Use the [`gcloud services api-keys describe` command](https://docs.cloud.google.com/sdk/gcloud/reference/services/api-keys/describe) to describe the API key. ``` gcloud services api-keys describe KEY_ID ``` If the API key is bound to a service account, the `serviceAccountEmail` field 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 the [`operations.get`](https://docs.cloud.google.com/api-keys/docs/reference/rest/v2/operations/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 1200 [application restrictions](https://docs.cloud.google.com/docs/authentication/api-keys#adding-application-restrictions) to an API key. ## What's next - Learn about [best practices for keeping your API keys secure](https://docs.cloud.google.com/docs/authentication/api-keys-best-practices). - Learn more about the [API Keys API](https://docs.cloud.google.com/api-keys/docs/overview). Send feedback Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2025-10-16 UTC. Need to tell us more? \[\[\["Easy to understand","easyToUnderstand","thumb-up"\],\["Solved my problem","solvedMyProblem","thumb-up"\],\["Other","otherUp","thumb-up"\]\],\[\["Hard to understand","hardToUnderstand","thumb-down"\],\["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"\],\["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"\],\["Other","otherDown","thumb-down"\]\],\["Last updated 2025-10-16 UTC."\],\[\],\[\]\] - ### Products and pricing - [See all products](https://cloud.google.com/products/) - [Google Cloud pricing](https://cloud.google.com/pricing/) - [Google Cloud Marketplace](https://cloud.google.com/marketplace/) - [Contact sales](https://cloud.google.com/contact/) - ### Support - [Google Cloud Community](https://www.googlecloudcommunity.com/) - [Support](https://cloud.google.com/support-hub/) - [Release Notes](https://cloud.google.com/release-notes) - [System status](https://status.cloud.google.com/) - ### Resources - [GitHub](https://github.com/googlecloudPlatform/) - [Getting Started with Google Cloud](https://docs.cloud.google.com/docs/get-started/) - [Code samples](https://docs.cloud.google.com/docs/samples) - [Cloud Architecture Center](https://docs.cloud.google.com/architecture/) - [Training and Certification](https://cloud.google.com/learn/training/) - ### Engage - [Blog](https://cloud.google.com/blog/) - [Events](https://cloud.google.com/events/) - [X (Twitter)](https://x.com/googlecloud) - [Google Cloud on YouTube](https://www.youtube.com/googlecloud) - [Google Cloud Tech on YouTube](https://www.youtube.com/googlecloudplatform) - [About Google](https://about.google/) - [Privacy](https://policies.google.com/privacy) - [Site terms](https://policies.google.com/terms?hl=en) - [Google Cloud terms](https://docs.cloud.google.com/product-terms/) - [Manage cookies](https://docs.cloud.google.com/docs/authentication/api-keys) - [Our third decade of climate action: join us](https://cloud.google.com/sustainability) - Sign up for the Google Cloud newsletter [Subscribe](https://cloud.google.com/newsletter/) - [English]() - [Deutsch]() - [Español]() - [Español – América Latina]() - [Français]() - [Indonesia]() - [Italiano]() - [Português]() - [Português – Brasil]() - [中文 – 简体]() - [中文 – 繁體]() - [日本語]() - [한국어]()
Readable Markdownnull
Shard95 (laksa)
Root Hash744624608793826895
Unparsed URLcom,google!cloud,docs,/docs/authentication/api-keys s443