## API Keys

All requests to ModelStack require authentication via an API key. Keys are passed in the `Authorization` header using the Bearer token format.

## Header Format

```
Authorization: Bearer your_api_key
```

## Key Format

ModelStack API keys follow this format:

```
sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

All keys are prefixed with `sk_` followed by a random alphanumeric string.

## Getting an API Key

1. Sign in to your [dashboard](https://modelstack.cc/dashboard)
2. Navigate to **API Keys**
3. Click **Create API Key**
4. Give your key a descriptive name
5. Copy the key immediately — it won't be shown again

<Warning>
  **Treat your API key like a password.** Do not expose it in client-side code,
  public repositories, or logs. If a key is compromised, revoke it immediately
  from your dashboard.
</Warning>

## Example Request

<CodeGroup>

```bash cURL
curl https://api.modelstack.cc/v1/chat/completions \
  -H "Authorization: Bearer your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
```

```python Python
from openai import OpenAI

client = OpenAI(
    api_key="your_api_key",
    base_url="https://api.modelstack.cc/v1"
)
```

```javascript Node.js
import OpenAI from 'openai'

const client = new OpenAI({
  apiKey: 'your_api_key',
  baseURL: 'https://api.modelstack.cc/v1',
})
```

</CodeGroup>

## Security Best Practices

<AccordionGroup>
  <Accordion title="Use environment variables">
    Store your API key in environment variables rather than hardcoding it:

    ```bash
    export MODELSTACK_API_KEY="your_api_key"
    ```

    ```python
    import os
    api_key = os.environ["MODELSTACK_API_KEY"]
    ```

  </Accordion>
  <Accordion title="Use separate keys for different environments">
    Create distinct API keys for development, staging, and production. This lets you revoke a compromised key without affecting other environments.
  </Accordion>
  <Accordion title="Rotate keys periodically">
    Rotate your API keys regularly. Create a new key, update your applications, then revoke the old key.
  </Accordion>
  <Accordion title="Never commit keys to source control">
    Add `.env` files to `.gitignore` and use secret management tools for production deployments.
  </Accordion>
</AccordionGroup>

## Error Responses

If authentication fails, the API returns a `401 Unauthorized` error:

```json
{
  "error": {
    "message": "Invalid API key provided",
    "type": "authentication_error",
    "code": 401
  }
}
```
