FastAPI
High-performance Python API framework - automatic OpenAPI docs, Pydantic validation, async/await support, and type annotations that serve as the schema.
skill: FastAPI category: Backend tags: [FastAPI, Python, REST API, Pydantic, Async] readingTime: 6
FastAPI is the default choice for Python REST APIs - it's faster than Flask, generates automatic OpenAPI docs, and enforces types via Pydantic. For ML-serving specifically, FastAPI + Uvicorn is the standard stack. Django REST Framework is better for Django ORM-heavy apps.
Workflow
- Set up FastAPI with UvicornUvicorn is the ASGI server that runs FastAPI - async-capable, production-grade, and the recommended server from the FastAPI docs.
- Define request/response models with PydanticPydantic models are FastAPI's schema layer - they validate incoming data, generate OpenAPI docs, and provide type annotations in one declaration.
- Use dependency injection for shared logicFastAPI's dependency system handles DB sessions, authentication, and pagination without repeating code in every endpoint.
- Write async endpoints for I/O-bound tasksAsync endpoints don't block the event loop on network I/O - enabling FastAPI to handle many concurrent requests on a single process.
- Run background tasksBackground tasks run after the response is sent - useful for sending emails, logging, or triggering webhooks without making the client wait.
Output Format
FastAPI app with Pydantic models, dependency injection, async endpoints, and background tasks.
app/
├── main.py # FastAPI instance, router includes
├── api/
│ ├── users.py # APIRouter for /users
│ └── auth.py
├── models/
│ ├── schemas.py # Pydantic request/response models
│ └── db.py # SQLAlchemy models
├── deps.py # Shared dependencies
└── core/
└── config.pyExamples
Input
Output
Edge Cases & Gotchas
- Blocking calls in async endpoints - Using sync DB calls (psycopg2, sqlite3) in async endpoints blocks the thread pool. Use asyncpg or SQLAlchemy async session for true async I/O.
- Pydantic v1 vs v2 - FastAPI 0.100+ uses Pydantic v2. Many tutorials show v1 syntax (.dict() vs .model_dump(), Config class vs model_config). Mixing them causes errors.
- Response model leaking sensitive fields - If response_model is the DB model (not a separate schema), it may serialize password hashes or internal fields. Always use a dedicated response schema.
- CORS for browser clients - Add CORSMiddleware from fastapi.middleware.cors before any other middleware. Without it, browser fetch to a different port fails silently.
When to Break These Rules
- Use Django + DRF when the project is data-heavy with complex ORM relationships, admin panel requirements, or built-in auth and permissions.
- Use Flask for very simple scripts or internal tools where FastAPI's structure is overkill.
Reference Files
https://fastapi.tiangolo.com/https://docs.pydantic.dev/