FastAPI is the fastest Python web framework. Automatic validation, OpenAPI docs, async support, type-safe.
Basic API¶
from fastapi import FastAPI, HTTPException from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float in_stock: bool = True items: dict[int, Item] = {} @app.post(“/items/”, status_code=201) async def create_item(item: Item) -> Item: item_id = len(items) + 1 items[item_id] = item return item @app.get(“/items/{item_id}”) async def get_item(item_id: int) -> Item: if item_id not in items: raise HTTPException(404, “Item not found”) return items[item_id]
Dependency Injection¶
from fastapi import Depends async def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get(“/users/{user_id}”) async def get_user(user_id: int, db: Session = Depends(get_db)): return db.query(User).filter(User.id == user_id).first()
Automatic Documentation¶
FastAPI automatically generates OpenAPI (Swagger) at /docs and ReDoc at /redoc. Just start the server and open it in your browser.
Key Takeaway¶
FastAPI = Pydantic validation + async + automatic docs. For new Python API projects, the clear choice.