Cara menggunakan google-sheets-api python github

I'm a self-taught web developer from India. I enjoy learning about new web technologies and working on projects. I hope that my work will assist other developers who are experiencing the same difficulties that I am.

This page describes how to use API keys to authenticate to Google Cloud APIs and services that support API keys.

Most Google Cloud APIs don't support API keys. Check that the API that you want to use supports API keys before using this authentication method.

For information about using API keys to authenticate to Google Maps Platform, see the Google Maps Platform documentation. For more information about the API Keys API, see the API Keys API documentation.

Introduction to API keys

When you use an API key to authenticate to an API, the API key does not identify a , nor does it provide any information. The API key associates the request with a Google Cloud project for billing and quota purposes. Because API keys do not identify the caller, they are often used for accessing public data or resources.

Many Google Cloud APIs do not accept API keys for authentication. Review the authentication documentation for the service or API that you want to use to determine whether it supports API keys.

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

StringThe API key string is an encrypted string, for example,

from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

    # 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
7. When you use an API key to authenticate, you always use the key's string. API keys do not have an associated JSON file.IDThe API key ID is used by Google Cloud administrative tools to uniquely identify the key. The key ID cannot be used to authenticate. 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 nameThe display name is an optional, descriptive name for the key, which you can set when you create or update the key.

To manage API keys, you must have the API Keys Admin role (


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

    # 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
8) on the project.

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, then select API key from the menu.

    The API key created dialog displays the string for your newly created key.

gcloud

You use the gcloud alpha services api-keys create command to create an API key.

Replace


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

    # 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
9 with a descriptive name for your key.

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

REST

You use the keys.create method to create an API key. This request returns a ; you must poll the operation to get the information for the new key.

Replace the following values:

  • 
    from google.cloud import api_keys_v2
    from google.cloud.api_keys_v2 import Key
    
    
    def create_api_key(project_id: str) -> Key:
        """
        Creates and restrict an API key.
    
        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 = "My first API key"
    
        # 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
    
    9: Optional. A descriptive name for your key.
  • POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
    1: 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"

For more information about creating API keys using the REST API, see in the API Key API documentation.

Java

To run this sample, you must install the

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
2 client.

auth/src/main/java/CreateApiKey.java

View on GitHub


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 Python Client for API Keys API.

auth/api-client/create_api_key.py

View on GitHub


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

    # 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

Copy your key string and keep it secure. Unless you're using a testing key that you intend to delete later, add .

Use an API key

If an API supports the use of API keys, You can use API keys to authenticate that API. You use API keys with and with that support them.

Using an API key with REST

You can pass the API key into a REST API call as a query parameter with the following format. Replace

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
3 with the key string of your API key.

For example, to pass an API key for a Cloud Natural Language API request for

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
4:

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY

Alternatively, you can use the

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
5 header to pass in your key. This header must be used with gRPC requests.

curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "X-goog-api-key: API_KEY" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://translation.googleapis.com/language/translate/v2"

Using an API key with client libraries

Client library support for API keys is language-specific.

Python

This example uses the Cloud Natural Language API, which supports API keys for authentication, to demonstrate how you would provide an API key to the library.

To run this sample, you must install the Python Client for Natural Language API and the Python Client for API Keys API.

auth/api-client/authenticate_with_api_key.py

View on GitHub


from google.cloud import language_v1


def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
    """
    Authenticates with an API key for Google Language service.

    TODO(Developer): Replace these variables before running the sample.

    Args:
        quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
        api_key_string: The API key to authenticate to the service.
    """

    # Initialize the Language Service client and set the API key and the quota project id.
    client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                               "quota_project_id": quota_project_id})

    text = "Hello, world!"
    document = language_v1.Document(
        content=text, type_=language_v1.Document.Type.PLAIN_TEXT
    )

    # Make a request to analyze the sentiment of the text.
    sentiment = client.analyze_sentiment(
        request={"document": document}
    ).document_sentiment

    print(f"Text: {text}")
    print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
    print("Successfully authenticated using the API key")

Secure an API key

When you use API keys in your applications, ensure that they are kept secure during both storage and transmission. Publicly exposing your API keys can lead to unexpected charges on your account. To help keep your API keys secure, follow these best practices:

  • Add to your key.

    By adding restrictions, you can limit the ways an API key can be used, reducing the impact of a compromised API key.

  • Delete unneeded API keys to minimize exposure to attacks.

  • Recreate your API keys periodically.

    Periodically create new API keys, delete the old keys, and update your applications to use the new API keys.

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

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:

OptionApplication typeNotesWeb applicationsSpecifies the websites that can use the key.Applications called by specific serversSpecifies the servers or cron jobs that can use the key.Android applicationsSpecifies the Android application that can use the key.iOS applicationsSpecifies 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 (

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
6) for the subdomain or the path, but you cannot insert a wildcard character into the middle of the URL. For example,
POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
7 is valid, and accepts all sites ending in
POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
8. However,
POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
9 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 do not specify a port number, then requests from any port number are matched.

You can add up to 1200 HTTP referrers to an API key.

The following table shows some example scenarios and browser restrictions:

ScenarioRestrictionsAllow a specific URLAdd a URL with an exact path. For example:
curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "X-goog-api-key: API_KEY" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://translation.googleapis.com/language/translate/v2"
0
curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "X-goog-api-key: API_KEY" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://translation.googleapis.com/language/translate/v2"
1
Allow any URL in your siteYou must set two URLs in the
curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "X-goog-api-key: API_KEY" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://translation.googleapis.com/language/translate/v2"
2 list.
  1. URL for the domain, without a subdomain, and with a wildcard for the path. For example:
    curl -X POST \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "X-goog-api-key: API_KEY" \
        -H "Content-Type: application/json; charset=utf-8" \
        -d @request.json \
        "https://translation.googleapis.com/language/translate/v2"
    
    3
  2. A second URL that includes a wildcard for the subdomain and a wildcard for the path. For example:
    curl -X POST \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "X-goog-api-key: API_KEY" \
        -H "Content-Type: application/json; charset=utf-8" \
        -d @request.json \
        "https://translation.googleapis.com/language/translate/v2"
    
    4
Allow any URL in a single subdomain or naked domain

You must set two URLs in the

curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "X-goog-api-key: API_KEY" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://translation.googleapis.com/language/translate/v2"
2 list to allow an entire domain:

  1. URL for the domain, without a trailing slash. For example:
    curl -X POST \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "X-goog-api-key: API_KEY" \
        -H "Content-Type: application/json; charset=utf-8" \
        -d @request.json \
        "https://translation.googleapis.com/language/translate/v2"
    
    6
    curl -X POST \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "X-goog-api-key: API_KEY" \
        -H "Content-Type: application/json; charset=utf-8" \
        -d @request.json \
        "https://translation.googleapis.com/language/translate/v2"
    
    7
    curl -X POST \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "X-goog-api-key: API_KEY" \
        -H "Content-Type: application/json; charset=utf-8" \
        -d @request.json \
        "https://translation.googleapis.com/language/translate/v2"
    
    8
  2. A second URL for the domain that includes a wildcard for the path. For example:
    curl -X POST \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "X-goog-api-key: API_KEY" \
        -H "Content-Type: application/json; charset=utf-8" \
        -d @request.json \
        "https://translation.googleapis.com/language/translate/v2"
    
    9
    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    0
    curl -X POST \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "X-goog-api-key: API_KEY" \
        -H "Content-Type: application/json; charset=utf-8" \
        -d @request.json \
        "https://translation.googleapis.com/language/translate/v2"
    
    3

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

Console

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

    Go to Credentials

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

  3. In the Application restrictions section, select HTTP referrers.

  4. For each restriction that you want to add, click Add an item, enter the restriction, and click Done.

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

gcloud

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

    The ID is not the same as the display name or the key string. You can get the ID by using the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    2 command to list the keys in your project.

  2. Use the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    3 command to add HTTP referrer restrictions to an API key.

    Replace the following values:

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      4: The ID of the key that you want to restrict.
    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      5: 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 alpha services api-keys update KEY_ID \
     --allowed-referrers="ALLOWED_REFERRER_1"
    

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 method. The ID is listed in the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    6 field of the response.

    Replace

    POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
    1 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 method to add HTTP referrer restrictions to the API key.

    This request returns a ; you must poll the operation to know when the operation completes and get the operation status.

    Replace the following values:

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      5: 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.

    • POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
      1: Your Google Cloud project ID or name.

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      4: 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 in the API Key API documentation.

Java

To run this sample, you must install the

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
2 client.

auth/src/main/java/RestrictApiKeyHttp.java

View on GitHub

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"
0

Python

To run this sample, you must install the Python Client for API Keys API.

auth/api-client/restrict_api_key_http.py

View on GitHub

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"
1

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 (
    gcloud alpha services api-keys update KEY_ID \
     --allowed-referrers="ALLOWED_REFERRER_1"
    
    2)
  • IPv6 (
    gcloud alpha services api-keys update KEY_ID \
     --allowed-referrers="ALLOWED_REFERRER_1"
    
    3)
  • A subnet using CIDR notation (
    gcloud alpha services api-keys update KEY_ID \
     --allowed-referrers="ALLOWED_REFERRER_1"
    
    4,
    gcloud alpha services api-keys update KEY_ID \
     --allowed-referrers="ALLOWED_REFERRER_1"
    
    5)

Using

gcloud alpha services api-keys update KEY_ID \
 --allowed-referrers="ALLOWED_REFERRER_1"
6 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

  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

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    2 command to list the keys in your project.

  2. Use the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    3 command to add server (IP address) restrictions to an API key.

    Replace the following values:

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      4: The ID of the key that you want to restrict.
    • curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
      
      0: Your allowed IP address.

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

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

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 method. The ID is listed in the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    6 field of the response.

    Replace

    POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
    1 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 method to add server (IP address) restrictions to an API key.

    This request returns a ; you must poll the operation to know when the operation completes and get the operation status.

    Replace the following values:

    • curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
      
      0: 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.

    • POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
      1: Your Google Cloud project ID or name.

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      4: The ID of the key that you want to restrict.

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

For more information about adding IP address restrictions to a key using the REST API, see in the API Key API documentation.

Java

To run this sample, you must install the

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
2 client.

auth/src/main/java/RestrictApiKeyServer.java

View on GitHub

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"
5

Python

To run this sample, you must install the Python Client for API Keys API.

auth/api-client/restrict_api_key_server.py

View on GitHub

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"
6

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.

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

Console

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

    Go to Credentials

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

  3. In the Application restrictions section, select Android apps.

  4. For each Android app that you want to add, click Add an item and enter the package name and SHA-1 certificate fingerprint, then click Done.

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

gcloud

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

    The ID is not the same as the display name or the key string. You can get the ID by using the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    2 command to list the keys in your project.

  2. Use the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    3 command to specify the Android apps that can use an API key.

    Replace the following values:

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      4: 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"
      
      0 and
      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"
      
      1: The app information for an Android app that can use the key.

      You can add as many apps as needed; use additional

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

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

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 method. The ID is listed in the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    6 field of the response.

    Replace

    POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
    1 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 method to specify the Android apps that can use an API key.

    This request returns a ; you must poll the operation to know when the operation completes and get the operation status.

    Replace the following values:

    • 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"
      
      5 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 objects. You must provide all applications with the request; the applications provided replace any existing allowed applications on the key.

    • POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
      1: Your Google Cloud project ID or name.

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      4: The ID of the key that you want to restrict.

    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"
    
    9

For more information about adding Android app restrictions to a key using the REST API, see in the API Key API documentation.

Java

To run this sample, you must install the

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
2 client.

auth/src/main/java/RestrictApiKeyAndroid.java

View on GitHub


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());
    }
  }
}
0

Python

To run this sample, you must install the Python Client for API Keys API.

auth/api-client/restrict_api_key_android.py

View on GitHub


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());
    }
  }
}
1

iOS apps

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

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

Console

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

    Go to Credentials

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

  3. In the Application restrictions section, select iOS apps.

  4. For each iOS app that you want to add, click Add an item and enter the bundle ID, then click Done.

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

gcloud

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

    The ID is not the same as the display name or the key string. You can get the ID by using the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    2 command to list the keys in your project.

  2. Use the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    3 method to specify the iOS apps that can use the key.

    Replace the following values:

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      4: The ID of the key that you want to restrict.
    • 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"
      
      02: 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.

    
    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());
        }
      }
    }
    2

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 method. The ID is listed in the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    6 field of the response.

    Replace

    POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
    1 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 method to specify the iOS apps that can use an API key.

    This request returns a ; you must poll the operation to know when the operation completes and get the operation status.

    Replace the following values:

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

    • POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
      1: Your Google Cloud project ID or name.

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      4: The ID of the key that you want to restrict.

    
    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());
        }
      }
    }
    4

For more information about adding iOS app restrictions to a key using the REST API, see in the API Key API documentation.

Java

To run this sample, you must install the

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
2 client.

auth/src/main/java/RestrictApiKeyIos.java

View on GitHub


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());
    }
  }
}
5

Python

To run this sample, you must install the Python Client for API Keys API.

auth/api-client/restrict_api_key_ios.py

View on GitHub


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());
    }
  }
}
6

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.

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

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    2 command to list the keys in your project.

  2. Use the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    3 command to specify which services an API key can be used to authenticate to.

    Replace the following values:

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      4: The ID of the key that you want to restrict.
    • 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"
      
      12,
      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"
      
      13...: 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

    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"
    
    14.

    
    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());
        }
      }
    }
    7

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 method. The ID is listed in the

    
    from google.cloud import language_v1
    
    
    def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
        """
        Authenticates with an API key for Google Language service.
    
        TODO(Developer): Replace these variables before running the sample.
    
        Args:
            quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
            api_key_string: The API key to authenticate to the service.
        """
    
        # Initialize the Language Service client and set the API key and the quota project id.
        client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                   "quota_project_id": quota_project_id})
    
        text = "Hello, world!"
        document = language_v1.Document(
            content=text, type_=language_v1.Document.Type.PLAIN_TEXT
        )
    
        # Make a request to analyze the sentiment of the text.
        sentiment = client.analyze_sentiment(
            request={"document": document}
        ).document_sentiment
    
        print(f"Text: {text}")
        print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
        print("Successfully authenticated using the API key")
    
    6 field of the response.

    Replace

    POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
    1 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 method to specify which services an API key can be used to authenticate to.

    This request returns a ; you must poll the operation to know when the operation completes and get the operation status.

    Replace the following values:

    • curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      -d {'"displayName" : "DISPLAY_NAME"'} \
      "https://apikeys.googleapis.com/v2/projects/PROJECT/locations/global/keys"
      
      12,
      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"
      
      13...: 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

      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"
      
      14.

    • POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
      1: Your Google Cloud project ID or name.

    • 
      from google.cloud import language_v1
      
      
      def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
          """
          Authenticates with an API key for Google Language service.
      
          TODO(Developer): Replace these variables before running the sample.
      
          Args:
              quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
              api_key_string: The API key to authenticate to the service.
          """
      
          # Initialize the Language Service client and set the API key and the quota project id.
          client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
                                                                     "quota_project_id": quota_project_id})
      
          text = "Hello, world!"
          document = language_v1.Document(
              content=text, type_=language_v1.Document.Type.PLAIN_TEXT
          )
      
          # Make a request to analyze the sentiment of the text.
          sentiment = client.analyze_sentiment(
              request={"document": document}
          ).document_sentiment
      
          print(f"Text: {text}")
          print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
          print("Successfully authenticated using the API key")
      
      4: The ID of the key that you want to restrict.

    
    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());
        }
      }
    }
    9

For more information about adding API restrictions to a key using the REST API, see in the API Key API documentation.

Java

To run this sample, you must install the

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
2 client.

auth/src/main/java/RestrictApiKeyApi.java

View on GitHub


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

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

Python

To run this sample, you must install the Python Client for API Keys API.

auth/api-client/restrict_api_key_api.py

View on GitHub


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

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

Get project information from a key string

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

Replace

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"
23 with the key string you need project information for.

gcloud

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


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

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

REST

You use the lookupKey method to get the project ID from a key string.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

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

Java

To run this sample, you must install the

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
2 client.

auth/src/main/java/LookupApiKey.java

View on GitHub


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

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

Python

To run this sample, you must install the Python Client for API Keys API.

auth/api-client/lookup_api_key.py

View on GitHub


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

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

Poll long-running operations

API Key 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 Key API operation, you use the

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"
25 method.

Replace

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"
26 with the operation name returned by the long-running operation. For example,
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"
27.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str) -> Key:
    """
    Creates and restrict an API key.

    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 = "My first API key"

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

Limits on API keys

You can create up to 300 API keys per project. This limit is a system limit, and cannot be changed using a quota increase request.

Step 1.) Install and open the Apipheny add-on for Google Sheets. Apipheny is an API connector for Google Sheets. ... .
Step 2.) Get a Github Access Token. ... .
Step 3.) Get the Github endpoints' URLs. ... .
Step 4.) Add your URL for a Github REST API endpoint into the Apipheny Add-on. ... .
Step 5.) Run the Github API Request..

How do I get data from Google Sheets using Python?

Using gspread + service account from Google Cloud Developer Console to read and write to accessible Google Sheets.
Enable Google Drive API and Google Sheets API under APIs and Services..
Create a new service account and note down the email of the service account..
Create a credential key and export the key as JSON..

Can you automate Google Sheets with Python?

It's been possible to automate Google Sheets via the Google Sheets API for many years and there are multiple Python packages available that wrap this API: there's gspread, pygsheets, ezsheets, and Google's own google-api-python-client.