API Authentication
Trainwave provides secure authentication methods for accessing the API. This guide covers everything you need to know about authenticating your API requests.
Quick Start
# Generate an API key in the dashboard
wave auth create-token --name "My API Key"
# Use the key in your requests
curl -H "Accept: application/json" \
-H "X-API-KEY: your-api-key" \
https://backend.trainwave.ai/api/v1/jobs/
Authentication Methods
1. API Key Authentication (Recommended)
API keys are the recommended method for programmatic access. They’re secure, easy to manage, and provide fine-grained control.
Generating an API Key
- Log in to Trainwave Dashboard
- Navigate to Settings → API Keys
- Click “Generate New Key”
- Set a descriptive name and permissions
- Copy the key immediately (it won’t be shown again)
Using API Keys
Include the key in the X-API-KEY
header:
# Python example
import requests
headers = {
"Accept": "application/json",
"X-API-KEY": "your-api-key"
}
response = requests.get(
"https://backend.trainwave.ai/api/v1/jobs/",
headers=headers
)
// JavaScript example
const response = await fetch("https://backend.trainwave.ai/api/v1/jobs/", {
headers: {
Accept: "application/json",
"X-API-KEY": "your-api-key",
},
});
// Go example
client := &http.Client{}
req, _ := http.NewRequest("GET", "https://backend.trainwave.ai/api/v1/jobs/", nil)
req.Header.Add("Accept", "application/json")
req.Header.Add("X-API-KEY", "your-api-key")
resp, _ := client.Do(req)
2. Session-based Authentication
For web applications, you can use session-based authentication with cookies and CSRF tokens.
Login Flow
- User submits credentials
- Server creates a session
- Client stores session cookie
- CSRF token required for mutations
Example login request:
import requests
session = requests.Session()
# Get CSRF token
response = session.get('https://backend.trainwave.ai/auth/csrf/')
csrf_token = response.cookies['csrftoken']
# Login
login_data = {
'email': 'user@example.com',
'password': 'your-password'
}
headers = {
'X-CSRFToken': csrf_token,
'Content-Type': 'application/json'
}
response = session.post(
'https://backend.trainwave.ai/auth/v1/login/',
json=login_data,
headers=headers
)
Security Best Practices
1. API Key Management
✅ DO:
- Store API keys in environment variables
- Use different keys for different environments
- Rotate keys regularly
- Set appropriate permissions
- Monitor key usage
❌ DON’T:
- Commit API keys to version control
- Share keys between teams
- Use production keys in development
- Store keys in client-side code
Example using environment variables:
# config.py
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv('TRAINWAVE_API_KEY')
if not API_KEY:
raise ValueError("TRAINWAVE_API_KEY environment variable is required")
2. Key Rotation
Regularly rotate your API keys to minimize security risks:
# Generate a new key
wave auth create-token --name "New Production Key"
# Update your applications with the new key
export TRAINWAVE_API_KEY="new-key"
# Revoke the old key
wave auth revoke-token old-key-id
3. Error Handling
Always handle authentication errors gracefully:
def make_api_request(url):
try:
response = requests.get(
url,
headers={"X-API-KEY": API_KEY}
)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
logger.error("Invalid API key")
# Implement retry or notification logic
elif e.response.status_code == 403:
logger.error("Insufficient permissions")
raise
4. Rate Limiting
Implement exponential backoff for rate limits:
import time
from requests.exceptions import RequestException
def api_request_with_retry(url, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.get(
url,
headers={"X-API-KEY": API_KEY}
)
response.raise_for_status()
return response.json()
except RequestException as e:
if e.response.status_code == 429: # Rate limit exceeded
if attempt == max_retries - 1:
raise
sleep_time = (2 ** attempt) * 0.1 # Exponential backoff
time.sleep(sleep_time)
else:
raise
Troubleshooting
Common Issues
-
Invalid API Key
{ "success": false, "error": { "code": "invalid_api_key", "message": "The provided API key is invalid or expired" } }
Solution: Verify your API key is correct and active in the dashboard.
-
Missing CSRF Token
{ "success": false, "error": { "code": "csrf_token_missing", "message": "CSRF token missing or incorrect" } }
Solution: Include the CSRF token in your request headers for mutations.
-
Rate Limit Exceeded
{ "success": false, "error": { "code": "rate_limit_exceeded", "message": "Too many requests" } }
Solution: Implement rate limiting and exponential backoff in your client.
Testing Authentication
Use our test endpoints to verify your authentication setup:
# Test API key authentication
curl -H "X-API-KEY: your-api-key" \
https://backend.trainwave.ai/api/v1/auth/test/
# Test session authentication
curl -b "session=your-session-cookie" \
-H "X-CSRFToken: your-csrf-token" \
https://backend.trainwave.ai/api/v1/auth/test/
Enterprise SSO
Enterprise customers can configure Single Sign-On (SSO) with:
- SAML 2.0
- OpenID Connect
- Active Directory
Contact enterprise@trainwave.ai for SSO setup.
Support
- Authentication issues: auth-support@trainwave.ai
- Security concerns: security@trainwave.ai
- Documentation: docs@trainwave.ai