> ## Documentation Index
> Fetch the complete documentation index at: https://the-early-spring18.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Google API Authentication: Keys, Scopes, and Auth Errors

> Learn how to generate a Google API key, pass it in the Authorization header, manage key scopes, and handle authentication errors in your integration.

The Google API uses API key authentication to verify your identity and authorize access to resources on your behalf. Every request you make must include a valid API key passed as a Bearer token in the `Authorization` header. API keys are tied to specific scopes that control which operations they can perform, giving you fine-grained control over what each integration is permitted to do. Before you can make your first request, you need to generate a key from your account settings — a process that takes under a minute and only needs to be done once per integration.

<Warning>
  Never commit API keys to source control. Even in private repositories, exposed keys are a security risk. Always load your keys from environment variables or a dedicated secrets manager such as AWS Secrets Manager, HashiCorp Vault, or your CI/CD platform's secret store.
</Warning>

## Generate an API Key

You can create as many API keys as you need — one per application, environment, or integration is a recommended practice. Follow the steps below to generate your first key.

<Steps>
  <Step title="Open API Key Settings">
    Log in to your Google account and navigate to **Settings → API Keys** in the left-hand sidebar. This page lists all active keys associated with your account along with their creation date, last-used timestamp, and assigned scopes.
  </Step>

  <Step title="Create a New Key">
    Click **New Key** to open the key creation dialog. Give your key a descriptive name (for example, `production-search-service` or `dev-local`) so you can identify it later. Then select the scopes this key requires — choose only the scopes your integration actually needs to follow the principle of least privilege. Available scopes are `read`, `write`, and `admin`.
  </Step>

  <Step title="Copy Your Key Immediately">
    After clicking **Create**, your full API key is displayed exactly once. Copy it to your clipboard right away — once you close or navigate away from this dialog, the key value is no longer retrievable and you will need to generate a new one if you lose it.
  </Step>

  <Step title="Store the Key Securely">
    Paste your key into your application's environment configuration. In local development, use a `.env` file (and ensure `.env` is listed in your `.gitignore`). In production, use your platform's secret management tooling. Never hardcode the key value directly in your source code.

    ```bash theme={null}
    # .env
    GOOGLE_API_KEY=your_api_key_here
    ```
  </Step>
</Steps>

## Using Your API Key

Pass your API key as a Bearer token in the `Authorization` header of every request. The header value must follow this exact format:

```
Authorization: Bearer YOUR_API_KEY
```

The example below demonstrates a basic authenticated search request using cURL:

```bash theme={null}
curl https://api.google.com/v1/search \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -G --data-urlencode 'q=example'
```

You can use the same pattern in any HTTP client or language. The code samples below show equivalent implementations in Python and JavaScript:

<CodeGroup>
  ```python Python theme={null}
  import requests

  headers = {'Authorization': 'Bearer YOUR_API_KEY'}
  params = {'q': 'example'}

  resp = requests.get(
      'https://api.google.com/v1/search',
      headers=headers,
      params=params
  )
  data = resp.json()
  print(data)
  ```

  ```javascript JavaScript theme={null}
  const res = await fetch('https://api.google.com/v1/search?q=example', {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY'
    }
  });

  const data = await res.json();
  console.log(data);
  ```
</CodeGroup>

<Tip>
  Create separate API keys for each environment — development, staging, and production. This makes it easy to rotate or revoke a compromised key in one environment without disrupting others, and lets you apply different scope restrictions per environment (for example, a read-only key for staging).
</Tip>

## API Key Scopes

When you create an API key, you assign it one or more scopes that determine which API operations it is permitted to perform. Requests made with a key that lacks the required scope for an operation will receive a `403 Forbidden` response.

| Scope   | Description                                       | Common Use Cases                          |
| ------- | ------------------------------------------------- | ----------------------------------------- |
| `read`  | Read-only access to all resources                 | Dashboards, search queries, data exports  |
| `write` | Create and update resources (includes `read`)     | Data ingestion pipelines, user management |
| `admin` | Full access including key management and settings | Automation scripts, account provisioning  |

<Note>
  The `write` scope implicitly includes all `read` permissions. Similarly, `admin` encompasses both `read` and `write`. You only need to select the highest scope your integration requires — there is no need to add lower scopes separately.
</Note>

## Authentication Errors

If authentication fails, the API returns one of two status codes depending on the nature of the problem. Understanding the distinction helps you diagnose issues quickly.

<CardGroup cols={2}>
  <Card title="401 Unauthorized" icon="circle-xmark">
    Your request is missing an `Authorization` header, the header is malformed, or the API key value is invalid (for example, it was deleted or never existed). Double-check that the header is formatted as `Bearer YOUR_API_KEY` and that the key value matches what was generated in your settings.
  </Card>

  <Card title="403 Forbidden" icon="lock">
    Your API key is valid and recognized, but it does not have the scope required to perform the requested operation. Review the scopes assigned to your key in **Settings → API Keys** and regenerate the key with the correct scopes if needed.
  </Card>
</CardGroup>

Both error responses follow the standard error envelope described in the [API Overview](/api/overview):

```json theme={null}
{
  "error": {
    "code": "unauthorized",
    "message": "Invalid or missing API key.",
    "request_id": "req_abc123"
  }
}
```

<Expandable title="Troubleshooting checklist for authentication failures">
  If you are receiving unexpected `401` or `403` errors, work through this checklist before contacting support:

  * Confirm the `Authorization` header is present on every request — some HTTP client wrappers or proxies may not forward custom headers by default.
  * Verify the header value starts with `Bearer ` (note the trailing space) followed immediately by the key.
  * Check that your environment variable is being loaded correctly — `console.log` or `print` the first few characters of the key at startup to confirm it is not `undefined` or empty.
  * Open **Settings → API Keys** and confirm the key has not been revoked or expired.
  * Ensure the key has the scope required by the endpoint you are calling (see the scope table above).
  * If you regenerated a key, make sure all running instances of your application have been updated with the new value.
</Expandable>
