# FastAPI Tham Khảo Nhanh

*Path operation, validation, dependency, xác thực, testing*

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

## Thiết Lập

### Ứng Dụng Tối Giản

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

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

### Chạy Ứng Dụng

```
pip install "fastapi[standard]"
fastapi dev main.py    # dev với auto-reload
fastapi run main.py    # production
```

### Tính Năng Nổi Bật

| Command | Description |
|---------|-------------|
| `Async native` | async/await với ASGI (Uvicorn) |
| `Tài liệu tự động` | Swagger UI tại `/docs`, ReDoc tại `/redoc` |
| `Xác thực kiểu` | Pydantic model cho request/response |
| `OpenAPI` | Schema OpenAPI tự động tạo |
| `Dependency injection` | Hệ thống DI tích hợp sẵn |

## Path Operations

### HTTP Methods

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

### Tham Số Path

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

# Ràng buộc Enum
from enum import Enum
class Color(str, Enum):
    red = "red"
    blue = "blue"
```

### Status Code & Tags

```
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

### Pydantic Models

```
from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str
    price: float = Field(gt=0, description="Phải dương")
    tags: list[str] = []
```

### Model Lồng Nhau

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

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

### Dùng Trong Endpoint

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

### Tính Năng Validation

| Command | Description |
|---------|-------------|
| `Field(gt=0)` | Lớn hơn 0 |
| `Field(min_length=1)` | Độ dài chuỗi tối thiểu |
| `Field(max_length=100)` | Độ dài chuỗi tối đa |
| `Field(pattern='^[a-z]+$')` | Khớp pattern regex |
| `Field(default=None)` | Tùy chọn với mặc định |
| `EmailStr` | Xác thực email (pydantic[email]) |

## Query Parameters

### Query Param Cơ Bản

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

### Validation 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}
```

### Tùy Chọn & Bắt Buộc

```
async def read_items(
    q: str | None = None,   # tùy chọn
    name: str = ...,         # bắt buộc (Ellipsis)
    tags: list[str] = Query(default=[]),
):
    return {"q": q, "name": name}
```

### Headers & Cookies

```
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}
```

## Response Models

### 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]  # lọc bỏ trường thừa
```

### Nhiều Loại Response

```
from fastapi.responses import JSONResponse, HTMLResponse

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

### Tùy Chọn Response Model

| Command | Description |
|---------|-------------|
| `response_model` | Pydantic model để lọc đầu ra |
| `response_model_exclude_unset` | Bỏ qua trường không được đặt tường minh |
| `response_model_include` | Whitelist trường cụ thể |
| `response_model_exclude` | Blacklist trường cụ thể |

### Response Lỗi

```
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="Không tìm thấy")
    return items[id]
```

## Dependencies

### Function Dependency

```
from fastapi import Depends

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

### Dùng Trong Endpoint

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

### Class-Based Dependencies

```
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]
```

### Phạm Vi Dependency

| Command | Description |
|---------|-------------|
| `Depends(func)` | Dependency theo endpoint |
| `app = FastAPI(dependencies=[...])` | Dependency toàn cục cho mọi route |
| `APIRouter(dependencies=[...])` | Dependency cấp router |
| `yield` | Setup/teardown (DB session, lock) |

## Xác Thực

### 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
```

### Luồng JWT Token

```
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"])
```

### Token Endpoint

```
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})}
```

### Security Schemes

| Command | Description |
|---------|-------------|
| `OAuth2PasswordBearer` | Bearer token qua form login |
| `HTTPBasic` | Xác thực Basic username/password |
| `APIKeyHeader` | API key trong header |
| `APIKeyCookie` | API key trong cookie |

## Background Tasks

### Background Task Đơn Giản

```
from fastapi import BackgroundTasks

def send_email(to: str, body: str):
    # thao tác chậm chạy sau khi response
    email_client.send(to, body)

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

### Dependency với 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 Workers

| Command | Description |
|---------|-------------|
| `BackgroundTasks` | Tác vụ nhẹ sau response (email, log) |
| `Celery / ARQ` | Tác vụ nặng cần worker riêng |
| `asyncio.create_task` | Coroutine async fire-and-forget |

## Middleware

### Custom Middleware

```
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
```

### Thêm 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 Tích Hợp

| Command | Description |
|---------|-------------|
| `CORSMiddleware` | Cross-origin resource sharing |
| `TrustedHostMiddleware` | Giới hạn hostname được phép |
| `GZipMiddleware` | Nén response Gzip |
| `HTTPSRedirectMiddleware` | Redirect HTTP sang HTTPS |

## Testing

### Test Client

```
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"
```

### Ghi Đè Dependencies

```
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
```

### Async Testing

```
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
```
