FastAPI

FastAPI is a modern Python web framework for building APIs. It’s fast (async support), uses type hints and Pydantic for validation and docs, and gives you automatic OpenAPI (Swagger) and ReDoc documentation. Below are the main usable and important things to know.

Install and run

Install with pip install fastapi uvicorn. You define an app, add routes, and run with uvicorn main:app --reload. The app instance is the center of your API.

Routes and HTTP methods

Use decorators to define endpoints: @app.get("/items"), @app.post("/items"), @app.put("/items/{item_id}"), @app.delete("/items/{item_id}"). Path parameters go in curly braces: /items/{item_id}. FastAPI passes them as function arguments with the same name.

Path and query parameters

Path parameters are part of the URL; query parameters come after ?. Declare both as function arguments. Use type hints so FastAPI validates and documents them.

@app.get("/items/{item_id}")
def read_item(item_id: int, skip: int = 0, limit: int = 10):
    return {"item_id": item_id, "skip": skip, "limit": limit}
# GET /items/42?skip=0&limit=5

Request body with Pydantic

For POST/PUT/PATCH, use a Pydantic model as the body. FastAPI validates the JSON, converts types, and documents the schema. Invalid data returns 422 with error details.

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool | None = None

@app.post("/items")
def create_item(item: Item):
    return {"name": item.name, "price": item.price}

Response model

Use response_model=SomeModel on the route to declare the response shape. FastAPI serializes the return value and documents it. Use response_model_exclude_unset=True to omit fields that weren’t set.

Dependency injection

Use Depends() to inject shared logic (auth, DB session, common params). Dependencies can depend on other dependencies. Same dependency instance is reused in one request.

def get_current_user(token: str = Header(...)):
    # validate token, return user
    return user

@app.get("/me")
def get_me(user = Depends(get_current_user)):
    return user

Validation and error responses

Pydantic and type hints give automatic validation. Wrong types or constraint violations produce 422 responses with a list of errors. You can raise HTTPException(status_code=404, detail="Not found") for custom errors.

Async support

Define route handlers as async def when you do I/O (DB, HTTP calls). FastAPI runs them in the event loop so they don’t block. Use normal def for CPU-only or sync code; FastAPI runs it in a thread pool.

Automatic docs

With the app running, open /docs for Swagger UI and /redoc for ReDoc. Both are generated from your routes, types, and Pydantic models. No extra config needed.

Summary

FastAPI gives you: typed routes with path/query/body params, Pydantic models for validation and docs, dependency injection, async by default, and built-in OpenAPI docs. Use type hints and Pydantic everywhere to get the most out of it.

← Back to concepts