0%

FastAPI自学教程(26) - 路径操作配置

1. 状态码配置

1
2
3
4
5
6
7
8
9
10
11
12
13
from fastapi import FastAPI, status
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
name: str
description: str | None = None
price: float

@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
return item
  • 通过status_code参数定义HTTP响应状态码,支持直接使用整数或status模块常量(如HTTP_201_CREATED
  • 状态码会自动添加到OpenAPI文档和Swagger UI
  • 技术细节:fastapi.status继承自Starlette库,包含所有标准HTTP状态码

2. 标签分组

1
2
3
4
5
6
7
@app.post("/items/", tags=["items"])
async def create_item(item: Item):
return item

@app.get("/users/", tags=["users"])
async def read_users():
return [{"username": "johndoe"}]
  • 使用tags参数传递字符串列表实现接口分组管理
  • 支持枚举管理标签(需导入Enum类),确保大型项目标签一致性
  • 文档效果:Swagger UI会自动生成分组导航栏

3. 摘要与描述

1
2
3
4
5
6
7
@app.post(
"/items/",
summary="创建物品",
description="创建包含完整信息的物品实体,支持名称、价格等字段"
)
async def create_item(item: Item):
return item
  • summary用于简短描述接口功能(显示在接口列表)
  • description支持多行详细说明(显示在接口详情页)
  • 扩展技巧:可通过函数docstring自动生成描述(使用\f字符截断OpenAPI显示内容)

4. 响应模型与描述

1
2
3
4
5
6
7
@app.post(
"/items/",
response_model=Item,
response_description="成功创建的新物品实体"
)
async def create_item(item: Item):
return item
  • response_model定义响应数据结构,自动过滤未声明字段
  • response_description参数用于描述响应内容(默认显示”Successful Response”)
  • 支持组合使用:response_model=List[Item]可定义列表响应

5. 高级配置

1
2
3
@app.get("/items/", include_in_schema=False, deprecated=True)
async def hidden_api():
return {"message": "内部接口"}
  • include_in_schema=False可从OpenAPI文档中隐藏接口
  • deprecated=True标记已弃用接口(文档显示删除线)