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

# Authentication

> Learn how to authenticate your requests to AnyAPI

AnyAPI uses API keys to authenticate requests. Your API keys carry many privileges, so be sure to keep them secure! Do not share your secret API keys in publicly accessible areas such as GitHub, client-side code, and so forth.

<Note>
  All API requests must be made over HTTPS. Calls made over plain HTTP will fail. API requests without authentication will also fail.
</Note>

## API Keys

Authentication to the API is performed via HTTP Bearer authentication. Provide your API key as a bearer token in the `Authorization` header.

<Card title="Getting Your API Key" icon="key">
  You can find and manage your API keys in the [AnyAPI.ai Dashboard](https://dash.anyapi.ai/?page=api-keys). Keep your API keys secure and rotate them regularly for optimal security.
</Card>

## Bearer Token Format

Include your API key in the `Authorization` header using the Bearer authentication scheme:

```
Authorization: Bearer your_api_key
```

## Basic Authentication Example

<CodeGroup>
  ```bash curl theme={"system"}
  curl -X POST https://api.anyapi.ai/v1/chat/completions \
  -H "Authorization: Bearer your_api_key" \
  -H "Content-Type: application/json" \
  -d '
  {
      "model": "openai/gpt-3.5-turbo",
      "messages": [
          {
              "role": "user",
              "content": "Hello, world!"
          }
      ]
  }'
  ```

  ```javascript JavaScript theme={"system"}
  const response = await fetch('https://api.anyapi.ai/v1/chat/completions', {
  method: 'POST',
  headers: 
      {
          'Authorization': 'Bearer your_api_key',
          'Content-Type': 'application/json',
      },
  body: JSON.stringify({
  model: 'openai/gpt-3.5-turbo',
  messages: [
          {
              role: 'user',
              content: 'Hello, world!'
          }
      ]})
  });

  const data = await response.json();
  console.log(data);
  ```

  ```python Python theme={"system"}
  import requests

  headers = {
      'Authorization': 'Bearer your_api_key',
      'Content-Type': 'application/json',
  }

  data = {
      'model': 'openai/gpt-3.5-turbo',
      'messages': [
          {
              'role': 'user',
              'content': 'Hello, world!'
          }
      ]
  }

  response = requests.post(
  'https://api.anyapi.ai/v1/chat/completions',
  headers=headers,
  json=data)

  print(response.json())
  ```

  ```php PHP theme={"system"}
  <?php

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, 'https://api.anyapi.ai/v1/chat/completions');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
      'model' => 'gpt-3.5-turbo',
      'messages' => [
          [
              'role' => 'user',
              'content' => 'Hello, world!'
          ]
      ]
  ]));

  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Authorization: Bearer your_api_key',
      'Content-Type: application/json',
  ]);

  $result = curl_exec($ch);
  curl_close($ch);

  echo $result;
  ?>
  ```
</CodeGroup>

## Advanced cURL Examples

### Basic Chat Completion

```bash theme={"system"}
curl -X POST https://api.anyapi.ai/v1/chat/completions \
  -H "Authorization: Bearer your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Explain quantum computing in simple terms."}
    ],
    "max_tokens": 150,
    "temperature": 0.7
  }'
```

### Streaming Response

```bash theme={"system"}
curl -X POST https://api.anyapi.ai/v1/chat/completions \
  -H "Authorization: Bearer your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-3.5-turbo",
    "messages": [
      {"role": "user", "content": "Write a short story about AI"}
    ],
    "stream": true
  }' \
  --no-buffer
```

### With Custom Headers (Optional)

```bash theme={"system"}
curl -X POST https://api.anyapi.ai/v1/chat/completions \
  -H "Authorization: Bearer your_api_key" \
  -H "Content-Type: application/json" \
  -H "X-Request-ID: unique-request-id-123" \
  -H "HTTP-Referer: https://yourapp.com" \
  -H "X-Title: My AI Application" \
  -d '{
    "model": "anthropic/claude-3-sonnet",
    "messages": [
      {"role": "user", "content": "Hello from my application!"}
    ]
  }'
```

## Error Handling

If your API key is missing or invalid, you'll receive an error response:

<CodeGroup>
  ```bash Missing API Key theme={"system"}
  curl -X POST https://api.anyapi.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "openai/gpt-3.5-turbo", "messages": [{"role": "user", "content": "Hello"}]}'
  ```

  ```json Response theme={"system"}
  {
      "error": {
      "message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY).",
      "type": "invalid_request_error",
      "code": "invalid_api_key"
      }
  }
  ```
</CodeGroup>

<CodeGroup>
  ```bash Invalid API Key theme={"system"}
  curl -X POST https://api.anyapi.ai/v1/chat/completions \
  -H "Authorization: Bearer invalid_key_here" \
  -H "Content-Type: application/json" \
  -d '{"model": "openai/gpt-3.5-turbo", "messages": [{"role": "user", "content": "Hello"}]}'
  ```

  ```json Response theme={"system"}
  {
      "error": {
      "message": "Invalid API key provided.",
      "type": "invalid_request_error",
      "code": "invalid_api_key"
      }
  }
  ```
</CodeGroup>

## Security Best Practices

<Warning>
  **Never expose your API keys in client-side code.** API keys should only be used in server-side applications where they can be kept secure.
</Warning>

### Environment Variables

Store your API key in environment variables:

<CodeGroup>
  ```bash .env theme={"system"}
  ANYAPI_API_KEY=your_api_key_here
  ```

  ```javascript JavaScript theme={"system"}
  // Use environment variables
  const apiKey = process.env.ANYAPI_API_KEY;

  const response = await fetch('https://api.anyapi.ai/v1/chat/completions', {
  headers: {
  'Authorization': `Bearer ${apiKey}`,
  'Content-Type': 'application/json',
  },
  // ... rest of request
  });
  ```

  ```python Python theme={"system"}
  import os

  api_key = os.getenv('ANYAPI_API_KEY')

  headers = {
  'Authorization': f'Bearer {api_key}',
  'Content-Type': 'application/json',
  }
  ```
</CodeGroup>

### Rate Limiting

Your API key has rate limits associated with it. Include proper error handling for rate limit responses:

```bash theme={"system"}
curl -X POST https://api.anyapi.ai/v1/chat/completions \
  -H "Authorization: Bearer your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"model": "openai/gpt-3.5-turbo", "messages": [{"role": "user", "content": "Hello"}]}' \
  -w "HTTP Status: %{http_code}\n"
```

## Testing Your Authentication

Use this simple curl command to test if your API key is working:

```bash theme={"system"}
curl -X GET https://api.anyapi.ai/v1/models \
  -H "Authorization: Bearer your_api_key" \
  -H "Content-Type: application/json"
```

A successful response will return a list of available models:

```json theme={"system"}
{
  "object": "list",
  "data": [
    {
      "id": "openai/gpt-4",
      "object": "model",
      "created": 1687882411,
      "owned_by": "openai"
    },
    {
      "id": "openai/gpt-3.5-turbo",
      "object": "model", 
      "created": 1677610602,
      "owned_by": "openai"
    }
    // ... more models
  ]
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Make Your First Request" icon="rocket" href="/api-reference/text/create-chat-completion">
    Learn how to make your first API call with AnyAPI.ai
  </Card>
</CardGroup>
