Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

FastAPI Web Application

FastAPI Web Application

This chapter takes you from zero to creating your first web app with FastAPI and experiencing the auto-generated API docs.


How FastAPI differs in positioning from Django/Flask

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

Feature Django Flask FastAPI
Design philosophy Batteries included Micro-framework, extend as needed High performance, type-driven
Async support Supported from 3.1+ No native support Native async/await
API Documentation requires drf-spectacular requires Flasgger Auto-generated Swagger UI
Data validation Django Forms / DRF Serializer Flask-WTF / manual Pydantic (built-in)
Server WSGI(Gunicorn) WSGI(Gunicorn) ASGI(Uvicorn)
Type Safety Optional Optional Enforces Python type hints

FastAPI's biggest difference: Python type hints drive everything—automatic validation of route parameters, automatic serialization of requests/responses, and automatic generation of interactive docs.


Environment Preparation



$ python3 -m venv venv

$ source venv/bin/activate

(venv) $ pip install fastapi uvicorn jinja2 python-multipart

The three core dependencies:


Minimal FastAPI app

Example

File path: main.py

from

fastapi

import

FastAPI

Create a FastAPI instance

app

=

FastAPI

(

    title

=

"RUNOOB Blog"

,

    description

=

"A personal blog showcase built with FastAPI"

,

    version

=

"1.0.0"

)

@

app.

get

(

"/"

)

         

Route decorator for GET requests

def

index

(

)

:

   

"""Homepage"""

   

return

{

"message"

:

"Welcome to the RUNOOB 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 the server



(venv) $ uvicorn main:app --reload

INFO:     Uvicorn running on http://127.0.0.1:8000

Note that the startup method differs from Flask:


Auto-generated API documentation

This is FastAPI's most impressive feature—without writing any extra code, interactive docs are generated automatically.

Access the /docs Once you see Swagger UI, 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: click GET /hello/{name} → Try it out → enter name → Execute, and you'll see the real response.


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 organizes routes with Blueprint; FastAPI uses APIRouter. The concept is similar but the syntax differs, and APIRouter naturally carries type constraints.


Chapter Summary

In this chapter you did 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 doc generation—the most essential feature that sets it apart from Django/Flask.