I. Định nghĩa FastAPI và Uvicorn

FastAPI là một web framework hiện đại, mã nguồn mở dành cho Python, được thiết kế để xây dựng API với hiệu suất cao, dễ dàng và nhanh chóng. Nó được xây dựng dựa trên hai nền tảng chính: Starlette (phần web routing và middleware) và Pydantic (phần kiểm tra và xác thực dữ liệu). FastAPI hỗ trợ cả đồng bộ và bất đồng bộ (async/await) một cách tự nhiên.

Một số tính năng nổi bật:

  • Hiệu suất cực cao: nhờ vào Starlette và Pydantic, FastAPI có tốc độ ngang ngửa NodeJS và Go (theo các benchmark).
  • Tự động tạo tài liệu API: hỗ trợ Swagger UI (tại /docs) và ReDoc (tại /redoc) dựa trên OpenAPI.
  • Kiểm tra dữ liệu tự động: sử dụng Python type hints để validate request/response.
  • Hỗ trợ WebSocket, GraphQL, OAuth2, CORS, v.v.

Uvicorn là một ASGI server tốc độ cao được dùng để chạy ứng dụng FastAPI. Nó dựa trên uvloop và httptools, cho phép xử lý hàng nghìn request mỗi giây một cách hiệu quả.

# Cài đặt FastAPI và Uvicorn
pip install fastapi uvicorn

# Tạo file main.py với nội dung đơn giản
# Sau đó chạy lệnh:
uvicorn main:app --reload

🚀 So sánh FastAPI với Flask

  • Tốc độ: FastAPI nhanh hơn đáng kể nhờ async và ASGI.
  • Validation: Flask cần thư viện ngoài (như Marshmallow); FastAPI có sẵn Pydantic.
  • Tài liệu: FastAPI tự động sinh OpenAPI; Flask không có sẵn.
  • Async: Flask hỗ trợ async nhưng còn hạn chế; FastAPI hỗ trợ đầy đủ.

II. REST Architecture

REST (Representational State Transfer) là một kiến trúc thiết kế API dựa trên các nguyên tắc chính:

  • Client–Server: phân tách giao diện người dùng và máy chủ.
  • Stateless: mỗi yêu cầu từ client chứa đầy đủ thông tin, server không lưu trạng thái giữa các yêu cầu.
  • Cacheable: phản hồi có thể được lưu cache để cải thiện hiệu suất.
  • Uniform Interface: sử dụng các phương thức HTTP chuẩn (GET, POST, PUT, DELETE, PATCH) và mã trạng thái (200, 201, 400, 404, 500...).
  • Layered System: cho phép tồn tại các tầng trung gian (proxy, gateway).
  • Code on Demand (không bắt buộc): server có thể gửi mã thực thi cho client.

FastAPI hỗ trợ REST một cách tự nhiên. Bạn chỉ cần dùng các decorator như @app.get(), @app.post(), @app.put(), @app.delete() để ánh xạ URL đến các hàm xử lý.

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    return {"item_id": item_id, "name": "Sample"}

III. FastAPI – Pydantic (Data Validation)

Pydantic là thư viện xác thực và phân tích cú pháp dữ liệu dựa trên type hints của Python. Trong FastAPI, bạn định nghĩa các model kế thừa từ BaseModel để mô tả cấu trúc của request body, query parameters, hay response.

Pydantic tự động:

  • Chuyển đổi kiểu dữ liệu (ví dụ: string "123" thành int 123).
  • Kiểm tra tính hợp lệ (ví dụ: email phải đúng định dạng).
  • Trả về lỗi 422 với thông báo chi tiết khi dữ liệu không hợp lệ.
from fastapi import FastAPI
from pydantic import BaseModel, Field
from typing import Optional

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float = Field(gt=0, description="Giá phải lớn hơn 0")
    is_offer: Optional[bool] = None
    tax: float = Field(default=0.0, ge=0)

@app.post("/items/")
async def create_item(item: Item):
    # item đã được validate, có thể dùng trực tiếp
    total = item.price + item.tax
    return {"item_name": item.name, "total": total}

📦 Nested model và validators

from pydantic import BaseModel, validator

class User(BaseModel):
    username: str
    password: str

    @validator('password')
    def password_length(cls, v):
        if len(v) < 6:
            raise ValueError('password too short')
        return v

class Order(BaseModel):
    user: User
    items: list[Item]

IV. FastAPI – Request Body

Request body thường được dùng trong các phương thức POST, PUT, PATCH. FastAPI hỗ trợ khai báo body thông qua Pydantic model hoặc dùng trực tiếp các kiểu đơn giản với Body().

from fastapi import FastAPI, Body

app = FastAPI()

# Dùng Pydantic model
@app.post("/items/")
async def create_item(item: Item):
    return item

# Dùng Body để nhận một giá trị đơn lẻ
@app.post("/hello/")
async def hello(name: str = Body(..., embed=True)):
    return {"message": f"Hello {name}"}

# Kết hợp path params, query params, và body
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, q: str = None):
    return {"item_id": item_id, "item": item.dict(), "query": q}

Bạn cũng có thể dùng Body(..., embed=True) để yêu cầu client gửi JSON có cấu trúc {"name": "value"} thay vì gửi trực tiếp "value".

V. Uploading Files

FastAPI hỗ trợ upload file qua kiểu UploadFile. Nó sử dụng cơ chế streaming nên có thể xử lý file lớn mà không chiếm nhiều bộ nhớ. Bạn có thể upload một hoặc nhiều file, kèm theo các trường form khác.

from fastapi import FastAPI, File, UploadFile, Form
from typing import List

app = FastAPI()

# Upload một file
@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    # Đọc nội dung file (dạng bytes)
    contents = await file.read()
    # Xử lý nội dung...
    return {"filename": file.filename, "size": len(contents)}

# Upload nhiều file
@app.post("/upload-multiple/")
async def upload_multiple(files: List[UploadFile] = File(...)):
    result = []
    for f in files:
        content = await f.read()
        result.append({"filename": f.filename, "size": len(content)})
    return result

# Kết hợp file và form fields
@app.post("/upload-with-metadata/")
async def upload_with_metadata(
    file: UploadFile = File(...),
    description: str = Form(...),
    tags: str = Form(...)
):
    return {
        "filename": file.filename,
        "description": description,
        "tags": tags.split(",")
    }

VI. FastAPI – WebSockets

FastAPI hỗ trợ WebSocket qua Starlette, cho phép xây dựng các ứng dụng real-time như chat, thông báo, streaming. Bạn có thể định nghĩa endpoint WebSocket với @app.websocket("/path").

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from typing import List

app = FastAPI()

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)

manager = ConnectionManager()

@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.send_personal_message(f"You wrote: {data}", websocket)
            await manager.broadcast(f"Client {client_id} said: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f"Client {client_id} left the chat")

WebSocket endpoint có thể dùng cả path parameters, query parameters, và có thể quản lý nhiều kết nối đồng thời.

VII. CRUD Operations (Create, Read, Update, Delete)

CRUD là bốn thao tác cơ bản với dữ liệu. Trong FastAPI, bạn sẽ tạo các endpoint tương ứng với từng thao tác, thường kết hợp với Pydantic model và lưu trữ tạm (ví dụ: dictionary hoặc database).

from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel
from typing import List, Dict

app = FastAPI()

# Dữ liệu giả lập trong bộ nhớ
fake_db: Dict[int, dict] = {}
counter = 1

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

class ItemResponse(BaseModel):
    id: int
    name: str
    price: float

# CREATE (POST)
@app.post("/items/", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
def create_item(item: ItemCreate):
    global counter
    new_item = {"id": counter, "name": item.name, "price": item.price}
    fake_db[counter] = new_item
    counter += 1
    return new_item

# READ all (GET)
@app.get("/items/", response_model=List[ItemResponse])
def read_items():
    return list(fake_db.values())

# READ one (GET)
@app.get("/items/{item_id}", response_model=ItemResponse)
def read_item(item_id: int):
    if item_id not in fake_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return fake_db[item_id]

# UPDATE (PUT)
@app.put("/items/{item_id}", response_model=ItemResponse)
def update_item(item_id: int, item: ItemCreate):
    if item_id not in fake_db:
        raise HTTPException(status_code=404, detail="Item not found")
    updated = {"id": item_id, "name": item.name, "price": item.price}
    fake_db[item_id] = updated
    return updated

# DELETE (DELETE)
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int):
    if item_id not in fake_db:
        raise HTTPException(status_code=404, detail="Item not found")
    del fake_db[item_id]
    return  # 204 No Content

Lưu ý sử dụng HTTPException để trả về lỗi với mã trạng thái phù hợp. Bạn cũng có thể dùng status module cho các mã phổ biến.

VIII. Response Model

response_model trong decorator của FastAPI giúp bạn kiểm soát dữ liệu trả về: lọc các trường, đảm bảo kiểu, và sinh tài liệu OpenAPI chính xác. Nó hoạt động dựa trên Pydantic model.

from pydantic import BaseModel, EmailStr

class UserIn(BaseModel):
    username: str
    password: str
    email: EmailStr

class UserOut(BaseModel):
    username: str
    email: EmailStr
    # không có password

@app.post("/users/", response_model=UserOut)
async def create_user(user: UserIn):
    # Lưu user vào database (giả lập)
    # Không trả về password dù user object có chứa password
    return user  # FastAPI tự động loại bỏ trường password

# Sử dụng response_model với các option
@app.get("/users/{user_id}", response_model=UserOut, response_model_exclude_unset=True)
def get_user(user_id: int):
    # Nếu trường nào không được set (None) sẽ không xuất hiện trong response
    return {"username": "john", "email": "john@example.com", "password": "secret"}

# response_model_include và response_model_exclude
@app.get("/users/me", response_model=UserOut, response_model_include={"username"})
def get_current_user():
    # Chỉ trả về username, các trường khác bị lược bỏ
    return {"username": "admin", "email": "admin@example.com", "password": "pass"}

Các option hữu ích:

  • response_model_exclude_unset=True: bỏ qua các trường có giá trị mặc định hoặc None.
  • response_model_include: tập hợp các trường muốn giữ lại.
  • response_model_exclude: tập hợp các trường muốn loại bỏ.
  • response_model_by_alias: sử dụng tên alias thay vì tên trường.

IX. Kết luận

FastAPI là một framework mạnh mẽ, hiện đại, và đang ngày càng phổ biến trong cộng đồng Python. Với khả năng tự động validate dữ liệu qua Pydantic, hỗ trợ WebSocket, upload file, response model linh hoạt, cùng hiệu suất vượt trội, FastAPI là lựa chọn hàng đầu cho các dự án API, microservices, và hệ thống real-time. Phần tiếp theo sẽ giới thiệu cách tích hợp FastAPI với SQLAlchemy và PostgreSQL.