Xây dựng REST API với FastAPI: Nhanh, hiện đại và hiệu năng cao

FastAPI là gì?

FastAPI là framework Python hiện đại với hiệu năng ngang Node.js và Go. Tự động sinh API documentation (Swagger UI) và hỗ trợ type hints.

Cài đặt và Hello World

pip install fastapi uvicorn

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="Python Vietnam API")

class SanPham(BaseModel):
    ten: str
    gia: float
    mo_ta: str | None = None
    con_hang: bool = True

san_pham_db = []

@app.get("/")
async def root():
    return {"message": "Chào mừng đến với Python Vietnam API!"}

@app.post("/san-pham")
async def tao_san_pham(sp: SanPham):
    san_pham_db.append(sp.model_dump())
    return {"message": "Tạo thành công!", "data": sp}

@app.get("/san-pham/{sp_id}")
async def chi_tiet(sp_id: int):
    if sp_id >= len(san_pham_db):
        return {"error": "Không tìm thấy"}
    return {"data": san_pham_db[sp_id]}
# Chạy server
uvicorn main:app --reload
# Swagger UI: http://localhost:8000/docs

FastAPI là lựa chọn số 1 cho backend Python hiện đại.

Chia sẻ bài viết: