> ## Documentation Index
> Fetch the complete documentation index at: https://docs.arouter.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# API Key Rotation

> Best practices for rotating ARouter API keys with zero downtime. Keep your application secure by regularly cycling credentials.

Regular API key rotation limits the blast radius of a compromised key and satisfies many security compliance requirements. ARouter's key management API supports zero-downtime rotation.

## Rotation Strategy

The safest rotation pattern is **create-then-delete**:

1. Create a new key with the same permissions as the old one
2. Deploy the new key to your application
3. Verify the new key is working
4. Delete the old key

This ensures no downtime — traffic continues on the old key until the new key is confirmed working.

***

## Step 1: Create a New Key

Use the [Key Management API](/en/api-reference/keys/create-key) to create a replacement key:

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl -X POST https://api.arouter.ai/v1/keys \
      -H "Authorization: Bearer lr_live_xxxx" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "production-v2",
        "allowed_providers": ["openai", "anthropic", "google"],
        "spending_limit": 500.00
      }'
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    response = requests.post(
        "https://api.arouter.ai/v1/keys",
        headers={"Authorization": "Bearer lr_live_xxxx"},
        json={
            "name": "production-v2",
            "allowed_providers": ["openai", "anthropic", "google"],
            "spending_limit": 500.00,
        },
    )
    new_key = response.json()["key"]
    print(f"New key created: {new_key[:8]}...")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const response = await fetch("https://api.arouter.ai/v1/keys", {
      method: "POST",
      headers: {
        Authorization: "Bearer lr_live_xxxx",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name: "production-v2",
        allowed_providers: ["openai", "anthropic", "google"],
        spending_limit: 500.0,
      }),
    });

    const { key } = await response.json();
    console.log(`New key: ${key.substring(0, 8)}...`);
    ```
  </Tab>
</Tabs>

**Save the returned key value immediately** — ARouter only returns the full key once at creation time.

***

## Step 2: Update Your Application

Update the `AROUTER_API_KEY` environment variable (or equivalent secret) in your deployment environment:

```bash theme={null}
# Example with a .env file
AROUTER_API_KEY=lr_live_new_key_here

# Example updating a Kubernetes secret
kubectl create secret generic arouter-credentials \
  --from-literal=api-key=lr_live_new_key_here \
  --dry-run=client -o yaml | kubectl apply -f -
```

Redeploy or restart your application to pick up the new key.

***

## Step 3: Verify the New Key

Before deleting the old key, confirm the new key is working:

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl https://api.arouter.ai/v1/models \
      -H "Authorization: Bearer lr_live_new_key_here"
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from openai import OpenAI

    # Test with new key
    client = OpenAI(
        base_url="https://api.arouter.ai/v1",
        api_key="lr_live_new_key_here",
    )

    response = client.chat.completions.create(
        model="openai/gpt-5.4",
        messages=[{"role": "user", "content": "ping"}],
        max_tokens=5,
    )
    print("New key verified:", response.choices[0].message.content)
    ```
  </Tab>
</Tabs>

Check the [ARouter Dashboard](https://arouter.ai/keys) to confirm requests are appearing under the new key.

***

## Step 4: Delete the Old Key

Once the new key is confirmed working, delete the old one using its key ID:

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl -X DELETE https://api.arouter.ai/v1/keys/key_oldid \
      -H "Authorization: Bearer lr_live_new_key_here"
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    requests.delete(
        "https://api.arouter.ai/v1/keys/key_oldid",
        headers={"Authorization": "Bearer lr_live_new_key_here"},
    )
    print("Old key deleted")
    ```
  </Tab>
</Tabs>

***

## Automated Rotation

For high-security environments, automate rotation on a schedule using your CI/CD system or a secrets manager:

### GitHub Actions Example

```yaml theme={null}
name: Rotate ARouter Key

on:
  schedule:
    - cron: '0 0 1 * *'  # Monthly

jobs:
  rotate:
    runs-on: ubuntu-latest
    steps:
      - name: Create new key
        id: create
        run: |
          NEW_KEY=$(curl -s -X POST https://api.arouter.ai/v1/keys \
            -H "Authorization: Bearer ${{ secrets.AROUTER_API_KEY }}" \
            -H "Content-Type: application/json" \
            -d '{"name": "production-auto-rotated"}' \
            | jq -r .key)
          echo "new_key=$NEW_KEY" >> $GITHUB_OUTPUT

      - name: Update secret
        uses: gliech/create-github-secret-action@v1
        with:
          name: AROUTER_API_KEY
          value: ${{ steps.create.outputs.new_key }}
          token: ${{ secrets.GH_TOKEN }}
```

***

## Listing Active Keys

List all active keys to audit what's in use:

```bash theme={null}
curl https://api.arouter.ai/v1/keys \
  -H "Authorization: Bearer lr_live_xxxx"
```

Response:

```json theme={null}
{
  "data": [
    {
      "id": "key_abc123",
      "name": "production-v2",
      "created_at": "2025-01-15T10:00:00Z",
      "last_used_at": "2025-04-01T08:30:00Z",
      "spending_limit": 500.00
    },
    {
      "id": "key_def456",
      "name": "staging",
      "created_at": "2025-03-01T09:00:00Z",
      "last_used_at": "2025-04-01T07:15:00Z",
      "spending_limit": 50.00
    }
  ]
}
```

***

## Best Practices

* **Rotate on a schedule** — Monthly rotation is a good baseline for most applications
* **Rotate immediately after suspected compromise** — Do not wait for the next scheduled rotation
* **Use descriptive names** — Include version or date in key names (`production-2025-04`, `production-v3`)
* **Set spending limits** — Always configure `spending_limit` on production keys to cap exposure
* **Use separate keys per environment** — Never share a key between production and staging
* **Audit regularly** — Review the key list monthly and delete any keys that are no longer in use
* **Store keys in secrets managers** — Use AWS Secrets Manager, HashiCorp Vault, or equivalent rather than `.env` files in version control

See [Key Management](/en/guides/key-management) for the full key management guide, and the [Key Management API](/en/api-reference/keys/create-key) for the complete API reference.
