1. What is FastAPI?
FastAPI is a modern, high-performance web framework for Python, designed to make building APIs quick and easy. Created by Sebastián Ramírez In 2018, FastAPI quickly became the most popular Python framework for Backend APIs thanks to its outstanding performance, great developer experience, and powerful type hints system.
FastAPI runs in the background Starlette (ASGI framework) and use Pydantic for data validation, delivering speeds comparable to Node.js and Go in many benchmarks.
Why choose FastAPI?
High performance: One of the fastest Python frameworks, thanks to Starlette and async/await
Type hints native: Use Python type hints for automated validation, serialization, and documentation
Auto-documentation: Automatically create Swagger UI and ReDoc from code, no need to write separate docs
Developer experience: Great editor support, autocompletion, type checking helps reduce bugs
Async-first: Supports native async/await, suitable for I/O-bound applications
Standards-based: Based on OpenAPI (Swagger), JSON Schema, OAuth2 standards
2. Compare FastAPI with other Frameworks
| Criteria | FastAPI | Django | Flask | Litestar |
|---|---|---|---|---|
| Type System | Native (Pydantic) | Optional | Optional | Native (attrs/msgspec) |
| Performance | Very high | Average | Average | Very high |
| 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 | Low-Medium | Medium-High | Low | Average |
| Community | Very large (70k+ ⭐) | Very big | Very big | Developing |
| Suitable | APIs, Microservices | Full-stack, CMS | MVP, Small APIs | APIs, Enterprise |
3. FastAPI Architecture
FastAPI is built on three solid foundations:
┌──────────────────────────────────────────────┐
│ FastAPI Application │
├──────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌──────────┐ ┌───────────┐ │
│ │ Routes │ │ Deps │ │ Models │ │
│ │ (Path │ │ (DI │ │ (Pydantic│ │
│ │ Ops) │ │ System)│ │ V2) │ │
│ └──────────┘ └──────────┘ └───────────┘ │
│ │
├──────────────────────────────────────────────┤
│ Starlette (ASGI) │
│ ┌──────────┐ ┌──────────┐ ┌───────────┐ │
│ │Middleware │ │ Routing │ │ WebSocket │ │
│ └──────────┘ └──────────┘ └───────────┘ │
├──────────────────────────────────────────────┤
│ Uvicorn / Hypercorn (Server) │
└──────────────────────────────────────────────┘
Main ingredients:
Uvicorn: ASGI server, runs FastAPI application, supports HTTP/1.1 and WebSocket
Starlette: Lightweight ASGI framework, providing routing, middleware, WebSocket, background tasks
Pydantic: Data validation and serialization based on type hints
OpenAPI: Automatically generate API documentation according to OpenAPI 3.1 standards
4. FastAPI ecosystem
FastAPI has a rich ecosystem with many supporting libraries:
| Field | Library | Description |
|---|---|---|
| ORM | SQLAlchemy, Tortoise-ORM, SQLModel | Database ORM for 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 and async client |
| Admin | SQLAdmin, FastAPI-Admin | Admin dashboard |
| Monitoring | prometheus-fastapi-instrumentator | Metrics and monitoring |
5. Hello World with FastAPI
Let's look at the simplest FastAPI application:
# 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}
Run the application:
# 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
With just a few lines of code, you have:
- REST API endpoint with path parameter (
item_id) is automatically validated asint - Query parameters optional (
q) with type hint - Interactive API documentation (Swagger UI)
- Alternative documentation (ReDoc)
- JSON Schema for request/response
6. WSGI vs ASGI - Why is ASGI important?
Understanding the difference between WSGI and ASGI is key to understanding why FastAPI is fast:
WSGI (Web Server Gateway Interface) - Traditional
# 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) - Modern
# 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))
With ASGI, FastAPI can handle thousands of concurrent requests without needing many threads or processes.
7. When should you use FastAPI?
FastAPI should be used when:
- Build REST APIs or GraphQL APIs
- Microservices architecture
- Real-time applications (WebSocket, SSE)
- Machine Learning model serving
- IoT backend services
- High-concurrency I/O-bound applications
Consider another framework when:
- Full-stack web app with server-rendered HTML → Django
- CMS, Admin-heavy applications → Django
- Quick prototype, simple API → Flask
- Need maximum speed with msgspec → Litestar
8. Course roadmap
In this series, we will go through 20 lessons divided into 5 parts:
- Part 1: Foundation - Python essentials, FastAPI basics, Request/Response
- Part 2: Databases - Pydantic, SQLAlchemy, Alembic, CRUD & Repository pattern
- Part 3: Security - Authentication, Authorization, OAuth2, Security best practices
- Part 4: Advanced - Middleware, WebSockets, Background Tasks, Caching, Async deep diving
- Part 5: Production - Clean Architecture, Testing, Docker, CI/CD, Deployment & Monitoring
Each lesson has practical code examples, and by the end of the series you will have enough knowledge to build a production-ready FastAPI application.
Summary
FastAPI is the most modern Python framework for building APIs, combining high performance with a great developer experience. In the next article, we will review the necessary Python knowledge before diving into FastAPI.