AI Skill Library

FastAPI Essentials

Build typed async REST APIs with FastAPI + Pydantic v2.

pythonbackendapi
# FastAPI Essentials

## Minimal app
```py
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post('/items')
async def create(item: Item) -> Item:
    return item
```
Run: `uvicorn main:app --reload`

## Path / query / body
```py
@app.get('/items/{item_id}')
async def get_item(item_id: int, q: str | None = None): ...
```

## Dependencies
```py
from fastapi import Depends

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

@app.get('/users')
async def list_users(db = Depends(get_db)): ...
```

## Auth via dependency
```py
from fastapi import Header, HTTPException
def auth(x_token: str = Header()):
    if x_token != 'secret':
        raise HTTPException(401)
```

## Response models
`response_model=ItemOut` strips fields not in schema. Useful for hiding password hashes.

## Background tasks
```py
from fastapi import BackgroundTasks
@app.post('/send')
async def send(bg: BackgroundTasks):
    bg.add_task(send_email, 'a@b.c')
```

## OpenAPI: auto at `/docs` and `/redoc`.

API: /api/skills/fastapi-essentials