Skip to main content

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

  1. Go to Deployxa Dashboard
  2. Click "New Project"
  3. Select your GitHub repository
  4. Deployxa will automatically detect FastAPI
  5. Click "Deploy"

Your app will be live in under 60 seconds!

Configuration

Detected Settings

Deployxa automatically detects these settings:

SettingValue
FrameworkFastAPI
Build Commandpip install -r requirements.txt
Output DirectoryN/A
Start Commanduvicorn main:app --host 0.0.0.0 --port 8000
Port8000

Custom Configuration

If you need to customize settings:

  1. Go to ProjectSettingsBuild
  2. Modify settings as needed
  3. 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

  1. Go to ProjectEnvironment
  2. Click "Add Variable"
  3. Enter key and value
  4. 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

  1. Go to ProjectDomains
  2. Click "Add Domain"
  3. Enter your domain (e.g., example.com)
  4. Configure DNS records
  5. 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

  1. Go to ProjectLogs
  2. 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

  1. Go to ProjectAnalytics
  2. 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:

  1. Check runtime logs for errors
  2. Verify environment variables
  3. Check database connection
  4. Ensure all dependencies are installed
  5. Check for syntax errors in code

Database Connection Failed

Problem: sqlalchemy.exc.OperationalError

Solution:

  1. Verify DATABASE_URL is correct
  2. Check database host and port
  3. Ensure database exists
  4. Check firewall rules
  5. Verify database user permissions

Module Not Found

Problem: ModuleNotFoundError: No module named 'fastapi'

Solution:

  1. Check requirements.txt includes FastAPI
  2. Verify build command installs dependencies
  3. Check build logs for installation errors
  4. Redeploy

Slow Response Times

Problem: Application responds slowly

Solution:

  1. Increase Uvicorn workers
  2. Enable caching
  3. Optimize database queries
  4. Use connection pooling
  5. Upgrade plan for more resources

API Documentation Not Accessible

Problem: /docs returns 404

Solution:

  1. Ensure FastAPI is properly configured
  2. Check docs_url is not disabled
  3. Verify app is running correctly
  4. 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 .env file
  • Use .env.example as 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"}

Resources


Need Help? Contact support@deployxa.com or join our community Discord.