# Authentication

Learn how to securely authenticate with the Freddy API using API keys and manage your authentication workflow.

## API Key Authentication

Freddy uses API key authentication for all requests. Your API key identifies your account and provides access to your resources.

### Getting Your API Key

1. **Log in** to [Freddy](https://chat.aitronos.com)
2. Navigate to **Settings** → **API Keys**
3. Click **"Create New API Key"**
4. **Name your key** (e.g., "Production App", "Development")
5. **Copy the key** immediately (it won't be shown again)


### API Key Format

All Freddy API keys follow this format:


```
ak_1234567890abcdef1234567890abcdef12345678
```

- Prefix: `ak_` (identifies it as an API key)
- Length: 42 characters total
- Characters: Alphanumeric (a-z, A-Z, 0-9)


## Using Your API Key

Pass your API key in the `X-API-Key` header on every request.

### Python SDK (Recommended)


```python
from aitronos import Aitronos

client = Aitronos(api_key="ak_your_api_key_here")

result = client.responses.create_response(
    organization_id="org_your_org_id",
    model="gpt-4o",
    inputs=[{"role": "user", "content": "Hello!"}],
)
print(result.response[0]["text"])
```

Install: `pip install aitronos-sdk`

### cURL


```bash
curl -X POST "https://api.aitronos.com/v1/model/response" \
  -H "X-API-Key: ak_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "organization_id": "org_your_org_id",
    "model": "gpt-4o",
    "inputs": [{"role": "user", "content": "Hello!"}]
  }'
```

### Python


```python
import os
import requests

api_key = os.environ["FREDDY_API_KEY"]
headers = {
    "X-API-Key": api_key,
    "Content-Type": "application/json",
}

response = requests.post(
    "https://api.aitronos.com/v1/model/response",
    headers=headers,
    json={
        "organization_id": "org_your_org_id",
        "model": "gpt-4o",
        "inputs": [{"role": "user", "content": "Hello!"}],
    },
)
data = response.json()
print(data["response"][0]["text"])
```

### JavaScript


```javascript
const apiKey = process.env.FREDDY_API_KEY;

const response = await fetch("https://api.aitronos.com/v1/model/response", {
  method: "POST",
  headers: {
    "X-API-Key": apiKey,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    organization_id: "org_your_org_id",
    model: "gpt-4o",
    inputs: [{ role: "user", content: "Hello!" }],
  }),
});
const data = await response.json();
console.log(data.response[0].text);
```

## Security Best Practices

### 1. Keep Your API Keys Secret

**DO:**

- Store API keys in environment variables
- Use secure key management systems
- Rotate keys regularly
- Use different keys for different environments


**DON'T:**

- Commit API keys to version control
- Share keys in chat or email
- Use production keys in development
- Hardcode keys in your application


### 2. Environment Variables

Store your API key securely:


```bash
# .env file
FREDDY_API_KEY=ak_your_api_key_here
```


```python
# Python
import os
api_key = os.getenv("FREDDY_API_KEY")
```


```javascript
// Node.js
const apiKey = process.env.FREDDY_API_KEY;
```

### 3. Key Rotation

Regularly rotate your API keys:

1. **Create a new key** in Freddy
2. **Update your applications** to use the new key
3. **Test thoroughly** in staging environment
4. **Deploy to production**
5. **Delete the old key** after confirming everything works


## Error Handling

### Common Authentication Errors

#### 401 Unauthorized


```json
{
  "success": false,
  "error": {
    "code": "INVALID_API_KEY",
    "message": "The API key provided is invalid or has expired.",
    "system_message": "API key validation failed",
    "type": "client_error",
    "status": 401,
    "details": {},
    "trace_id": "abc-123-def",
    "timestamp": "2025-12-22T15:30:00Z"
  }
}
```

**Causes:**

- Missing `X-API-Key` header
- Invalid or expired API key
- Malformed API key


#### 403 Forbidden


```json
{
  "success": false,
  "error": {
    "code": "INSUFFICIENT_PERMISSIONS",
    "message": "You don't have permission to access this resource.",
    "system_message": "Insufficient permissions for this operation",
    "type": "client_error",
    "status": 403,
    "details": {},
    "trace_id": "abc-123-def",
    "timestamp": "2025-12-22T15:30:00Z"
  }
}
```

**Causes:**

- API key doesn't have required permissions
- Account limitations or restrictions
- Resource access denied


### Error Handling Code


```python
import os
import requests

def make_authenticated_request(endpoint):
    api_key = os.environ["FREDDY_API_KEY"]
    headers = {"X-API-Key": api_key}

    response = requests.get(
        f"https://api.aitronos.com/v1/{endpoint}",
        headers=headers,
    )

    if response.status_code == 401:
        print("Authentication failed. Check your API key.")
        return None
    elif response.status_code == 403:
        print("Permission denied. Check your account permissions.")
        return None
    elif response.status_code == 200:
        return response.json()
    else:
        print(f"Unexpected error: {response.status_code}")
        return None
```

## Rate Limiting

API keys are subject to rate limits based on your plan:

- **Standard**: 100 requests/minute
- **Premium**: 1,000 requests/minute
- **Enterprise**: Custom limits


Rate limit headers are included in responses:


```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200
```

## Monitoring Usage

Track your API usage in [Freddy](https://chat.aitronos.com):

1. Go to **Settings** → **API Keys**
2. View **Usage Statistics** for each key
3. Monitor **Rate Limit Status**
4. Set up **Usage Alerts**


## Troubleshooting

### API Key Not Working?

1. **Check the format** — Should start with `ak_`
2. **Verify in Hub** — Ensure key exists and is active
3. **Check the header** — Use `X-API-Key` as the header name
4. **Test with cURL** — Isolate the issue


### Still Having Issues?

- **[Quick Start](/docs/documentation/getting-started/quick-start)** — Basic setup guide
- **[API Reference](/docs/api-reference/introduction)** — Detailed endpoint docs
- **[Hub](https://chat.aitronos.com)** — Manage your keys
- **Support** — Contact our team


- **[Quick Start](/docs/documentation/getting-started/quick-start)** — Make your first request
- **[Code Examples](/docs/documentation/examples)** — Common patterns and use cases
- **[Error Handling](/docs/documentation/error-handling)** — Handle errors gracefully