FastAPI Web application

This chapter takes you from scratch to create your first Web application with FastAPI and experience the auto-generated API documentation.


Positioning Differences Between FastAPI and Django/Flask

FastAPI is a rising star among Python web frameworks, positioned between Django and Flask.

FeaturesDjangoFlaskFastAPI
Design philosophyBatteries includedMicro-framework, extendable on demandHigh performance, type-driven
Async supportSupported from 3.1+No native supportNative async/await
API DocumentationRequires drf-spectacularRequires FlasggerAutomatically generate Swagger UI
Data validationDjango Forms / DRF SerializerFlask-WTF / manualPydantic (built-in)
ServerWSGI(Gunicorn)WSGI(Gunicorn)ASGI(Uvicorn)
Type SafetyOptionalOptionalEnforced Python type hints

The biggest difference of FastAPI:Drive everything with Python type hints— automatic validation of route parameters, automatic serialization of requests/responses, and automatic generation of interactive documentation.


Environment Preparation

$ python3 -m venv venv
$ source venv/bin/activate
(venv) $ pip install fastapi uvicorn jinja2 python-multipart

Explanation of the three core dependencies:

  • fastapi: The web framework itself
  • uvicorn: ASGI server (equivalent to Gunicorn for Flask)
  • jinja2: Template engine (optional, but required for SSR)

FastAPI minimal application

Example

# File path: main.py
from fastapi import FastAPI

# Create FastAPI instance
app = FastAPI(
    title="EXAMPLE blog",
    description="A personal blog showcase site built with FastAPI",
    version="1.0.0"
)

@app.get("/")           # Route decorator for GET request
def index():
    """Home Page"""
    return {"message": "Welcome to EXAMPLE blog"}

@app.get("/hello/{name}")   # Path parameter {name}
def hello(name: str):       # FastAPI automatically validates based on type hints
    return {"greeting": f"Hello, {name}!"}

Start server

(venv) $ uvicorn main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000

Note that the startup method is different from Flask:

  • Flask:flask run(based on Werkzeug)
  • FastAPI:uvicorn main:app(Based on ASGI, natively supports async)

Automatically generated API documentation

This is FastAPI's most amazing feature—Automatically generate interactive documentation without writing any extra code。

Visit/docsYou'll see Swagger UI, where you can test the API directly on the page:

http://127.0.0.1:8000/docs      # Swagger UI(交互式测试)
http://127.0.0.1:8000/redoc     # ReDoc(只读文档,更美观)

In Swagger UI Medium:Click GET /hello/{name} → Try it out → Input name → Execute,Justability看totruerealresponse。


Project Directory Structure Planning

blog_project/
├── main.py               # 应用入口
├── models.py             # SQLAlchemy ORM 模型
├── schemas.py            # Pydantic Schema(FastAPI 独有)
├── database.py           # 数据库连接与 Session
├── auth.py               # JWT 认证逻辑
├── routers/              # APIRouter 路由模块
│   ├── posts.py
│   ├── categories.py
│   ├── users.py
│   └── favorites.py
├── templates/            # Jinja2 模板
├── static/               # 静态文件
└── alembic/              # 数据库迁移

Flask uses Blueprint to organize routes, FastAPI usesAPIRouter. The concept is similar but the syntax differs, and APIRouter natively comes with type constraints.


Chapter summary

In this chapter, you accomplished three things: installed FastAPI + Uvicorn, wrote your first route with type hints, and visited the auto-generated /docs interactive API documentation.

Key takeaway: FastAPI uses Python type hints to drive parameter validation and documentation generation. This is its most fundamental feature distinguishing it from Django/Flask.

other extensions