Making Your First API Call#
This guide walks you through making your first authenticated API call to the ops-db-api.
Prerequisites#
Before proceeding, ensure you have:
Completed the Installation steps
The API server running locally
curlor a similar HTTP client installed
Starting the API Server#
If the server isn’t already running, start it:
cd ops-db-api
source venv/bin/activate
uvicorn ccat_ops_db_api.main:app --reload --port 8000
The server will start on http://localhost:8000.
Accessing the API Documentation#
FastAPI provides interactive API documentation out of the box:
- Swagger UI (Recommended for exploration)
Visit: http://localhost:8000/docs
- ReDoc (Alternative documentation view)
Visit: http://localhost:8000/redoc
The Swagger UI allows you to:
Browse all available endpoints
View request/response schemas
Test endpoints directly from your browser
See authentication requirements
Making an Unauthenticated Request#
Start with a simple health check that doesn’t require authentication:
curl http://localhost:8000/health
Expected response:
{
"status": "healthy",
"database": "connected",
"redis": "connected",
"transaction_buffer": {
"size": 0,
"failed": 0
},
"background_processor": "running"
}
This confirms that:
The API is running
Database connection is working
Redis connection is working
Transaction buffering system is operational
Getting an API Token#
For authenticated requests, you need an API token. There are several ways to obtain one:
Method 1: Demo Token (Development Only)#
For local development, you can use a demo token endpoint:
curl -X POST http://localhost:8000/api/demo/create-demo-token
Expected response:
{
"token": "demo_token_abc123xyz789...",
"user_id": 1,
"role": "admin"
}
Warning
Demo tokens should never be used in production. They are only for local testing.
Method 2: Admin Script (Recommended)#
Use the admin script to create a proper API token:
# Create an admin user if not exists
./create_admin_user.sh
# Then use the UI or CLI to generate a token
Method 3: GitHub OAuth (For UI Users)#
If you have GitHub OAuth configured, you can log in through the web UI and generate a token from your profile.
Making an Authenticated Request#
Once you have a token, include it in the Authorization header:
Format#
curl -H "Authorization: Bearer YOUR_TOKEN" \
http://localhost:8000/ENDPOINT
Example: Get Current User#
TOKEN="your_actual_token_here"
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8000/auth/me
Expected response:
{
"id": 1,
"username": "admin",
"email": "admin@example.com",
"full_name": "Admin User",
"roles": ["admin"],
"is_active": true,
"created_at": "2025-01-01T00:00:00Z"
}
Example: List Instruments#
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8000/instruments/
Expected response:
[
{
"id": 1,
"name": "CCAT-prime",
"description": "Prime-Cam instrument",
"is_active": true
}
]
Example: Get Transfer Overview#
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8000/api/transfer/overview
Expected response:
{
"total_packages": 42,
"pending_transfers": 3,
"active_transfers": 2,
"completed_transfers": 37,
"failed_transfers": 0,
"total_data_size_gb": 1250.5
}
Making a POST Request#
To create or modify data, use POST requests with JSON payloads:
Example: Create User Preference#
curl -X POST http://localhost:8000/api/demo/update-user-preferences \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"user_id": 1,
"preferences": {
"theme": "dark",
"language": "en",
"notifications": true
}
}'
Expected response:
{
"status": "success",
"message": "User preferences updated",
"transaction_id": "abc123"
}
Using the Interactive Documentation#
The easiest way to explore the API is through Swagger UI at http://localhost:8000/docs:
Step 2: Test an Endpoint#
Expand any endpoint (e.g.,
GET /instruments/)Click Try it out
Fill in any required parameters
Click Execute
View the response below
Step 3: View Request/Response Schemas#
Scroll down to see the Schemas section
Each data model is documented with field types and constraints
Click on schemas to expand and explore
Common Response Codes#
Understanding HTTP status codes:
- 200 OK
Request succeeded, data returned
- 201 Created
Resource created successfully
- 400 Bad Request
Invalid request format or missing required fields
- 401 Unauthorized
Missing or invalid authentication token
- 403 Forbidden
Valid token but insufficient permissions
- 404 Not Found
Requested resource doesn’t exist
- 500 Internal Server Error
Server error (check logs)
Testing Transaction Buffering#
If you’re running with SITE_TYPE=secondary, you can test the transaction buffering system:
Create a Buffered Observation#
curl -X POST http://localhost:8000/api/demo/create-observation \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"obs_data": {
"obs_unit_id": 1,
"start_time": "2025-01-01T00:00:00Z",
"end_time": "2025-01-01T01:00:00Z",
"mean_pwv": 2.5,
"mean_elevation": 45.0,
"package_name": "test_package_001",
"instrument_module_configuration_id": 1
},
"raw_files": [
{
"name": "test_file_001.fits",
"path": "/data/test_file_001.fits",
"size": 1024000,
"checksum": "abc123",
"file_type": "fits"
}
]
}'
Check Buffer Status#
curl http://localhost:8000/buffer-stats
Expected response:
{
"pending_transactions": 1,
"failed_transactions": 0,
"processing_rate": 1.0
}
Troubleshooting#
Connection Refused#
If curl can’t connect:
Verify the API server is running
Check the correct port (default: 8000)
Try
http://127.0.0.1:8000instead oflocalhost
Empty Response or Error#
If you get unexpected responses:
Check the API logs in the terminal where uvicorn is running
Verify your database has data (some endpoints return empty arrays for empty tables)
Try the same request in Swagger UI for better error messages
Next Steps#
Now that you can make API calls, explore:
Running Locally with Docker Compose - Set up the full stack with Docker Compose
Simple Read Endpoint - Build your own endpoints
System Overview - Understand how the API works
Transaction Buffering Overview - Learn about the buffering system
Using Python to Make API Calls#
For programmatic access, use the requests library:
import requests
BASE_URL = "http://localhost:8000"
TOKEN = "your_token_here"
headers = {
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json"
}
# Health check
response = requests.get(f"{BASE_URL}/health")
print(response.json())
# Authenticated request
response = requests.get(f"{BASE_URL}/auth/me", headers=headers)
print(response.json())
# POST request
data = {
"user_id": 1,
"preferences": {"theme": "dark"}
}
response = requests.post(
f"{BASE_URL}/api/demo/update-user-preferences",
headers=headers,
json=data
)
print(response.json())
See Service Scripts Best Practices for production-ready examples.