Yếu Tố | Express.js | FastAPI |
---|---|---|
Thiết lập | Cần tạo app, cài thêm middleware, thủ công | Chỉ cần vài dòng, tích hợp sẵn mọi thứ |
Định nghĩa route | app.get('/', (req, res) => {...}) | app.get("/") def read_root(): {...} |
JSON response | res.json({ message: "Hello" }) | return {"message": "Hello"} |
Chạy server | app.listen(port) | uvicorn.run(app) |
Tài liệu API | Thường phải cài thêm swagger-ui-express | Tự động sinh docs tại /docs |
app.post('/products', (req, res) => { const { name, price } = req.body; if (!name || typeof name !== 'string') { return res.status(400).json({ error: "Name is required and must be text" }); } if (!price || typeof price !== 'number') { return res.status(400).json({ error: "Price is required and must be a number" }); } res.json({ message: "Product created!", product: { name, price } });});
from fastapi import FastAPIfrom pydantic import BaseModel
app = FastAPI()
class Product(BaseModel): name: str price: float
@app.post("/products")def create_product(product: Product): return {"message": "Product created!", "product": product}
@app.get("/products/{product_id}")def get_product(product_id: int): return {"product_id": product_id, "name": "Sample Product", "price": 29.99}
import asyncio
async def get_orders_from_db(user_id: int): await asyncio.sleep(0.1) return [{"id": 1, "item": "Laptop"}, {"id": 2, "item": "Mouse"}]
@app.get("/users/{user_id}/orders")async def get_user_orders(user_id: int): orders = await get_orders_from_db(user_id) return {"user_id": user_id, "orders": orders}
app.get('/users/:userId/orders', async (req, res) => { const orders = await getOrdersFromDB(req.params.userId); res.json({ userId: req.params.userId, orders });});
Tiêu chí | FastAPI | Express.js |
---|---|---|
Hệ thống kiểu dữ liệu | Tích hợp sẵn với Pydantic | Thường dùng TypeScript (tùy chọn) |
Tài liệu API | Tự động, interactive | Thủ công hoặc dùng plugin bổ sung |
Hiệu năng | Rất nhanh, cạnh tranh Node.js | Nhanh, nhẹ |
Middleware | Dùng dependencies và middleware | Dùng .use() cho middleware |
Độ phức tạp học | Hơi cao do kiểu cố định và async | Dễ học, linh hoạt từng phần |