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

# Authentication

> Learn how to authenticate with the Whisky API

# Authentication

The Whisky API uses API key authentication to secure access to all endpoints. This ensures that only authorized users can access the API and helps prevent abuse.

## API Key Authentication

All API requests must include a valid API key in the request headers.

### Header Method (Recommended)

Include your API key in the `X-API-Key` header:

```bash theme={null}
curl -H "X-API-Key: your-api-key-here" \
     https://api.whisky.casino/status
```

### Authorization Method

Alternatively, you can use the `Authorization` header with Bearer token:

```bash theme={null}
curl -H "Authorization: Bearer your-api-key-here" \
     https://api.whisky.casino/status
```

## Getting an API Key

### Request Access

To get an API key, contact the Whisky team:

* **Email**: [api@whisky.casino](mailto:api@whisky.casino)
* **Discord**: [Whisky Gaming Discord](https://discord.gg/whisky-gaming)
* **GitHub**: [Create an issue](https://github.com/weknowyourgame/whisky-gaming/issues)

### API Key Format

API keys are 64-character hexadecimal strings:

```
a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef12345678
```

## Environment Setup

### Environment Variables

Add your API key to your environment variables:

```bash theme={null}
# .env file
API_KEY=your-secure-api-key-here
HELIUS_API_KEY=your-helius-api-key
SOLANA_RPC_ENDPOINT=your-solana-rpc-endpoint
PORT=3000
```

### JavaScript/TypeScript

```typescript theme={null}
// Using environment variables
const apiKey = process.env.API_KEY;

const response = await fetch('https://api.whisky.casino/status', {
  headers: {
    'X-API-Key': apiKey,
    'Content-Type': 'application/json'
  }
});
```

### Python

```python theme={null}
import os
import requests

api_key = os.getenv('API_KEY')

headers = {
    'X-API-Key': api_key,
    'Content-Type': 'application/json'
}

response = requests.get('https://api.whisky.casino/status', headers=headers)
```

## Error Responses

### Invalid API Key

```json theme={null}
{
  "error": "Invalid API key",
  "code": "UNAUTHORIZED",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

**HTTP Status**: `401 Unauthorized`

### Missing API Key

```json theme={null}
{
  "error": "API key required",
  "code": "MISSING_API_KEY",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

**HTTP Status**: `401 Unauthorized`

### Rate Limited

```json theme={null}
{
  "error": "Rate limit exceeded",
  "code": "RATE_LIMITED",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "retryAfter": 60
}
```

**HTTP Status**: `429 Too Many Requests`

## Rate Limiting

The API implements rate limiting to ensure fair usage:

### Rate Limits by Tier

| Tier           | Requests per Minute | Burst Limit |
| -------------- | ------------------- | ----------- |
| **Standard**   | 100                 | 200         |
| **Premium**    | 1000                | 2000        |
| **Enterprise** | Custom              | Custom      |

### Rate Limit Headers

Rate limit information is included in response headers:

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

### Handling Rate Limits

```typescript theme={null}
async function makeApiRequest(endpoint: string) {
  try {
    const response = await fetch(`https://api.whisky.casino${endpoint}`, {
      headers: {
        'X-API-Key': apiKey
      }
    });

    if (response.status === 429) {
      const retryAfter = response.headers.get('Retry-After');
      const waitTime = parseInt(retryAfter || '60');
      
      console.log(`Rate limited. Waiting ${waitTime} seconds...`);
      await new Promise(resolve => setTimeout(resolve, waitTime * 1000));
      
      return makeApiRequest(endpoint); // Retry
    }

    return response.json();
  } catch (error) {
    console.error('API request failed:', error);
    throw error;
  }
}
```

## Security Best Practices

### Keep API Keys Secure

* **Never commit API keys to version control**
* **Use environment variables**
* **Rotate keys regularly**
* **Use different keys for different environments**

### Example: Secure Configuration

```typescript theme={null}
// config/api.ts
export const apiConfig = {
  baseUrl: process.env.API_BASE_URL || 'https://api.whisky.casino',
  apiKey: process.env.API_KEY,
  timeout: parseInt(process.env.API_TIMEOUT || '30000'),
  retries: parseInt(process.env.API_RETRIES || '3')
};

// Validate configuration
if (!apiConfig.apiKey) {
  throw new Error('API_KEY environment variable is required');
}
```

### API Key Rotation

```typescript theme={null}
// Support for multiple API keys
const apiKeys = [
  process.env.API_KEY_PRIMARY,
  process.env.API_KEY_SECONDARY
].filter(Boolean);

let currentKeyIndex = 0;

function getNextApiKey(): string {
  const key = apiKeys[currentKeyIndex];
  currentKeyIndex = (currentKeyIndex + 1) % apiKeys.length;
  return key;
}
```

## SDK Integration

### Whisky API Client

```typescript theme={null}
class WhiskyAPI {
  private baseUrl: string;
  private apiKey: string;

  constructor(baseUrl: string, apiKey: string) {
    this.baseUrl = baseUrl;
    this.apiKey = apiKey;
  }

  private async request(endpoint: string, options: RequestInit = {}) {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      ...options,
      headers: {
        'X-API-Key': this.apiKey,
        'Content-Type': 'application/json',
        ...options.headers,
      },
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error || `HTTP ${response.status}`);
    }

    return response.json();
  }

  // API methods...
}
```

### Usage Example

```typescript theme={null}
const api = new WhiskyAPI(
  'https://api.whisky.casino',
  process.env.API_KEY
);

// Make authenticated requests
const stats = await api.getStats();
const games = await api.getSettledGames({ limit: 10 });
```

## Troubleshooting

### Common Issues

**"Invalid API key" Error**

* Verify the API key is correct
* Check for extra spaces or characters
* Ensure the key hasn't expired

**"API key required" Error**

* Make sure the API key is included in headers
* Check environment variable configuration
* Verify the header name is correct

**Rate Limiting Issues**

* Implement exponential backoff
* Use multiple API keys if available
* Monitor rate limit headers

### Debug Mode

```typescript theme={null}
// Enable debug logging
const DEBUG = process.env.NODE_ENV === 'development';

if (DEBUG) {
  console.log('API Key:', apiKey ? 'Present' : 'Missing');
  console.log('Request Headers:', headers);
  console.log('Response Status:', response.status);
}
```

## Support

For authentication issues:

* **Documentation**: This documentation
* **Community**: [Discord Server](https://discord.gg/whisky-gaming)
* **Issues**: [GitHub Issues](https://github.com/weknowyourgame/whisky-gaming/issues)
* **Email**: [api@whisky.casino](mailto:api@whisky.casino)
