Use API keys to access APIs

This page describes how to use API keys to access Google Cloud APIs and services that accept API keys.

Not all Google Cloud APIs accept API keys to authorize usage. Review the documentation for the service or API that you want to use to determine whether it accepts API keys.

For information about creating and managing API keys, including restricting API keys, see Manage API keys.

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

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 API_KEY with the key string of your API key.

For example, to pass an API key for a Cloud Natural Language API request for documents.analyzeEntities:

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

Alternatively, you can use the x-goog-api-key header to pass in your key. This header must be used with gRPC requests.

curl -X POST \
    -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.

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.

Python

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


from google.cloud import language_v1


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

    TODO(Developer): Replace this variable before running the sample.

    Args:
        api_key_string: The API key to authenticate to the service.
    """

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

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

Node.js

To run this sample, you must install the Natural Language client library and the API Keys client library](/nodejs/docs/reference/apikeys/latest).


const {
  v1: {LanguageServiceClient},
} = require('@google-cloud/language');

/**
 * Authenticates with an API key for Google Language service.
 *
 * @param {string} apiKey An API Key to use
 */
async function authenticateWithAPIKey(apiKey) {
  const language = new LanguageServiceClient({apiKey});

  // Alternatively:
  // const auth = new GoogleAuth({apiKey});
  // const {GoogleAuth} = require('google-auth-library');
  // const language = new LanguageServiceClient({auth});

  const text = 'Hello, world!';

  const [response] = await language.analyzeSentiment({
    document: {
      content: text,
      type: 'PLAIN_TEXT',
    },
  });

  console.log(`Text: ${text}`);
  console.log(
    `Sentiment: ${response.documentSentiment.score}, ${response.documentSentiment.magnitude}`
  );
  console.log('Successfully authenticated using the API key');
}

authenticateWithAPIKey();

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. For more information, see Best practices for managing API keys.

What's next