Introduction to API keys
There are two types of API keys: standard API keys, and authorization keys. Both keys let you associate a request with a project for billing and quota purposes. However, they differ in the following way:
A standard API key doesn't authenticate a principal.
An authorization key authenticates as a service account. It operates in a similar fashion to a long-lived access token.
The Credentials page in the Google Cloud console ensures that the correct type of API key is created for a selected API.
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.
Authorization keys
Authorization keys are API keys that are bound to a service account. When you use an authorization key to access an API, your request is processed as if you used the bound service account to make the request.
APIs that support authorization keys include
Vertex AI
(aiplatform.googleapis.com) and the
Gemini API
(generativelanguage.googleapis.com).
When using authorization keys, keep the following in mind:
Requests authenticated by authorization keys aren't recorded in service account usage metrics.
Binding keys to a service account is prevented by a default organization policy constraint. To change this, see Enable authorization keys.
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
- Authorization keys 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.
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 authorization keys
Before you can create an authorization key, you must do one of the following:
Update the
constraints/iam.managed.disableServiceAccountApiKeyCreationorganization policy constraint to restrict the services that users can create authorization keys for. When creating an authorization key, users must add an API restriction that matches a service allowed by the constraint.Disable the
constraints/iam.managed.disableServiceAccountApiKeyCreationorganization policy constraint.
Changing the organization policy requires an 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.
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 policy name Block service account API key bindings.Click Manage policy.
In the Policy source section, select Override parent's policy.
Click Add a rule.
To disable the constraint, set Enforcement to Off.
To add a service to the allowed list, set Enforcement to On.
Click Edit.
In the Value type section, select User-defined.
Enter the service that you want to allow creating API keys for.
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
To add a service to the allowed list, do the following:
Create a file named
spec.yamlwith the following content:name: SCOPE/SCOPE_ID/policies/iam.managed.disableServiceAccountApiKeyCreation spec: rules: - enforce: true parameters: allowedServices: - SERVICE_NAMEProvide the following values:
SCOPE: Eitherorganizations,folders, orprojects.SCOPE_ID: Depending on SCOPE, the ID of the organization, folder, or project to which the organization policy applies.SERVICE_NAME: The name of the service you want to allow—for example,compute.googleapis.com.
Run the following
gcloudcommand to allow binding of API keys to service accounts for the specified service:gcloud org-policies set-policy spec.yaml \ --update-mask spec
To disable the constraint, do the following:
Create a file named
spec.yamlwith the following content:name: SCOPE/SCOPE_ID/policies/iam.managed.disableServiceAccountApiKeyCreation spec: rules: - enforce: falseRun the following
gcloudcommand to disable the constraint: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:
Click Create credentials, and then select API key from the menu.
Add at least one API key restriction. For more information, see Apply API key restrictions.
Optional: To bind the API key to a service account and create an authorization key, 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 Authorization keys.
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.
gcloud services api-keys create \
--display-name=DISPLAY_NAME \
--api-target=service=SERVICE_1 \
--api-target=service=SERVICE_2
Replace the following values:
DISPLAY_NAME: A descriptive name for your key.SERVICE_1,SERVICE_2...: The service names of the APIs that the key can be used to access.You can find the service name by searching for the API on the API dashboard. Service names are strings like
bigquery.googleapis.com.To bind the API key to a service account and create an authorization key for services such as Vertex AI and the Gemini API, use
gcloud betainstead, with the--service-accountflag:gcloud beta services api-keys create \ --display-name=DISPLAY_NAME \ --api-target=service=SERVICE_1 \ --api-target=service=SERVICE_2 \ --service-account=SERVICE_ACCOUNT_EMAIL_ADDRESSFor more information, see Authorization keys.
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.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d '{
"displayName" : "DISPLAY_NAME",
"restrictions" : {
"apiTargets": [
{
"service": "SERVICE_1"
},
{
"service" : "SERVICE_2"
},
]
}
}' \
"https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys"
Replace the following values:
DISPLAY_NAME: A descriptive name for your key.PROJECT_ID: Your Google Cloud project ID or name.SERVICE_1,SERVICE_2...: The service names of the APIs that the key can be used to access.
You can find the service name by searching for the API on the
API dashboard. Service names are strings
like bigquery.googleapis.com.
Optional: To bind the API key to a service account and create an authorization key 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",
"restrictions" : {
"apiTargets": [
{
"service": "SERVICE_1"
},
{
"service" : "SERVICE_2"
},
]
},
"serviceAccountEmail" : "SERVICE_ACCOUNT_EMAIL_ADDRESS"
}' \
"https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys"
For more information, see Authorization keys.
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
Unrestricted API keys are insecure. To reduce security risks, you can restrict API keys in the following ways:
API restrictions: Limit an API key so it can only be used with a specific set of APIs. API keys without API restrictions can be used with all APIs that accept keys generated by Google Cloud.
Application restrictions: Limit an API key so it can only be used by specific websites, IP addresses, or applications. API keys without application restrictions can be used from anywhere.
We recommend setting both API restrictions and application restrictions.
In the Google Cloud console, you must add at least one API restriction to be able to create an API key. However, when you create API keys using the gcloud CLI or REST API, the keys are unrestricted unless you specify a restriction. To do so, add the following when you create an API key:
The gcloud CLI: The
--api-targetflag, along with the API restrictions you want to add.REST: The
restrictionsobject to your request body, containing anapiTargetsarray that specifies the restrictions you want to add.
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:
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 listcommand to list the keys in your project.Use the
gcloud services api-keys updatecommand 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.