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

Lesson 1: Introducing FastAPI - The most modern Python framework

Find out what FastAPI is, compare with Django, Flask, Litestar. ASGI architecture, async-first, type hints, auto-documentation. Ecosystem and practical use cases.

💻 Programming — Lesson 1 Lesson 1: Introducing FastAPI - Framework State of the art Python

Python FastAPI: From Basics to Advanced

Part 1: Python Foundation & FastAPI

xdev.asia

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

CriteriaFastAPIDjangoFlaskLitestar
Type SystemNative (Pydantic)OptionalOptionalNative (attrs/msgspec)
PerformanceVery highAverageAverageVery high
Async SupportNativePartial (Django 5+)Flask 2+ (limited)Native
Auto DocsSwagger + ReDocDRF SpectacularFlask-RESTXSwagger + ReDoc
ORMSQLAlchemy/TortoiseDjango ORMSQLAlchemySQLAlchemy
Admin PanelSQLAdmin/FastAPI-AdminBuilt-inFlask-AdminCommunity
Learning CurveLow-MediumMedium-HighLowAverage
CommunityVery large (70k+ ⭐)Very bigVery bigDeveloping
SuitableAPIs, MicroservicesFull-stack, CMSMVP, Small APIsAPIs, 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:

FieldLibraryDescription
ORMSQLAlchemy, Tortoise-ORM, SQLModelDatabase ORM for Python
MigrationAlembicDatabase schema migration
Authpython-jose, Passlib, AuthlibJWT, OAuth2, Password hashing
Cachingfastapi-cache2, RedisResponse caching
Task QueueCelery, ARQ, SAQBackground task processing
Testingpytest, httpxTesting framework and async client
AdminSQLAdmin, FastAPI-AdminAdmin dashboard
Monitoringprometheus-fastapi-instrumentatorMetrics 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 as int
  • 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:

  1. Part 1: Foundation - Python essentials, FastAPI basics, Request/Response
  2. Part 2: Databases - Pydantic, SQLAlchemy, Alembic, CRUD & Repository pattern
  3. Part 3: Security - Authentication, Authorization, OAuth2, Security best practices
  4. Part 4: Advanced - Middleware, WebSockets, Background Tasks, Caching, Async deep diving
  5. 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.