Skip to content
Back to Deployment

Deploying FastAPI Apps

Async Python API framework with auto OpenAPI docs, deploy via Uvicorn/Gunicorn to container or serverless.

PlatformsIntermediate

Why

FastAPI leverages async/await and Pydantic for request validation, achieving Node.js-level performance in Python. Auto-generated OpenAPI docs and type safety reduce boilerplate and bugs.

When

Use FastAPI for modern Python APIs needing async I/O, auto-docs, and validation. Prefer over Flask for new projects; choose Flask for legacy WSGI middleware.

How

1. ASGI server — uvicorn app:app --host 0.0.0.0 --port 8000 2. Production — gunicorn app:app -w 4 -k uvicorn.workers.UvicornWorker 3. Docker — python:3.12-slim, uvicorn CMD 4. Serverless — mangum adapter for Lambda, or Vercel Python 5. Auto docs — /docs (Swagger) and /redoc (ReDoc) auto-generated 6. Async — use async def for I/O-bound, sync def offloaded to threadpool 7. CORS — CORSMiddleware for cross-origin frontend

Example

# main.py from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.get("/health") async def health(): return {"ok": True} @app.post("/items") async def create(item: Item): return {"created": item} # Dockerfile FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD ["gunicorn", "main:app", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "-b", "0.0.0.0:8000"] # Vercel — api/index.py from mangum import Mangum from main import app handler = Mangum(app)

Common Problems

  • ⚠Blocking call in async route — sync I/O in async def blocks event loop, use run_in_executor or sync def
  • ⚠Uvicorn workers not utilizing CPU — single worker = single core, use Gunicorn with UvicornWorker
  • ⚠Pydantic v1 vs v2 mismatch — FastAPI version pins Pydantic, mixing causes runtime errors

Best Practices

  • ✓Use async def for I/O-bound handlers (DB, HTTP) and sync def for CPU-bound — FastAPI offloads sync to threadpool
  • ✓Always define Pydantic models for request/response — gives validation, docs, and type safety for free
  • ✓Set up health checks and graceful shutdown — handle SIGTERM to drain in-flight requests before exit

FAQ