Bastio
API Documentation

API Authentication

Complete guide to authenticating with Bastio's API endpoints.

API Authentication

Bastio uses API keys for authentication. All API requests must include a valid API key in the Authorization header.

API Key Format

Bastio API keys follow this format:

bastio_sk_[random_string]

Authentication Methods

Include your API key in the Authorization header:

Authorization: Bearer bastio_sk_your_api_key_here

2. Header Authentication

Alternative header format:

X-Bastio-API-Key: bastio_sk_your_api_key_here

Creating API Keys

Via Dashboard

  1. Navigate to Dashboard > API Keys
  2. Click "Generate New Key"
  3. Configure key settings:
    • Name: Descriptive name for the key
    • Environment: Production, Staging, or Development
    • Permissions: Select allowed endpoints
    • Rate Limits: Set request limits
    • IP Restrictions: Whitelist specific IPs (recommended)

API Key Configuration

Permissions

Configure specific permissions for each API key:

  • Chat Completions - /v1/chat/completions
  • Completions - /v1/completions
  • Embeddings - /v1/embeddings
  • Images - /v1/images/generations
  • Audio - /v1/audio/transcriptions
  • Analytics - Access to usage analytics
  • ⚠️ Admin - Full account access (use sparingly)

Rate Limits

Set appropriate limits based on your usage:

{
  "rateLimit": {
    "requests": 1000,
    "period": "hour",
    "burst": 100
  }
}

IP Restrictions

Enhance security by restricting API key usage to specific IP addresses:

{
  "ipWhitelist": [
    "203.0.113.0/24",
    "198.51.100.42"
  ]
}

Request Examples

cURL

curl -X POST https://api.bastio.com/v1/chat/completions \
  -H "Authorization: Bearer bastio_sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4",
    "messages": [
      {"role": "user", "content": "Hello!"}
    ]
  }'

Python

import openai

# Using OpenAI client with Bastio
client = openai.OpenAI(
    api_key="bastio_sk_your_api_key_here",
    base_url="https://api.bastio.com/v1"
)

response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello!"}]
)

JavaScript

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'bastio_sk_your_api_key_here',
  baseURL: 'https://api.bastio.com/v1'
});

const completion = await client.chat.completions.create({
  model: 'gpt-4',
  messages: [{ role: 'user', content: 'Hello!' }]
});

Go

import "github.com/sashabaranov/go-openai"

config := openai.DefaultConfig("bastio_sk_your_api_key_here")
config.BaseURL = "https://api.bastio.com/v1"
client := openai.NewClientWithConfig(config)

Environment Variables

Store API keys securely using environment variables:

Development

# .env file
BASTIO_API_KEY=bastio_sk_your_development_key_here
BASTIO_BASE_URL=https://api.bastio.com/v1

Production

# Set in your deployment environment
export BASTIO_API_KEY="bastio_sk_your_production_key_here"
export BASTIO_BASE_URL="https://api.bastio.com/v1"

Security Best Practices

1. Key Management

  • 🔐 Never commit API keys to version control
  • 🔄 Rotate keys regularly (every 90 days recommended)
  • 🏷️ Use descriptive names to identify key usage
  • 🗑️ Delete unused keys immediately

2. Environment Separation

Use different API keys for different environments:

# Development
BASTIO_API_KEY=bastio_sk_dev_12345...

# Staging  
BASTIO_API_KEY=bastio_sk_staging_67890...

# Production
BASTIO_API_KEY=bastio_sk_prod_abcdef...

3. IP Whitelisting

Restrict API key usage to known IP addresses:

{
  "name": "Production Server",
  "permissions": ["chat_completions"],
  "ipWhitelist": ["203.0.113.10", "203.0.113.11"],
  "rateLimit": {
    "requests": 10000,
    "period": "hour"
  }
}

4. Minimal Permissions

Grant only the permissions needed:

{
  "name": "Chat Bot API Key",
  "permissions": ["chat_completions"],
  "excludePermissions": ["admin", "analytics"]
}

Error Handling

Authentication Errors

401 Unauthorized

{
  "error": {
    "message": "Invalid API key provided",
    "type": "authentication_error",
    "code": "invalid_api_key"
  }
}

Common causes:

  • Missing Authorization header
  • Incorrect API key format
  • Expired or revoked API key

403 Forbidden

{
  "error": {
    "message": "API key does not have permission for this endpoint",
    "type": "permission_error", 
    "code": "insufficient_permissions"
  }
}

Common causes:

  • API key lacks required permissions
  • Request from non-whitelisted IP address
  • Endpoint requires admin privileges

429 Rate Limited

{
  "error": {
    "message": "Rate limit exceeded",
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "details": {
      "limit": 1000,
      "remaining": 0,
      "resetTime": "2024-01-15T10:30:00Z"
    }
  }
}

Error Handling Code

import openai
from openai import AuthenticationError, PermissionDeniedError, RateLimitError

try:
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": "Hello!"}]
    )
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except PermissionDeniedError as e:
    print(f"Permission denied: {e}")
except RateLimitError as e:
    print(f"Rate limit exceeded: {e}")

Testing Authentication

Test Script

#!/bin/bash

API_KEY="bastio_sk_your_api_key_here"
BASE_URL="https://api.bastio.com/v1"

# Test authentication
echo "Testing API authentication..."
response=$(curl -s -w "%{http_code}" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-3.5-turbo","messages":[{"role":"user","content":"test"}],"max_tokens":5}' \
  "$BASE_URL/chat/completions")

http_code="${response: -3}"

if [ "$http_code" -eq 200 ]; then
    echo "✅ Authentication successful"
else
    echo "❌ Authentication failed (HTTP $http_code)"
fi

Test with Multiple Keys

def test_api_keys():
    keys = [
        ("development", "bastio_sk_dev_123..."),
        ("production", "bastio_sk_prod_abc...")
    ]
    
    for env, key in keys:
        client = openai.OpenAI(
            api_key=key,
            base_url="https://api.bastio.com/v1"
        )
        
        try:
            response = client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[{"role": "user", "content": "test"}],
                max_tokens=5
            )
            print(f"✅ {env}: Authentication successful")
        except Exception as e:
            print(f"❌ {env}: Authentication failed - {e}")

Monitoring API Keys

Usage Analytics

Monitor API key usage in the dashboard:

  • Request Count: Total requests per key
  • Error Rate: Authentication and permission errors
  • Geographic Usage: Requests by location
  • Timestamp Analysis: Usage patterns over time

Alerts

Set up alerts for:

  • High error rates (>5% authentication failures)
  • Unusual geographic usage
  • Rate limit approaches
  • New IP addresses (if using IP restrictions)

Migration from Other Providers

From OpenAI

- const client = new OpenAI({
-   apiKey: process.env.OPENAI_API_KEY
- });

+ const client = new OpenAI({
+   apiKey: process.env.BASTIO_API_KEY,
+   baseURL: 'https://api.bastio.com/v1'
+ });

From Anthropic

- const client = new Anthropic({
-   apiKey: process.env.ANTHROPIC_API_KEY
- });

+ const client = new Anthropic({
+   apiKey: process.env.BASTIO_API_KEY,
+   baseURL: 'https://api.bastio.com/v1'
+ });

Advanced Authentication

Custom Headers

Pass additional context for enhanced security:

const completion = await client.chat.completions.create({
  model: 'gpt-4',
  messages: [{ role: 'user', content: 'Hello!' }]
}, {
  headers: {
    'X-User-ID': 'user_123',
    'X-Session-ID': 'session_456',
    'X-App-Version': '1.2.3'
  }
});

Webhook Authentication

For webhook endpoints, Bastio includes signature verification:

import hmac
import hashlib

def verify_webhook_signature(payload, signature, secret):
    expected_signature = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(f"sha256={expected_signature}", signature)

Next Steps