# Riferimento Rapido FastAPI

*Operazioni path, validazione, dipendenze, autenticazione, test*

> Source: FastAPI Documentation (fastapi.tiangolo.com) · MIT

## Configurazione

### App Minimale

```
from fastapi import FastAPI
app = FastAPI()

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

### Eseguire l'App

```
pip install "fastapi[standard]"
fastapi dev main.py    # sviluppo con auto-reload
fastapi run main.py    # produzione
```

### Funzionalità Principali

| Command | Description |
|---------|-------------|
| `Async nativo` | async/await con ASGI (Uvicorn) |
| `Docs automatica` | Swagger UI su `/docs`, ReDoc su `/redoc` |
| `Validazione tipi` | Modelli Pydantic per richiesta/risposta |
| `OpenAPI` | Schema OpenAPI generato automaticamente |
| `Dependency injection` | Sistema DI integrato |

## Operazioni Path

### Metodi HTTP

```
@app.get("/items")
@app.post("/items")
@app.put("/items/{item_id}")
@app.patch("/items/{item_id}")
@app.delete("/items/{item_id}")
```

### Parametri Path

```
@app.get("/users/{user_id}")
async def get_user(user_id: int):
    return {"user_id": user_id}

# Vincolo enum
from enum import Enum
class Color(str, Enum):
    red = "red"
    blue = "blue"
```

### Codici Stato e Tag

```
from fastapi import status

@app.post("/items", status_code=status.HTTP_201_CREATED,
          tags=["items"])
async def create_item(item: Item):
    return item
```

## Request Body

### Modelli Pydantic

```
from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str
    price: float = Field(gt=0, description="Must be positive")
    tags: list[str] = []
```

### Modelli Annidati

```
class Address(BaseModel):
    street: str
    city: str
    zip_code: str

class User(BaseModel):
    name: str
    address: Address
```

### Utilizzo nell'Endpoint

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

### Funzionalità di Validazione

| Command | Description |
|---------|-------------|
| `Field(gt=0)` | Maggiore di 0 |
| `Field(min_length=1)` | Lunghezza minima stringa |
| `Field(max_length=100)` | Lunghezza massima stringa |
| `Field(pattern='^[a-z]+$')` | Corrispondenza pattern regex |
| `Field(default=None)` | Opzionale con default |
| `EmailStr` | Validazione email (pydantic[email]) |

## Parametri Query

### Parametri Query Base

```
@app.get("/items")
async def list_items(skip: int = 0, limit: int = 10):
    return items[skip : skip + limit]
# GET /items?skip=0&limit=20
```

### Validazione Query

```
from fastapi import Query

@app.get("/search")
async def search(
    q: str = Query(min_length=3, max_length=50),
    page: int = Query(default=1, ge=1),
):
    return {"q": q, "page": page}
```

### Opzionale e Obbligatorio

```
async def read_items(
    q: str | None = None,   # opzionale
    name: str = ...,         # obbligatorio (Ellipsis)
    tags: list[str] = Query(default=[]),
):
    return {"q": q, "name": name}
```

### Header e Cookie

```
from fastapi import Header, Cookie

async def read(
    user_agent: str | None = Header(default=None),
    session_id: str | None = Cookie(default=None),
):
    return {"ua": user_agent}
```

## Modelli di Risposta

### Response Model

```
class ItemOut(BaseModel):
    name: str
    price: float

@app.get("/items/{id}", response_model=ItemOut)
async def get_item(id: int):
    return items[id]  # filtra i campi in eccesso
```

### Tipi di Risposta Multipli

```
from fastapi.responses import JSONResponse, HTMLResponse

@app.get("/html", response_class=HTMLResponse)
async def get_html():
    return "<h1>Hello</h1>"
```

### Opzioni Response Model

| Command | Description |
|---------|-------------|
| `response_model` | Modello Pydantic per filtro output |
| `response_model_exclude_unset` | Ometti campi non impostati esplicitamente |
| `response_model_include` | Whitelist di campi specifici |
| `response_model_exclude` | Blacklist di campi specifici |

### Risposte di Errore

```
from fastapi import HTTPException

@app.get("/items/{id}")
async def get_item(id: int):
    if id not in items:
        raise HTTPException(status_code=404, detail="Not found")
    return items[id]
```

## Dipendenze

### Dipendenza a Funzione

```
from fastapi import Depends

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

### Utilizzo nell'Endpoint

```
@app.get("/users")
async def list_users(db: Session = Depends(get_db)):
    return db.query(User).all()
```

### Dipendenze Basate su Classi

```
class Pagination:
    def __init__(self, skip: int = 0, limit: int = 10):
        self.skip = skip
        self.limit = limit

@app.get("/items")
async def list_items(pg: Pagination = Depends()):
    return items[pg.skip : pg.skip + pg.limit]
```

### Scope delle Dipendenze

| Command | Description |
|---------|-------------|
| `Depends(func)` | Dipendenza per endpoint |
| `app = FastAPI(dependencies=[...])` | Dipendenza globale per tutte le route |
| `APIRouter(dependencies=[...])` | Dipendenza a livello router |
| `yield` | Setup/teardown (sessioni DB, lock) |

## Autenticazione

### OAuth2 Password Bearer

```
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
async def read_me(token: str = Depends(oauth2_scheme)):
    user = decode_token(token)
    return user
```

### Flusso Token JWT

```
from jose import jwt
SECRET = "your-secret-key"

def create_token(data: dict):
    return jwt.encode(data, SECRET, algorithm="HS256")

def decode_token(token: str):
    return jwt.decode(token, SECRET, algorithms=["HS256"])
```

### Endpoint Token

```
from fastapi.security import OAuth2PasswordRequestForm

@app.post("/token")
async def login(form: OAuth2PasswordRequestForm = Depends()):
    user = authenticate(form.username, form.password)
    if not user:
        raise HTTPException(status_code=401)
    return {"access_token": create_token({"sub": user.id})}
```

### Schemi di Sicurezza

| Command | Description |
|---------|-------------|
| `OAuth2PasswordBearer` | Bearer token via login form |
| `HTTPBasic` | Auth Basic username/password |
| `APIKeyHeader` | API key nell'header |
| `APIKeyCookie` | API key nel cookie |

## Task in Background

### Task in Background Semplice

```
from fastapi import BackgroundTasks

def send_email(to: str, body: str):
    # operazione lenta eseguita dopo la risposta
    email_client.send(to, body)

@app.post("/notify")
async def notify(bg: BackgroundTasks):
    bg.add_task(send_email, "user@example.com", "Hello!")
    return {"status": "queued"}
```

### Dipendenza con Background

```
async def log_request(bg: BackgroundTasks):
    bg.add_task(write_log, "request received")

@app.get("/items", dependencies=[Depends(log_request)])
async def list_items():
    return items
```

### Background vs Worker

| Command | Description |
|---------|-------------|
| `BackgroundTasks` | Task leggeri dopo la risposta (email, log) |
| `Celery / ARQ` | Task pesanti che richiedono worker separati |
| `asyncio.create_task` | Coroutine async fire-and-forget |

## Middleware

### Middleware Personalizzato

```
import time
from starlette.middleware.base import BaseHTTPMiddleware

class TimingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        start = time.time()
        response = await call_next(request)
        duration = time.time() - start
        response.headers["X-Process-Time"] = str(duration)
        return response
```

### Aggiungere Middleware

```
app.add_middleware(TimingMiddleware)
```

### CORS

```
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://example.com"],
    allow_methods=["*"],
    allow_headers=["*"],
)
```

### Middleware Integrati

| Command | Description |
|---------|-------------|
| `CORSMiddleware` | Condivisione risorse cross-origin |
| `TrustedHostMiddleware` | Limita gli hostname consentiti |
| `GZipMiddleware` | Compressione risposta Gzip |
| `HTTPSRedirectMiddleware` | Reindirizza HTTP a HTTPS |

## Testing

### Client di Test

```
from fastapi.testclient import TestClient

client = TestClient(app)

def test_read_root():
    resp = client.get("/")
    assert resp.status_code == 200
    assert resp.json() == {"message": "Hello, World!"}
```

### Test POST

```
def test_create_item():
    resp = client.post("/items", json={
        "name": "Widget",
        "price": 9.99,
    })
    assert resp.status_code == 201
    assert resp.json()["name"] == "Widget"
```

### Override Dipendenze

```
async def mock_db():
    return FakeDB()

app.dependency_overrides[get_db] = mock_db

def test_with_mock_db():
    resp = client.get("/users")
    assert resp.status_code == 200
```

### Test Async

```
import pytest
from httpx import AsyncClient, ASGITransport

@pytest.mark.anyio
async def test_async():
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport) as ac:
        resp = await ac.get("/")
    assert resp.status_code == 200
```
