来源:黑马程序员PythonWeb开发:FastAPI从入门到实战视频教程,涵盖路由、依赖注入、Pydantic、异步编程、ORM、项目拆分、模型训练、部署、接口测试2025-12-10 09:00:00
本文开始日期:2026-10-15 15:03
1.基础语法
FastAPI是一个基于Python的高性能Web框架,专门用于快速构建API接口服务
- 异步性能高
- 开发效率高
- 自动生成文档


快速入门:
python
from fastapi import FastAPI
# 创建一个fastapi实例
app = FastAPI()
# async代表异步,被async修饰的函数,是异步函数,可以处理并发请求。
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/hello/{name}")
async def say_hello(name: str):
return {"message": f"Hello {name}"}
1.1路由
路由就是 URL地址和处理函数 之间的映射关系,它决定了当用户访问某个特定网址时,服务器应该执行哪段代码来返回结果。

1.2参数
参数就是客户端发送请求时 附带的额外信息和指令
参数的作用是让同一个接口能根据不同的输入,返回不同的输出,实现动态交互

1.2.1路径参数

python
@app.get("/book/{id}")
async def get_book(id: int):
return {"id": id, "title": f"得到第{id}章"}
注意类型注解影响返回值:
- 如果是int,返回{"id" : 666, "title" : "得到第666章"};如果是str,返回{"id" : "666", "title" : "得到第666章"};
- 上面的类型注解是
python原生注解,接下来看看Path注解
对于路径参数的例子,思考:如果要限制id在1-100,该怎么做?
FaStAPI允许为参数声明额外的信息和校验

python
from fastapi import FastAPI,Path
# 使用Path参数限制id的范围在1-100
@app.get("/book/{id}")
async def get_book(id: int = Path(..., gt=0, lt=101, description="书籍id限制在1到100之间")):
return {"id": id, "title": f"得到第{id}章"}
# 使用Path参数限制name的长度在2-10
@app.get("/author/{name}")
async def get_name(name: str = Path(..., min_length=2, max_length=10)):
return {"msg": f"这是{name}的信息"}
1.2.2查询参数

python
@app.get("/news/news_list")
async def get_news_list(skip: int, limit: int = 10):
return {"skip": skip, "limit": limit, "msg": "获取新闻列表成功"}
同样,如果需要对查询参数做限制,可以使用原生注解,也可以使用Query注解:
python
from fastapi import FastAPI, Query
# 使用Query注解:skip参数默认值为0,需要小于100;limit参数默认值为10
@app.get("/news/news_list")
async def get_news_list(
skip: int = Query(0, description="跳过的记录数", lt=100),
limit: int = Query(10, description="返回的记录数")
):
return {"skip": skip, "limit": limit, "msg": "获取新闻列表成功"}
1.2.3请求体参数


python
from fastapi import FastAPI,Path, Query
from pydantic import BaseModel
# 创建一个fastapi实例
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
class User(BaseModel):
username: str
password: str
@app.post("/register")
async def register(user: User):
return user
同样,如果需要对请求体参数做限制,可以使用原生注解,也可以使用Field注解:
python
from pydantic import BaseModel,Field
class User(BaseModel):
username: str = Field(default="张三", min_length=2, max_length=10,description="用户名,长度2-10个字")
password: str = Field(min_length=3, max_length=20, description="密码,长度3-20个字")
@app.post("/register")
async def register(user: User):
return user
1.3响应类型
1.3.1-JSON格式
- 默认情况下,FastAPI会 自动 将路径操作函数返回的 Python对象 (字典、列表、Pydantic模型等),经由jsonable_encoder转换为JSON 兼容格式,并包装为JSONResponse返回。
- 这省去了手动序列化的步骤,让开发者能更专注于业务逻辑。
- 如果需要返回非JSON数据 (如HTML、文件流),FastAPI提供了丰富的响应类型来返回不同数据

响应类型设置方式:


1.3.2-HTML格式
python
from fastapi.responses import HTMLResponse
@app.get("/html", response_class=HTMLResponse)
async def html_res():
return "<h1>html响应格式</h1>"
1.3.3文件格式
FileResponse是FastAPI提供的专门用于高效返回文件内容(如图片、PDF、Excel、音视频等)的响应类。它能够智能处理文件路径、媒体类型推断、范围请求和缓存头部,是服务静态文件的推荐方式。
python
from fastapi.responses import FileResponse
@app.get("/file")
async def get_file():
file_path = r"./1.jpg"
return FileResponse(file_path)
1.3.4自定义响应数据格式

1.3.5异常响应处理
