FastAPI ist das schnellste Python-Web-Framework. Automatische Validierung, OpenAPI-Docs, Async-Support, typsicher.
Grundlegende 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()
Automatische Dokumentation¶
FastAPI generiert automatisch OpenAPI (Swagger) unter /docs und ReDoc unter /redoc. Einfach starten und im Browser öffnen.
Wichtigste Erkenntnis¶
FastAPI = Pydantic-Validierung + Async + automatische Docs. Für neue Python-API-Projekte die klare Wahl.