FastAPI: Building High-Performance REST APIs

Routing, path and query parameters, Pydantic validation, dependency injection, async databases, JWT authentication and Docker deployment — modern Python backend in one guide.

IntermediateUpdated 2026-10-3093K views

Getting Started

pip install fastapi "uvicorn[standard]"

# 热重载开发
uvicorn main:app --reload --port 8000
from fastapi import FastAPI

app = FastAPI(title="Demo API")

@app.get("/")
async def root():
     return {"message": "Hello, BackendWiki"}

Open http://localhost:8000/docs and you already have interactive Swagger UI — FastAPI generates it from your type annotations.

Path, Query and Body with Pydantic

from pydantic import BaseModel, Field, EmailStr
from typing import Optional

class UserCreate(BaseModel):
    name: str = Field(min_length=2, max_length=50)
    email: EmailStr
    age: Optional[int] = Field(default=None, ge=0, le=150)

@app.get("/users/{uid}")
async def get_user(uid: int):           # 路径参数自动解析+类型校验
    ...

@app.get("/users")
async def list_users(
    q: Optional[str] = None,           # 查询参数
    limit: int = 20, offset: int = 0,
):
    ...

@app.post("/users", status_code=201)
async def create_user(body: UserCreate):
    return body    # 响应也会序列化并校验

Validation failures return HTTP 422 with detailed field-level errors automatically — no manual if-checking needed.

Dependency Injection

from fastapi import Depends

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/orders")
async def list_orders(db = Depends(get_db),
                     user = Depends(get_current_user)):
    return db.query(Order).all()

Dependencies are cached per request, support nested injection, and make testing easy — override get_db with a test session in fixtures.

JWT Authentication

from datetime import datetime, timedelta
import jwt

SECRET = "change-me"

def create_token(uid: int) -> str:
    payload = {
        "sub": uid,
        "exp": datetime.utcnow() + timedelta(hours=2),
    }
    return jwt.encode(payload, SECRET, algorithm="HS256")

async def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, SECRET, algorithms=["HS256"])
        return payload["sub"]
    except jwt.PyJWTError:
        raise HTTPException(401, "Invalid token")

Packaging and Deployment

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"]

Behind nginx or a container platform, run uvicorn with --workers 4 (or use gunicorn -k uvicorn.workers.UvicornWorker) to use multiple CPU cores.

Friends & Partners