FastAPI
核心优势
轻量异步API框架(ASGI),原生支持async/await,性能高,支持Pydantic数据自动校验,自动生成Swagger交互式接口文档,强依赖类型注解。
快速启动
python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
@app.get("/name/{name}")
def get_name(name: str):
return {"message": f"Hello, {name}!"}
命令行启动方式:
bash
# 用 Uvicorn 启动一个 ASGI 服务,加载 main.py里的 app对象,并在代码变更时自动重启。
uvicorn <模块名>:app --reload
# 例如
uvicorn main:app --reload
启动成功后:
bash
(fastapi-app) PS D:\projects\FastAPI> uvicorn demo1:app --reload
INFO: Will watch for changes in these directories: ['D:\\projects\\FastAPI']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [22148] using WatchFiles
INFO: Started server process [30640]
INFO: Waiting for application startup.
INFO: Application startup complete.
启动之后:
路由
路由就是 URL 地址和处理函数之间的映射关系,它决定了当用户访问某个特定网址时,服务器应该执行哪段代码来返
回结果。
路径参数
python
@app.get("/books/{id}")
def get_book_by_id(id :int):
类型注解Path
导入Path函数
python
from fastapi import Path
@app.get("/books/{id}")
def get_book_by_id(id :int = Path()):
FastAPI Path 函数常用参数一览
| 参数名 | 类型 | 说明 |
|---|---|---|
default |
Any | 默认值。若为 ... 则表示该参数是必填的路径参数。 |
alias |
str | 参数别名。例如在路径中是 {item_id},代码中可用 alias="item_id" 映射。 |
title |
str | 参数标题,用于 API 文档(Swagger/ReDoc)显示。 |
description |
str | 参数的详细描述,显示在文档中。 |
gt |
float | 数值校验:大于(Greater Than)。 |
ge |
float | 数值校验:大于等于(Greater than or Equal)。 |
lt |
float | 数值校验:小于(Less Than)。 |
le |
float | 数值校验:小于等于(Less than or Equal)。 |
min_length |
int | 字符串/列表长度校验:最小长度。 |
max_length |
int | 字符串/列表长度校验:最大长度。 |
pattern |
str | 字符串正则匹配校验(Pydantic v1);v2 推荐使用 str.regex()。 |
regex |
str | (Pydantic v1 遗留)正则表达式校验,功能同 pattern。 |
deprecated |
bool | 标记该路径参数是否已弃用,文档中会显示为灰色。 |
example |
Any | 单个请求示例,显示在文档中(OpenAPI 2.0 / 非严格模式)。 |
examples |
Dictstr, Any | 多个请求示例,OpenAPI 3.0+ 推荐用法,可在文档中展示多种场景。 |
include_in_schema |
bool | 是否将该参数包含在 OpenAPI 文档中(设为 False 则隐藏)。 |
json_schema_extra |
dict | Callable | 附加额外的 JSON Schema 字段(如 {"x-custom-field": "value"}),用于扩展文档元数据。 |
查询参数
声明的参数不是路径参数时,路径操作函数会把该参数自动解释为查询参数。
python
@app.get("/books")
def get_book_by_id(id: int, name: str = "你好"):
类型注解Query
导入 Query 函数
python
from fastapi import Query
@app.get("/books")
def get_book_by_id(
id: int = Query(...,gt=1,description="The ID of the book"),
name: str = "你好"):
请求体参数
一个完整的HTTP请求包含三部分:
-
请求行:方法、URL、协议版本
-
请求头:元数据信息(Content-Type、Authorization)
-
请求体:实际发送数据
-
定义参数
python
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
- 类型注解
python
@app.post("/users")
def register(user: User):
类型注解Field
导入pydantic的Field函数
python
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(...)
age: int = Field(...)
请求和响应
响应类型
默认情况下,FastAPI会自动将路径操作函数返回的 Python对象(字典、列表、Pydantic 模型等),经由jsonable_encoder 转换为
JSON 兼容格式,并包装为 JSONResponse 返回。这省去了手动序列化的步骤,让开发者能更专注于业务逻辑。
如果需要返回非 JSON 数据(如 HTML、文件流),FastAPI提供了丰富的响应类型来返回不同数据。
| 响应类型 | 用途 | 示例 |
|---|---|---|
JSONResponse |
默认响应,返回JSON数据 | return {"key": "value"} |
HTMLResponse |
返回HTML内容 | return HTMLResponse(html_content) |
| PlainTextResponse | 返回纯文本 | return PlainTextResponse("text") |
FileResponse |
返回文件下载 | return FileResponse(path) |
| StreamingResponse | 流式响应 | 生成器函数返回数据 |
| RedirectResponse | 重定向 | return RedirectResponse(url) |
响应类型设置方式
- 装饰器中指定响应类:固定返回类型(HTML、纯文本等)
python
@app.get("/html", response_class=HTMLResponse)
def get_html():
- 返回响应对象:适用于文件下载、图片、流式响应
python
@app.get("/file")
def get_file():
file_path= "./files/file.txt"
return FileResponse(file_path)
自定义响应数据格式
response_model是路径操作装饰器(如@app.get或@app.post)的关键参数,它通过一个Pydantic模型来严格定义和约束API端点的输出格式。
这一机制在提供自动数据验证和序列化的同时,更是保障数据安全性的第一道防线。
python
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
age: int
@app.get("/users/{id}", response_model=User)
def get_user(id: int):
return {
"id": id,
"name": "name",
"age": 2
}
异常处理
对于客户端引发的错误(4xx,如资源未找到、认证失败),应使用 fastapi.HTTPException 来中断正常处理流程,并返回标准错误响应。
python
from fastapi import FastAPI, HTTPException
@app.get('/user/{id}')
def get_user(id: int):
id_list = [1,2,3]
if id not in id_list:
raise HTTPException(status_code=404, detail="用户id不存在")
return {"id": id}
中间件
使用中间件为每个请求前后添加统一的处理逻辑
中间件(Middleware)是一个在每次请求进入FastAPI应用时都会被执行的函数。
它在请求到达实际的路径操作(路由处理函数)之前运行,并且在响应返回给客户端之前再运行一次。
中间件:函数顶部使用装饰器@app.middleware("http")
python
@app.middleware("http")
def middleware(request, call_next):
print('中间件 start')
response = call_next(request)
print('中间件 end')
return response
当存在多个中间件时,中间件自下而上执行,并且先执行后结束,后执行先结束
依赖注入
使用依赖注入系统来共享通用逻辑,减少重复代码
依赖项:可重用的组件(函数/类),负责提供某种功能或数据。
注入:FastAPI自动调用依赖项,并将结果"注入"到路径操作函数中。
优点:
- 代码复用
- 解耦
- 易于测试:使用模拟依赖替换真实依赖测试
步骤
- 创建依赖项
- 导入Depends
- 声明依赖项
例如分页参数逻辑公用
python
from fastapi import Depends
def common_parameters(
skip: int = Query(0, ge=0),
limit: int = Query(10, le=60)
):
return {"skip": skip, "limit": limit}
@app.get("/user/user_list")
def get_user_list(commons=Depends(common_parameters)):
return commons