1. FastAPI là gì?
FastAPI là một web framework hiện đại, hiệu năng cao cho Python, được thiết kế để xây dựng APIs nhanh chóng và dễ dàng. Được tạo bởi Sebastián Ramírez vào năm 2018, FastAPI nhanh chóng trở thành framework Python phổ biến nhất cho Backend API nhờ vào hiệu năng vượt trội, developer experience tuyệt vời và hệ thống type hints mạnh mẽ.
FastAPI chạy trên nền Starlette (ASGI framework) và sử dụng Pydantic cho data validation, mang lại tốc độ ngang ngửa Node.js và Go trong nhiều benchmark.
Tại sao chọn FastAPI?
Hiệu năng cao: Một trong những Python framework nhanh nhất, nhờ Starlette và async/await
Type hints native: Sử dụng Python type hints cho validation, serialization và documentation tự động
Auto-documentation: Tự động tạo Swagger UI và ReDoc từ code, không cần viết docs riêng
Developer experience: Editor support tuyệt vời, autocompletion, type checking giúp giảm bugs
Async-first: Hỗ trợ native async/await, phù hợp cho I/O-bound applications
Standards-based: Dựa trên OpenAPI (Swagger), JSON Schema, OAuth2 standards
2. So sánh FastAPI với các Framework khác
| Tiêu chí | FastAPI | Django | Flask | Litestar |
|---|---|---|---|---|
| Type System | Native (Pydantic) | Optional | Optional | Native (attrs/msgspec) |
| Performance | Rất cao | Trung bình | Trung bình | Rất cao |
| Async Support | Native | Partial (Django 5+) | Flask 2+ (limited) | Native |
| Auto Docs | Swagger + ReDoc | DRF Spectacular | Flask-RESTX | Swagger + ReDoc |
| ORM | SQLAlchemy/Tortoise | Django ORM | SQLAlchemy | SQLAlchemy |
| Admin Panel | SQLAdmin/FastAPI-Admin | Built-in | Flask-Admin | Community |
| Learning Curve | Thấp-Trung bình | Trung bình-Cao | Thấp | Trung bình |
| Community | Rất lớn (70k+ ⭐) | Rất lớn | Rất lớn | Đang phát triển |
| Phù hợp | APIs, Microservices | Full-stack, CMS | MVP, Small APIs | APIs, Enterprise |
3. Kiến trúc FastAPI
FastAPI được xây dựng dựa trên bộ ba foundation vững chắc:
┌──────────────────────────────────────────────┐
│ FastAPI Application │
├──────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌──────────┐ ┌───────────┐ │
│ │ Routes │ │ Deps │ │ Models │ │
│ │ (Path │ │ (DI │ │ (Pydantic│ │
│ │ Ops) │ │ System)│ │ V2) │ │
│ └──────────┘ └──────────┘ └───────────┘ │
│ │
├──────────────────────────────────────────────┤
│ Starlette (ASGI) │
│ ┌──────────┐ ┌──────────┐ ┌───────────┐ │
│ │Middleware │ │ Routing │ │ WebSocket │ │
│ └──────────┘ └──────────┘ └───────────┘ │
├──────────────────────────────────────────────┤
│ Uvicorn / Hypercorn (Server) │
└──────────────────────────────────────────────┘
Thành phần chính:
Uvicorn: ASGI server, chạy ứng dụng FastAPI, hỗ trợ HTTP/1.1 và WebSocket
Starlette: ASGI framework nhẹ, cung cấp routing, middleware, WebSocket, background tasks
Pydantic: Data validation và serialization dựa trên type hints
OpenAPI: Tự động generate API documentation theo chuẩn OpenAPI 3.1
4. Hệ sinh thái FastAPI
FastAPI có hệ sinh thái phong phú với nhiều thư viện hỗ trợ:
| Lĩnh vực | Thư viện | Mô tả |
|---|---|---|
| ORM | SQLAlchemy, Tortoise-ORM, SQLModel | Database ORM cho Python |
| Migration | Alembic | Database schema migration |
| Auth | python-jose, Passlib, Authlib | JWT, OAuth2, Password hashing |
| Caching | fastapi-cache2, Redis | Response caching |
| Task Queue | Celery, ARQ, SAQ | Background task processing |
| Testing | pytest, httpx | Testing framework và async client |
| Admin | SQLAdmin, FastAPI-Admin | Admin dashboard |
| Monitoring | prometheus-fastapi-instrumentator | Metrics và monitoring |
5. Hello World với FastAPI
Cùng xem một ứng dụng FastAPI đơn giản nhất:
# main.py
from fastapi import FastAPI
app = FastAPI(
title="My First API",
description="Learning FastAPI from scratch",
version="1.0.0"
)
@app.get("/")
async def root():
return {"message": "Hello, FastAPI!"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
Chạy ứng dụng:
# Cài đặt
pip install fastapi uvicorn
# Chạy development server
uvicorn main:app --reload
# Server sẽ chạy tại http://127.0.0.1:8000
# Swagger UI: http://127.0.0.1:8000/docs
# ReDoc: http://127.0.0.1:8000/redoc
Chỉ với vài dòng code, bạn đã có:
- REST API endpoint với path parameter (
item_id) được validate tự động làint - Query parameter optional (
q) với type hint - Interactive API documentation (Swagger UI)
- Alternative documentation (ReDoc)
- JSON Schema cho request/response
6. WSGI vs ASGI - Tại sao ASGI quan trọng?
Hiểu sự khác biệt giữa WSGI và ASGI là chìa khóa để hiểu tại sao FastAPI nhanh:
WSGI (Web Server Gateway Interface) - Truyền thống
# Flask (WSGI) - synchronous, blocking
@app.route("/data")
def get_data():
result1 = db.query("SELECT ...") # Block - đợi DB
result2 = requests.get("https://api.example.com") # Block - đợi HTTP
return jsonify(result1, result2)
# Tổng thời gian = time(query) + time(http_call)
ASGI (Asynchronous Server Gateway Interface) - Hiện đại
# FastAPI (ASGI) - asynchronous, non-blocking
@app.get("/data")
async def get_data():
result1, result2 = await asyncio.gather(
db.query("SELECT ..."), # Non-blocking
httpx.get("https://api.example.com") # Non-blocking
)
return {"db": result1, "api": result2}
# Tổng thời gian = max(time(query), time(http_call))
Với ASGI, FastAPI có thể xử lý hàng nghìn concurrent requests mà không cần nhiều threads hay processes.
7. Khi nào nên dùng FastAPI?
Nên dùng FastAPI khi:
- Xây dựng REST APIs hoặc GraphQL APIs
- Microservices architecture
- Real-time applications (WebSocket, SSE)
- Machine Learning model serving
- IoT backend services
- High-concurrency I/O-bound applications
Cân nhắc framework khác khi:
- Full-stack web app với server-rendered HTML → Django
- CMS, Admin-heavy applications → Django
- Quick prototype, simple API → Flask
- Cần tốc độ tối đa với msgspec → Litestar
8. Lộ trình khóa học
Trong series này, chúng ta sẽ đi qua 20 bài học chia thành 5 phần:
- Phần 1: Nền tảng - Python essentials, FastAPI basics, Request/Response
- Phần 2: Database - Pydantic, SQLAlchemy, Alembic, CRUD & Repository pattern
- Phần 3: Security - Authentication, Authorization, OAuth2, Security best practices
- Phần 4: Advanced - Middleware, WebSockets, Background Tasks, Caching, Async deep dive
- Phần 5: Production - Clean Architecture, Testing, Docker, CI/CD, Deployment & Monitoring
Mỗi bài học đều có code examples thực tế, và cuối series bạn sẽ có đủ kiến thức để xây dựng production-ready FastAPI application.
Tổng kết
FastAPI là framework Python hiện đại nhất cho việc xây dựng APIs, kết hợp hiệu năng cao với developer experience tuyệt vời. Trong bài tiếp theo, chúng ta sẽ ôn tập các kiến thức Python cần thiết trước khi đi sâu vào FastAPI.