Xây dựng Production API với FastAPI
FastAPI là framework Python hiện đại nhất để xây dựng API. Nó kết hợp tốc độ cao, type safety, và automatic documentation.
Thiết kế API
Bước đầu tiên là thiết kế schema của API. Dùng Pydantic models để validate dữ liệu:
from pydantic import BaseModel
from typing import Optional
class User(BaseModel):
id: int
name: str
email: str
is_active: Optional[bool] = TrueError Handling
Xử lý lỗi một cách clean và consistent:
from fastapi import HTTPException, status
@app.get("/users/{user_id}")
async def get_user(user_id: int):
if user_id < 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="User ID must be positive"
)
return {"id": user_id}Testing
Viết test trước (TDD), sau đó implement:
from fastapi.testclient import TestClient
def test_get_user():
response = client.get("/users/1")
assert response.status_code == 200
assert response.json()["id"] == 1Đây là nền tảng để xây dựng API production-ready!