Manage API keys

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 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:

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.

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.

  1. Install the Google Cloud CLI.

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

  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

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

Java

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

  1. Install the Google Cloud CLI.

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

  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

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

Python

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

  1. Install the Google Cloud CLI.

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

  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

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

REST

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

    Install the Google Cloud CLI.

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

For more information, 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.disableServiceAccountApiKeyCreation organization 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.disableServiceAccountApiKeyCreation organization 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

  1. In the Google Cloud console, go to the Organization policies page.

    Go to Organization policies

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

  3. In the Filter box, enter Block service, and then click the policy 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.

  7. To disable the constraint, set Enforcement to Off.

    To add a service to the allowed list, set Enforcement to On.

    1. Click Edit.

    2. In the Value type section, select User-defined.

    3. Enter the service that you want to allow creating API keys for.

  8. Click Done.

  9. Optional: Click Test changes to give you insight on how the proposed policy might cause compliance violations or disruptions.

  10. Click Set policy.

gcloud

To add a service to the allowed list, do the following:

  1. Create a file named spec.yaml with the following content:

    name: SCOPE/SCOPE_ID/policies/iam.managed.disableServiceAccountApiKeyCreation
    spec:
      rules:
      - enforce: true
        parameters:
          allowedServices:
          - SERVICE_NAME
    

    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.

    • SERVICE_NAME: The name of the service you want to allow—for example, compute.googleapis.com.

  2. Run the following gcloud command 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:

  1. Create a file named spec.yaml with the following content:

    name: SCOPE/SCOPE_ID/policies/iam.managed.disableServiceAccountApiKeyCreation
    spec:
      rules:
      - enforce: false
    
  2. Run the following gcloud command 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

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

    Go to Credentials

  2. Click Create credentials, and then select API key from the menu.

  3. Add at least one API key restriction. For more information, see Apply API key restrictions.

  4. 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.

  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 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 beta instead, with the --service-account flag:

    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_ADDRESS
    

    For more information, see Authorization keys.

C++

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

#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.


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.


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 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-target flag, along with the API restrictions you want to add.

  • REST: The restrictions object to your request body, containing an apiTargets array 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

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

    Go to Credentials

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

  3. In the API restrictions section, click Restrict key.

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

  5. Click Save to save your changes and return to the API key list.

gcloud

  1. Get the ID of the key that you want to restrict.

    The ID is not the same as the display name or the key string. You can get the ID by using the gcloud services api-keys list command to list the keys in your project.

  2. 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.


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;