前言
在 Python Web 开发领域,FastAPI 凭借高性能和类型安全成为新宠。相比 Django 的厚重和 Flask 的灵活,它提供了更现代化的开发体验,特别适合需要快速构建 API 的场景。
一、FastAPI 是什么
在 Python Web 生态中,主要有三个选择:
- Django:功能全面但较重,适合大型单体应用。
- Flask:轻量灵活,但插件繁多,需自行组装。
- FastAPI:新晋顶流,速度快、自动生成文档、利用类型提示减少 Bug。
为什么推荐新手使用?
- 无需手写文档:代码写完,Swagger UI 文档自动生成。
- 类型检查:参数传错直接报错,避免运行时崩溃。
- 简洁高效:Hello World 仅需几行代码。
二、环境搭建
1. 安装依赖
确保 Python 版本为 3.8 及以上。安装 FastAPI 核心库及 ASGI 服务器 Uvicorn:
pip install fastapi uvicorn
2. 运行与启动
新建 main.py 文件,写入以下基础代码:
from fastapi import FastAPI
import uvicorn
# 创建应用实例
app = FastAPI()
# 定义路由
@app.get("/")
def root():
return {"message": "Hello World"}
# 启动入口
if __name__ == "__main__":
uvicorn.run(app="main:app", host="127.0.0.1", port=8000)
这里的 main:app 表示运行 main.py 文件中的 app 对象。启动服务后访问 http://127.0.0.1:8000,即可看到返回的 JSON 数据。
三、自动文档功能
这是 FastAPI 最实用的特性之一。无需编写任何文档代码,框架会自动生成交互式接口文档。
启动服务后,访问 http://127.0.0.1:8000/docs,你会看到 Swagger UI 界面。可以直接在网页上点击 Try it out,填写参数并执行测试,极大简化了调试流程。
四、接收数据的方式
后端主要工作是接收前端数据、处理并返回结果。FastAPI 支持多种参数传递方式。
1. 路径参数 (Path Parameters)
场景:查询特定 ID 的资源,如 /student/5。
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/student/{student_id}")
def get_student(student_id: int):
return {
"学生 ID": student_id,
"类型": str(type(student_id))
}
if __name__ == "__main__":
uvicorn.run(app="main:app", host="127.0.0.1", port=8088)
注意函数参数中的 student_id: int。如果访问 /student/abc,FastAPI 会直接报错提示类型不匹配,这就是类型检查的优势。
2. 查询参数 (Query Parameters)
场景:类似搜索,如 /search?keyword=python&page=1。
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/search")
def search_data(keyword: str, page: int = 1):
return {
"你搜的词": keyword,
"当前页码": page
}
if __name__ == "__main__":
uvicorn.run(app="main:app", host="127.0.0.1", port=8088)
未提供的参数可使用默认值(如 page=1),符合 URL 规范。
五、Pydantic 数据模型
当需要接收复杂结构的数据(如注册信息)时,逐个定义函数参数会很混乱。FastAPI 内置 Pydantic 用于定义数据模型。
from fastapi import FastAPI
import uvicorn
from pydantic import BaseModel
app = FastAPI()
# 定义数据模型
class UserInfo(BaseModel):
username: str
password: str
age: int = 18
is_student: bool = True
@app.post("/register")
def register(user: UserInfo):
if user.age < 18:
return {"message": "未成年人禁止注册", "code": 400}
return {
"message": "注册成功",
"用户": user.username,
"身份": "学生" if user.is_student else "社会人"
}
if __name__ == "__main__":
uvicorn.run(app="main:app", host="127.0.0.1", port=8088)
在接口中使用 UserInfo 作为参数类型,FastAPI 会自动将前端传来的 JSON 解析并校验。若字段缺失或类型错误,框架会直接返回验证失败信息。
六、总结
掌握以上内容,你已经具备了 FastAPI 的基础开发能力:
- 安装:使用 pip 安装 fastapi 和 uvicorn。
- 启动:通过 uvicorn 运行应用。
- 文档:利用
/docs自动生成接口文档进行测试。 - 参数:利用类型提示约束路径和查询参数。
- 模型:使用 BaseModel 处理复杂的 POST 数据。
FastAPI 不仅提升了编码效率,更通过类型系统保证了代码的健壮性。后续可结合数据库进一步实现完整的业务逻辑。


