FastAPI: Python API development framework

FastAPI is a modern Web API framework based on Python Type Hints, suitable for RESTful API, microservices, data services and AI/LLM application backends.

Core features:

  • Parameter analysis and verification of Type Hints driver.
  • Pydantic data model.
  • Automatically generate OpenAPI / Swagger documents.
  • Dependency Injection (dependency injection).
  • ASGI and asynchronous I/O.
  • Flexible combination of database, authentication and middleware components.

1. Architecture and Startup

FastAPI
├── Starlette
│   ├── Routing
│   ├── Middleware
│   ├── Request / Response
│   └── ASGI
│
├── Pydantic
│   ├── Type Validation
│   ├── Serialization
│   └── JSON Schema
│
└── FastAPI Features
    ├── Dependency Injection
    ├── OpenAPI
    ├── Request / Response Validation
    └── Security Utilities

Installation:

pip install "fastapi[standard]"

Create main.py:

from fastapi import FastAPI

app = FastAPI(
    title="Example API",
    version="1.0.0",
)

@app.get("/")
def hello():
    return {"message": "Hello World"}

Development server:

fastapi dev main.py

Or:

uvicorn main:app --reload

Accessible by default:

http://127.0.0.1:8000

/docs       → Swagger UI
/redoc      → ReDoc
/openapi.json → OpenAPI Schema

--reload is only suitable for development environments.

2. Routing: Routing

FastAPI declares HTTP Endpoint using Decorator.

@app.get("/users")
def list_users():
    return []

@app.post("/users", status_code=201)
def create_user():
    return {"id": 1}

@app.get("/users/{user_id}")
def get_user(user_id: int):
    return {"user_id": user_id}

@app.delete("/users/{user_id}", status_code=204)
def delete_user(user_id: int):
    return None

Path Parameters

@app.get("/users/{user_id}")
def get_user(user_id: int):
    return {"id": user_id}

user_id resolves to an integer according to the type declaration.

If a value that cannot be parsed as an integer is passed in, FastAPI returns HTTP 422 Validation Error by default.

Query Parameters

@app.get("/users")
def list_users(
    page: int = 1,
    limit: int = 20,
    active: bool | None = None,
):
    return {
        "page": page,
        "limit": limit,
        "active": active,
    }

By default, simple type parameters that are not recognized as Path, Body, or Dependency are usually treated as Query Parameter.

Query Validation

It is recommended to use Annotated:

from typing import Annotated
from fastapi import Query

@app.get("/items")
def list_items(
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
):
    return {"limit": limit}

Among them:

  • ge:Greater than or equal。
  • le:Less than or equal。
  • min_length/max_length: String length constraints.
  • pattern: string regular constraint.

3. Pydantic: Data verification

Pydantic is one of the most important components of FastAPI.

Declare the data structure using BaseModel:

from pydantic import BaseModel, Field

class UserCreate(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    age: int = Field(ge=0, le=120)
    email: str

Request:

@app.post("/users")
def create_user(data: UserCreate):
    return data

FastAPI will be completed automatically:

  1. Parse JSON Request Body.
  2. Verified against Pydantic Model.
  3. Create a Python object.
  4. Returns 422 on validation errors.
  5. Add Schema to OpenAPI.

Optional and Default

class UserCreate(BaseModel):
    name: str
    nickname: str | None = None

Need to distinguish:

nickname: str | None

Indicates None is allowed, but the field is still required.

nickname: str | None = None

Indicates that the field can be omitted and the default value is None.

Field Validator

Pydantic v2 uses field_validator:

from pydantic import BaseModel, field_validator

class UserCreate(BaseModel):
    name: str

    @field_validator("name")
    @classmethod
    def validate_name(cls, value: str) -> str:
        value = value.strip()

        if not value:
            raise ValueError("Name cannot be empty")

        return value

Data serialization

user = UserCreate(name="Alice", age=25, email="a@example.com")

user.model_dump()
user.model_dump_json()

Pydantic v2 Common API:

APIfunction
model_validate()Create and validate models from input data
model_dump()Convert to Python dictionary
model_dump_json()Serialized to JSON
model_json_schema()Generate JSON Schema

4. Request Body and Response Model

FastAPI usually uses different models to describe the input and output.

from pydantic import BaseModel

class UserCreate(BaseModel):
    name: str
    password: str

class UserResponse(BaseModel):
    id: int
    name: str

Endpoint:

@app.post(
    "/users",
    response_model=UserResponse,
    status_code=201,
)
def create_user(data: UserCreate):
    # Example: Passwords should be hashed securely and persisted in actual projects
    return {
        "id": 1,
        "name": data.name,
        "password": data.password,
    }

response_model validates, serializes, and filters response fields.

password above is not in UserResponse and therefore will not appear in the final response.

However, database persistence, password security processing and sensitive information protection still need to be implemented at the business layer.

Value of Response Model

  • Guaranteed API Response structure.
  • Avoid accidentally exposing extra fields.
  • Automatically generate OpenAPI Response Schema.
  • Provides type and runtime data validation.

It can be understood as Response Serializer similar to DRF, but the interfaces and implementation mechanisms of the two are different.

5. Dependency Injection: Dependency injection

FastAPI uses Depends() to declare the dependencies required by Endpoint.

from typing import Annotated
from fastapi import Depends, Query

def pagination(
    page: int = Query(default=1, ge=1),
    limit: int = Query(default=20, ge=1, le=100),
):
    return {"page": page, "limit": limit}

@app.get("/users")
def list_users(
    pagination_params: Annotated[dict, Depends(pagination)],
):
    return pagination_params

The framework automatically executes pagination() and injects the result into Endpoint.

Common usage scenarios

  • Database Session.
  • Currently logged in user.
  • Permission verification.
  • Public Query Parameters.
  • External service Client.
  • Configuration object.

Dependency with yield

When you need to release resources after use, you can use yield:

from collections.abc import Generator
from sqlalchemy import create_engine
from sqlalchemy.orm import Session

engine = create_engine("postgresql+psycopg://user:password@localhost/db")

def get_db() -> Generator[Session, None, None]:
    with Session(engine) as session:
        yield session

Used in Endpoint:

@app.get("/users")
def list_users(
    db: Annotated[Session, Depends(get_db)],
):
    return {"message": "Database session available"}

Responsible for creating resources before yield and cleaning up resources when exiting the dependency context.

Real projects should read database connection information from environment variables.

Dependency Injection is one of the most distinguishing features between FastAPI and traditional functional API development.

6. APIRouter: Modular routing

Large projects should not put all Endpoint in main.py.

It is recommended to use APIRouter:

# routers/users.py

from fastapi import APIRouter

router = APIRouter(
    prefix="/users",
    tags=["users"],
)

@router.get("/")
def list_users():
    return []

Register to the main application:

# main.py

from fastapi import FastAPI
from routers.users import router as users_router

app = FastAPI()

app.include_router(
    users_router,
    prefix="/api/v1",
)

Final path:

GET /api/v1/users/

Recommended project structure:

app/
├── main.py
├── routers/
│   └── users.py
├── schemas/
│   └── user.py
├── models/
│   └── user.py
├── services/
│   └── user_service.py
├── dependencies.py
└── database.py

FastAPI There is no mandatory project directory structure.

routers, schemas, services, etc. are a common application layering method.

7. Async / Await and ASGI

FastAPI natively supports asynchronous Endpoint.

@app.get("/async")
async def async_endpoint():
    return {"message": "async"}

Ordinary synchronization functions are also supported:

@app.get("/sync")
def sync_endpoint():
    return {"message": "sync"}

async def and def

TypeExecution method
async defCoroutine executed by event loop
defFastAPI Synchronization is usually performed via a thread pool Endpoint

Use async I/O:

import httpx

@app.get("/external")
async def get_external_data():
    async with httpx.AsyncClient(timeout=10) as client:
        response = await client.get("https://example.com")
        response.raise_for_status()

    return {"status": response.status_code}

The main value of asynchrony

When a request needs to wait:

  • database.
  • HTTP API。
  • Redis。
  • File or network I/O.

Asynchronous I/O allows the event loop to continue processing other tasks while the current request is waiting.

Common mistakes

import time

@app.get("/bad")
async def bad():
    time.sleep(5)  # Blocking event loop
    return {}

Performing blocking operations directly within async def may affect other requests on the same event loop.

If you use synchronous database Client, the simple way is to use def Endpoint; if you use real asynchronous database Client, you can use async def in conjunction with await.

async does not automatically speed up CPU intensive calculations. For large-scale Pandas operations, model training, etc., process pools, task queues or independent Worker are usually required.

8. Database and ORM

FastAPI does not have built-in ORM.

Common combinations:

  • SQLAlchemy。
  • SQLModel。
  • PostgreSQL。
  • Alembic (database migration).

SQLAlchemy Session

from sqlalchemy import create_engine
from sqlalchemy.orm import Session

engine = create_engine(DATABASE_URL)

with Session(engine) as session:
    result = session.execute(...)

Asynchronous database usage:

from sqlalchemy.ext.asyncio import (
    create_async_engine,
    async_sessionmaker,
)

engine = create_async_engine(
    "postgresql+asyncpg://user:password@localhost/db"
)

SessionLocal = async_sessionmaker(
    engine,
    expire_on_commit=False,
)

Async Session Dependency

from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with SessionLocal() as session:
        yield session

Need to pay attention to:

  • Session Lifecycle should be managed per request or unit of work.
  • Multiple concurrent tasks should not share the same variable AsyncSession.
  • Database transactions should explicitly control commit() / rollback().
  • Database structure changes are typically managed by Alembic Migration.

Unlike the Django, the FastAPI does not offer uniformly integrated ORM, Migration and Admin systems.

9. Error Handling

FastAPI uses HTTPException to return the HTTP error.

from fastapi import HTTPException

@app.get("/users/{user_id}")
def get_user(user_id: int):
    if user_id != 1:
        raise HTTPException(
            status_code=404,
            detail="User not found",
        )

    return {"id": user_id}

Common status codes

status codemeaning
200OK
201Created
204No Content
400Bad Request
401Unauthorized
403Forbidden
404Not Found
409Conflict
422Validation Error
500Internal Server Error

FastAPI returns 422 for request parameter validation errors by default.

Custom exception handling

from fastapi import Request
from fastapi.responses import JSONResponse

class BusinessError(Exception):
    pass

@app.exception_handler(BusinessError)
async def business_error_handler(
    request: Request,
    exc: BusinessError,
):
    return JSONResponse(
        status_code=400,
        content={"detail": str(exc)},
    )

In production environments, it is recommended to unify the error response structure and avoid exposing database exceptions, internal paths, and sensitive debugging information to the client.

10. Middleware, CORS and certification

Middleware

Middleware executes common logic before the request enters Endpoint and before the response is returned to the client.

Request
   ↓
Middleware
   ↓
Routing / Endpoint
   ↓
Middleware
   ↓
Response

For example adding processing time:

import time
from fastapi import Request

@app.middleware("http")
async def add_process_time(
    request: Request,
    call_next,
):
    start = time.perf_counter()

    response = await call_next(request)

    duration = time.perf_counter() - start
    response.headers["X-Process-Time"] = str(duration)

    return response

CORS

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://example.com"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)

CORS mainly controls the cross-domain request behavior of the browser, not the identity authentication mechanism of the backend API.

OAuth2 / JWT

FastAPI provides security-related tools:

from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="/auth/token",
)

It can extract Bearer Token from the request and describe OpenAPI Security Scheme.

But you still need to implement it yourself:

  • Token verification.
  • Signature and expiration time checks.
  • User query.
  • Permission authorization.
  • Token cancellation and other business strategies.

Authentication is responsible for confirming the user's identity; Authorization is responsible for confirming whether the user can perform operations.

11. BackgroundTasks and Lifespan

BackgroundTasks

FastAPI supports performing simple background tasks after the response is sent.

from fastapi import BackgroundTasks

def write_log(message: str):
    with open("events.log", "a", encoding="utf-8") as f:
        f.write(message + "\n")

@app.post("/events")
def create_event(tasks: BackgroundTasks):
    tasks.add_task(write_log, "Event created")

    return {"status": "accepted"}

Suitable for simple, short-term tasks that do not require reliable persistence.

Important limitations:

  • BackgroundTasks usually still executes within the application process.
  • Process exit may cause tasks to be lost.
  • Does not provide reliable queues, persistence and complex retry mechanisms like Celery.

For model inference tasks, large-scale data processing, batch mailing, etc., Celery, RQ, or standalone tasks Worker should be used as appropriate.

Lifespan

Used to manage resources when the application is started and closed.

from contextlib import asynccontextmanager
from fastapi import FastAPI

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    print("Application starting")

    yield

    # Shutdown
    print("Application stopping")

app = FastAPI(lifespan=lifespan)

Common uses:

  • Initialize the connection pool.
  • Create HTTP Client.
  • Load the model.
  • Release shared resources.

Compared with the old @app.on_event("startup") / shutdown mechanism, new projects recommend the use of Lifespan.

12. OpenAPI and API documents

FastAPI automatically generates OpenAPI Schema based on routes, Pydantic Model and dependencies.

For example:

@app.get(
    "/users/{user_id}",
    response_model=UserResponse,
    summary="Get user",
    description="Retrieve user information by ID.",
    tags=["users"],
)
def get_user(user_id: int):
    return {"id": user_id, "name": "Alice"}

FastAPI will generate:

  • Path Parameter definition.
  • Query / Request Body Schema。
  • Response Schema。
  • Status Code。
  • Operation Metadata。

Available at:

/docs
/redoc
/openapi.json

View the documentation.

If the front end uses Orval, you can continue to use:

FastAPI
   ↓
OpenAPI Schema
   ↓
Orval
   ↓
TypeScript Client
   ↓
TanStack Query

Therefore, FastAPI is also suitable for the simultaneous development of front-end and back-end types of OpenAPI-first or Schema-driven.

13. Testing: Interface test

FastAPI often uses pytest and TestClient.

# main.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/healthz")
def health():
    return {"status": "ok"}

Test:

# test_main.py

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_health():
    response = client.get("/healthz")

    assert response.status_code == 200
    assert response.json() == {"status": "ok"}

Run:

pytest

Dependency Override

You can replace database, authentication and other dependencies during testing:

app.dependency_overrides[get_current_user] = (
    lambda: {"id": 1, "role": "admin"}
)

Override should be cleaned up after testing:

app.dependency_overrides.clear()

This enables tests to use Mock User, a test database, or mock external services without relying on real production resources.

For testing asynchronous database and complete Lifespan scenarios, further configuration of asynchronous testing tools and application life cycle management is required.

14. Deployment: Uvicorn, Gunicorn, Docker

FastAPI is ASGI Application and requires ASGI Server to handle the HTTP connection.

The most common is Uvicorn.

development environment

uvicorn main:app --reload

production environment

uvicorn main:app \
  --host 0.0.0.0 \
  --port 8000 \
  --workers 4

--workers starts multiple independent Worker processes to improve multi-core CPU utilization and process-level concurrent processing capabilities.

But please note:

  • Each Worker may have independent application resources and memory.
  • Large models can cause significant memory increases if loaded in every Worker.
  • The number of Worker is not always better, it should be determined in combination with CPU, memory and load testing.
  • The container orchestration environment can also adopt a single Worker/container and scale through multiple container replicas.

Works with Nginx

Client
   ↓
Nginx / HTTPS
   ↓
Uvicorn
   ↓
FastAPI
   ↓
Database / Redis / External Services

FastAPI officially provides fastapi run as the production mode startup command; you can also use Uvicorn directly.

Docker example

FROM python:3.12-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

EXPOSE 8000

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Production deployment also needs to be configured according to actual conditions:

  • Environment Variables / Secrets。
  • HTTPS / Reverse Proxy。
  • Health Checks。
  • Logging。
  • Request Timeout。
  • Graceful Shutdown。
  • CI/CD。

15. FastAPI and Django / DRF

ContrastFastAPIDjango + DRF
PositioningLightweight, API priorityComplete Web frame + API
Data validationPydanticDRF Serializer
ORMMake your own choiceDjango ORM
MigrationUsually AlembicBuilt-in Migration
AdminNot built-inBuilt-in Django Admin
Dependency InjectionBuilt-in DependsUsually self-organized
AsyncNative ASGI designSupport ASGI and some asynchronous capabilities
OpenAPIAutomatic integrationCommonly used drf-spectacular
Authentication and permissionsself-assembledDjango/DRF components are more mature
Applicable scenariosAPI, microservices, AI servicesComplex business system, CRUD, backend management

Advantages of FastAPI

  • Type declarations are closely integrated with parameter validation.
  • API development code is relatively concise.
  • Dependency Injection is easy to use.
  • Auto OpenAPI.
  • The asynchronous network I/O is supported naturally.
  • Suitable for combining HTTP Client, model services and database dependencies.

Advantages of Django / DRF

  • ORM, Migration, Authentication, Admin are maturely integrated.
  • Complex business systems have more capabilities out of the box.
  • CRUD, permissions and data model management have a complete ecosystem.
  • Large business systems can reduce the need for self-selection and integration of basic components.

Is FastAPI necessarily faster than Django?

uncertain.

FastAPI has better performance characteristics in lightweight API and asynchronous I/O scenarios.

But the performance of actual business services also depends on:

  • Database query.
  • Network I/O.
  • serialization.
  • cache.
  • Worker configuration.
  • CPU Computation intensive.

If a request spends most of its time on PostgreSQL queries or waiting on external services, simply changing the framework won't necessarily yield significant gains.


Summary

Knowledge pointsimportance
Routing / Path / Query Parameterscore
Pydantic BaseModel / Fieldcore
Request / Response Modelcore
Dependency Injection / Dependscore
APIRoutercore
Async / Await / ASGIcore
Database Session / SQLAlchemyimportant
HTTPException / Error Handlinghigh frequency
Middleware / CORS / Authenticationimportant
BackgroundTasks / Lifespanimportant
OpenAPI / Swaggercore
pytest / TestClientimportant
Uvicorn / Docker Deploymentimportant

FastAPI The four core concepts that need to be mastered most:

  1. Type Hints + Pydantic: Use the Python type declaration to complete data parsing, verification and serialization.
  2. Dependency Injection: Unified management of database, authentication, configuration and other reusable dependencies.
  3. ASGI / Async: Supports high-concurrency I/O scenarios, but needs to correctly handle synchronous blocking operations.
  4. OpenAPI: Automatically generate API Schema to facilitate document maintenance and TypeScript Client code generation.

Reference documentation

Back to top