Deploy FastAPI
This guide will help you deploy a FastAPI application to Deployxa.
Overview
FastAPI is a modern, fast Python web framework for building APIs with automatic documentation. Deployxa provides optimized deployments for FastAPI with automatic configuration.
Features:
- Automatic framework detection
- Python 3.8+ support
- PostgreSQL and MySQL support
- Uvicorn ASGI server
- Automatic API documentation (Swagger/OpenAPI)
- Automatic HTTPS
- Global CDN
Prerequisites
- A FastAPI application
- A GitHub repository with your code
- A Deployxa account
- PostgreSQL or MySQL database (optional)
Quick Start
1. Create Your FastAPI App
If you don't have a FastAPI app yet:
mkdir my-fastapi-app
cd my-fastapi-app
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install fastapi uvicorn[standard] sqlalchemy psycopg2-binary
Create main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "Deployxa"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
2. Create requirements.txt
pip freeze > requirements.txt
Ensure it includes:
fastapi>=0.109.0
uvicorn[standard]>=0.27.0
sqlalchemy>=2.0.25
psycopg2-binary>=2.9.9
3. Push to GitHub
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/my-fastapi-app.git
git push -u origin main
4. Deploy to Deployxa
- Go to Deployxa Dashboard
- Click "New Project"
- Select your GitHub repository
- Deployxa will automatically detect FastAPI
- Click "Deploy"
Your app will be live in under 60 seconds!
Configuration
Detected Settings
Deployxa automatically detects these settings:
| Setting | Value |
|---|---|
| Framework | FastAPI |
| Build Command | pip install -r requirements.txt |
| Output Directory | N/A |
| Start Command | uvicorn main:app --host 0.0.0.0 --port 8000 |
| Port | 8000 |
Custom Configuration
If you need to customize settings:
- Go to Project → Settings → Build
- Modify settings as needed
- Save changes
Example Custom Settings:
{
"buildCommand": "pip install -r requirements.txt",
"startCommand": "uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4"
}
Environment Variables
Adding Environment Variables
- Go to Project → Environment
- Click "Add Variable"
- Enter key and value
- Click "Save"
Common FastAPI Environment Variables:
ENVIRONMENT=production
SECRET_KEY=your-secret-key-here
DEBUG=False
# Database (optional)
DATABASE_URL=postgresql://user:pass@host:5432/dbname
# API Keys
API_KEY=your-api-key
Using Environment Variables
In your FastAPI app:
import os
from fastapi import FastAPI
app = FastAPI()
SECRET_KEY = os.environ.get('SECRET_KEY')
DATABASE_URL = os.environ.get('DATABASE_URL')
@app.get("/")
def read_root():
return {"Hello": "Deployxa"}
Database Configuration
Using SQLAlchemy
For database operations:
pip install sqlalchemy psycopg2-binary
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
SQLALCHEMY_DATABASE_URL = os.environ.get('DATABASE_URL')
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Database Models
from sqlalchemy import Column, Integer, String
from .database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)
email = Column(String, unique=True, index=True)
Database Migrations
Use Alembic for migrations:
pip install alembic
alembic init alembic
Configure alembic.ini:
sqlalchemy.url = postgresql://user:pass@host:5432/dbname
Run migrations:
alembic upgrade head
API Documentation
Automatic Documentation
FastAPI automatically generates:
- Swagger UI:
/docs - ReDoc:
/redoc - OpenAPI JSON:
/openapi.json
Access these endpoints after deployment:
- Swagger UI:
https://your-app.deployxa.app/docs - ReDoc:
https://your-app.deployxa.app/redoc
Custom Documentation
from fastapi import FastAPI
app = FastAPI(
title="My API",
description="API for my application",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
)
Custom Domains
Adding a Custom Domain
- Go to Project → Domains
- Click "Add Domain"
- Enter your domain (e.g.,
example.com) - Configure DNS records
- Wait for verification
DNS Configuration
For Apex Domain (example.com):
Type: A
Name: @
Value: 76.76.21.21
For Subdomain (www.example.com):
Type: CNAME
Name: www
Value: cname.deployxa.com
Performance Optimization
Enable Multiple Workers
Configure Uvicorn workers based on CPU cores:
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
Formula: (2 x CPU_CORES) + 1
Enable Caching
Use FastAPI caching:
pip install fastapi-cache2
from fastapi import FastAPI
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from redis import asyncio as aioredis
app = FastAPI()
@app.on_event("startup")
async def startup():
redis = aioredis.from_url("redis://localhost")
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
Database Connection Pooling
Use connection pooling for better performance:
from sqlalchemy import create_engine
from sqlalchemy.pool import QueuePool
engine = create_engine(
DATABASE_URL,
poolclass=QueuePool,
pool_size=10,
max_overflow=20,
pool_timeout=30
)
Monitoring
Viewing Logs
- Go to Project → Logs
- Select log type:
- Build Logs: Deployment process
- Runtime Logs: Application output
- Error Logs: Application errors
FastAPI Logging
Configure logging:
import logging
from fastapi import FastAPI
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
@app.get("/")
def read_root():
logger.info("Root endpoint accessed")
return {"Hello": "Deployxa"}
Monitoring Metrics
- Go to Project → Analytics
- View metrics:
- Request count
- Response times
- Error rates
- Bandwidth usage
- CPU/RAM usage
Health Checks
Deployxa automatically monitors your application:
- HTTP health checks every 30 seconds
- Automatic restart on failure
- Alerts on consecutive failures
Add a health check endpoint:
@app.get("/health")
def health_check():
return {"status": "healthy"}
Troubleshooting
500 Internal Server Error
Problem: Application returns 500 error
Solution:
- Check runtime logs for errors
- Verify environment variables
- Check database connection
- Ensure all dependencies are installed
- Check for syntax errors in code
Database Connection Failed
Problem: sqlalchemy.exc.OperationalError
Solution:
- Verify DATABASE_URL is correct
- Check database host and port
- Ensure database exists
- Check firewall rules
- Verify database user permissions
Module Not Found
Problem: ModuleNotFoundError: No module named 'fastapi'
Solution:
- Check requirements.txt includes FastAPI
- Verify build command installs dependencies
- Check build logs for installation errors
- Redeploy
Slow Response Times
Problem: Application responds slowly
Solution:
- Increase Uvicorn workers
- Enable caching
- Optimize database queries
- Use connection pooling
- Upgrade plan for more resources
API Documentation Not Accessible
Problem: /docs returns 404
Solution:
- Ensure FastAPI is properly configured
- Check docs_url is not disabled
- Verify app is running correctly
- Check runtime logs for errors
Best Practices
Project Structure
my-fastapi-app/
├── main.py
├── requirements.txt
├── .env.example
├── alembic/
│ └── versions/
├── alembic.ini
├── app/
│ ├── __init__.py
│ ├── models.py
│ ├── schemas.py
│ ├── crud.py
│ └── database.py
└── README.md
Environment Variables
- Never commit
.envfile - Use
.env.exampleas template - Rotate SECRET_KEY regularly
- Use different values per environment
Security
- Keep FastAPI updated
- Use HTTPS only
- Validate all inputs
- Use parameterized queries
- Implement rate limiting
- Use authentication (JWT/OAuth)
- Enable CORS properly
Performance
- Use multiple Uvicorn workers
- Enable caching
- Optimize database queries
- Use connection pooling
- Use async/await properly
- Enable compression
Database
- Use connection pooling
- Index frequently queried columns
- Use transactions for complex operations
- Backup database regularly
- Use SQLAlchemy for complex queries
Advanced Configuration
Custom Uvicorn Configuration
Create uvicorn.conf.py:
bind = '0.0.0.0:8000'
workers = 4
worker_class = 'uvicorn.workers.UvicornWorker'
timeout = 120
keepalive = 5
accesslog = '-'
errorlog = '-'
loglevel = 'info'
Update start command:
uvicorn main:app --config uvicorn.conf.py
Background Tasks
Use FastAPI background tasks:
from fastapi import BackgroundTasks
def send_email(email: str, message: str):
# Send email logic
pass
@app.post("/send-email/")
async def send_email_endpoint(
email: str,
background_tasks: BackgroundTasks
):
background_tasks.add_task(send_email, email, "Hello")
return {"message": "Email will be sent"}
Middleware
Add custom middleware:
from fastapi import Request
import time
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
CORS Configuration
Configure CORS:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://example.com"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Examples
Basic FastAPI App
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "Deployxa"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
With Database
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from . import models, schemas, database
app = FastAPI()
@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(database.get_db)):
db_user = models.User(**user.dict())
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
REST API
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
items = []
@app.get("/items/")
def get_items():
return items
@app.post("/items/")
def create_item(item: Item):
items.append(item)
return item
With Authentication
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import HTTPBearer
app = FastAPI()
security = HTTPBearer()
@app.get("/protected")
def protected_route(credentials = Depends(security)):
if credentials.credentials != "secret-token":
raise HTTPException(status_code=401)
return {"message": "Access granted"}
Related Topics
Resources
Need Help? Contact support@deployxa.com or join our community Discord.