Django REST Framework tốt, nhưng nếu bạn cần tốc độ phát triển nhanh, auto-generated docs, và async out-of-the-box — FastAPI là câu trả lời. Được xây dựng trên Starlette và Pydantic, FastAPI là một trong những framework Python được star nhiều nhất trên GitHub.
Tại Sao FastAPI?
- Nhanh: Hiệu năng ngang Node.js và Go nhờ async
- Ít code hơn: Validation, serialization tự động qua type hints
- Docs miễn phí: Swagger UI và ReDoc tự sinh từ code
- Type safety: Editor autocomplete, bắt lỗi từ compile time
Cài Đặt Và Hello World
pip install fastapi uvicorn
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello, FastAPI!"}
# Chạy server
uvicorn main:app --reload
Mở http://localhost:8000/docs — Swagger UI đã sẵn sàng, không cần config thêm gì.
Pydantic Models — Validation Tự Động
from pydantic import BaseModel, EmailStr
from typing import Optional
class PostCreate(BaseModel):
title: str
content: str
excerpt: Optional[str] = None
published: bool = False
@app.post("/posts", status_code=201)
def create_post(post: PostCreate):
# FastAPI tự validate kiểu dữ liệu
# Nếu sai → trả 422 với chi tiết lỗi
return {"id": 1, **post.model_dump()}
Path Params Và Query Params
from fastapi import Query
@app.get("/posts/{post_id}")
def get_post(post_id: int): # tự convert string → int
return {"id": post_id}
@app.get("/posts")
def list_posts(
page: int = Query(default=1, ge=1),
size: int = Query(default=10, le=100),
status: str = "published"
):
return {"page": page, "size": size, "status": status}
Dependency Injection
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer
security = HTTPBearer()
def get_current_user(token = Depends(security)):
# Verify token
if not verify_token(token.credentials):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token không hợp lệ"
)
return decode_token(token.credentials)
@app.get("/me")
def get_me(user = Depends(get_current_user)):
return user
Async Endpoints
import httpx
@app.get("/github/{username}")
async def get_github_user(username: str):
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://api.github.com/users/{username}"
)
return response.json()
Kết Nối Database Với SQLAlchemy
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession)
async def get_db():
async with AsyncSessionLocal() as session:
yield session
@app.get("/posts")
async def list_posts(db: AsyncSession = Depends(get_db)):
result = await db.execute(select(Post))
return result.scalars().all()
FastAPI không phải là replacement cho Django — nó giải quyết bài toán khác: microservices, internal APIs, và những project cần type safety từ đầu. Chọn đúng công cụ cho đúng bài toán.
Kết Luận
FastAPI có learning curve thấp cho ai đã biết Python. Điểm mạnh nhất là auto-generated docs và type validation — hai thứ thường tốn nhiều thời gian nhất khi viết API. Bước tiếp theo: tìm hiểu Alembic cho database migrations và pytest-asyncio cho testing async code.
Chưa có bình luận. Hãy là người đầu tiên!