Chuyển đến nội dung chính

Bài 1: Giới thiệu FastAPI - Framework Python hiện đại nhất

Tìm hiểu FastAPI là gì, so sánh với Django, Flask, Litestar. Kiến trúc ASGI, async-first, type hints, auto-documentation. Hệ sinh thái và use cases thực tế.

💻 Lập trình — Bài 1 Bài 1: Giới thiệu FastAPI - Framework Python hiện đại nhất

Python FastAPI: Từ Cơ bản đến Nâng cao

Phần 1: Nền tảng Python & FastAPI

xdev.asia

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íFastAPIDjangoFlaskLitestar
Type SystemNative (Pydantic)OptionalOptionalNative (attrs/msgspec)
PerformanceRất caoTrung bìnhTrung bìnhRất cao
Async SupportNativePartial (Django 5+)Flask 2+ (limited)Native
Auto DocsSwagger + ReDocDRF SpectacularFlask-RESTXSwagger + ReDoc
ORMSQLAlchemy/TortoiseDjango ORMSQLAlchemySQLAlchemy
Admin PanelSQLAdmin/FastAPI-AdminBuilt-inFlask-AdminCommunity
Learning CurveThấp-Trung bìnhTrung bình-CaoThấpTrung bình
CommunityRất lớn (70k+ ⭐)Rất lớnRất lớnĐang phát triển
Phù hợpAPIs, MicroservicesFull-stack, CMSMVP, Small APIsAPIs, 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ựcThư việnMô tả
ORMSQLAlchemy, Tortoise-ORM, SQLModelDatabase ORM cho Python
MigrationAlembicDatabase schema migration
Authpython-jose, Passlib, AuthlibJWT, OAuth2, Password hashing
Cachingfastapi-cache2, RedisResponse caching
Task QueueCelery, ARQ, SAQBackground task processing
Testingpytest, httpxTesting framework và async client
AdminSQLAdmin, FastAPI-AdminAdmin dashboard
Monitoringprometheus-fastapi-instrumentatorMetrics 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:

  1. Phần 1: Nền tảng - Python essentials, FastAPI basics, Request/Response
  2. Phần 2: Database - Pydantic, SQLAlchemy, Alembic, CRUD & Repository pattern
  3. Phần 3: Security - Authentication, Authorization, OAuth2, Security best practices
  4. Phần 4: Advanced - Middleware, WebSockets, Background Tasks, Caching, Async deep dive
  5. 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.