5. FastApi 路由管理

FastAPI 常用请求装饰器

  1. @app.get()

    • 处理 GET 请求,用于从服务器获取数据。
    • 通常用于获取资源(比如读取数据)而不修改它们。
    python 复制代码
    @app.get("/items/{item_id}")
    async def read_item(item_id: int):
        return {"item_id": item_id, "name": "Item Name"}
  2. @app.post()

    • 处理 POST 请求,用于向服务器提交数据(例如创建新的资源)。
    • 通常用于创建新的条目或提交数据。
    python 复制代码
    @app.post("/items/")
    async def create_item(item: Item):
        return {"item_id": 1, "name": item.name}
  3. @app.put()

    • 处理 PUT 请求,用于更新现有资源。
    • 完全替换目标资源的内容,通常是替换整个资源。
    python 复制代码
    @app.put("/items/{item_id}")
    async def update_item(item_id: int, item: Item):
        return {"item_id": item_id, "name": item.name}
  4. @app.patch()

    • 处理 PATCH 请求,用于部分更新现有资源。
    • 只会更新资源的一部分,而不是整个资源。
    python 复制代码
    @app.patch("/items/{item_id}")
    async def partial_update_item(item_id: int, item: Item):
        return {"item_id": item_id, "name": item.name}
  5. @app.delete()

    • 处理 DELETE 请求,用于删除现有资源。
    python 复制代码
    @app.delete("/items/{item_id}")
    async def delete_item(item_id: int):
        return {"message": "Item deleted successfully"}

FastApi 请求装饰器的常用参数

1. tags

  • tags 是一个列表,用于为 API 路由分组。在生成的文档(Swagger UI)中,这些标签会将接口分组,帮助用户更好地理解和浏览不同类别的 API。
  • 常用于对相似功能的路由进行分类。
csharp 复制代码
@app.get("/items/", tags=["items"])
async def get_items():
    return {"message": "Items list"}
  • 在 Swagger UI 中,接口会根据 tags 分类,类似于分组的效果。

2. summary

  • summary 是一个简短的描述,概述该路由的功能。
  • 在 Swagger UI 中,它会作为每个路由的标题显示,帮助用户快速理解该路由的作用。
python 复制代码
@app.get("/items/{item_id}", summary="Get item by ID")
async def get_item(item_id: int):
    return {"item_id": item_id}

3. description

  • description 提供了更详细的描述,解释该路由的作用、参数、返回值等。它会在 Swagger UI 中显示为该接口的详细说明。
  • 适用于需要解释业务逻辑或额外细节的情况。
python 复制代码
@app.get("/items/{item_id}", description="Fetch an item by its unique ID.")
async def get_item(item_id: int):
    return {"item_id": item_id, "name": "Item Name"}

response_model

  • response_model 用于指定该路由返回的响应模型,可以是一个 Pydantic 模型。FastAPI 会根据这个模型自动生成文档,并进行数据验证。
  • 如果你返回的是复杂的数据结构,使用 response_model 来规范响应格式。
python 复制代码
class Item(BaseModel):
    name: str
    description: str

@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
    return {"name": "Item Name", "description": "Item Description"}

status_code

  • status_code 用来指定该路由的 HTTP 响应状态码。
  • 默认情况下,FastAPI 会自动为 GET 请求返回 200 OK,而 POST 请求返回 201 Created,但你可以通过该参数自定义状态码。
python 复制代码
@app.post("/items/", status_code=201)
async def create_item(item: Item):
    return {"name": item.name, "description": item.description}

response_description

  • response_description 用于为响应添加自定义描述,在生成的 OpenAPI 文档中显示。
  • 它可以帮助用户理解响应的内容,尤其是在响应结构比较复杂时。
python 复制代码
@app.get("/items/{item_id}", response_description="Details of the requested item")
async def get_item(item_id: int):
    return {"item_id": item_id, "name": "Item Name"}

responses

  • responses 用于为不同的 HTTP 状态码提供自定义描述或响应内容。你可以为不同的状态码指定不同的描述信息或返回模型。
  • 常用于处理错误或异常情况,并在文档中为不同状态码提供详细说明。
python 复制代码
@app.get("/items/{item_id}", responses={404: {"description": "Item not found"}})
async def get_item(item_id: int):
    if item_id != 1:
        return {"message": "Item not found"}, 404
    return {"item_id": item_id, "name": "Item Name"}

deprecated

  • deprecated 用来标记一个路由是否为过时的。设置为 True 会在 Swagger UI 中标记该接口为已废弃。
  • 这在你计划逐步淘汰某些 API 时非常有用。
python 复制代码
@app.get("/old-items/", deprecated=True)
async def get_old_items():
    return {"message": "This API is deprecated"}

operation_id

  • operation_id 是 OpenAPI 的一个标准字段,用于为每个操作指定一个唯一的 ID。这有助于生成更具可识别性的 API 文档。
  • 如果没有指定,FastAPI 会自动生成一个基于路由的名称作为 ID。
python 复制代码
@app.get("/items/{item_id}", operation_id="get_item_by_id")
async def get_item(item_id: int):
    return {"item_id": item_id}

示例:

python 复制代码
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

# 定义响应模型,使用 Field 来为字段添加描述
class StudentResponse(BaseModel):
    id: int = Field(..., description="学生ID")
    name: str = Field(..., description="学生姓名")
    sex: str = Field(..., description="学生性别")
    school_class: str = Field(None, description="学生所在班级")

@app.get("/students/{item_id}",
         tags=["tags_students"],
         summary="summary_通过ID获取学生信息",
         description="description_查询学生ID一个学生的信息(包含学生ID,姓名,性别,班级)",
         response_model=StudentResponse,
         response_description="response_description_返回数据为学生详细信息",
         responses={404: {"description": "未找见该学生信息"}, 500: {"description": "服务器内部错误"}, 422: {"description": "请求参数错误"}},
         deprecated=False,
         operation_id="operation_id_get_student_info_by_id"
        )
async def read_item(item_id: int):
    if item_id == 1:
        return {500: {"message": "服务器内部错误"}}
    return {"id": item_id, "name": "李明", "sex": "男", "school_class": "1班"}

设置deprecated 为True 时

路由分发 include_router

使用 include_router 可以实现将多个路由分组并进行模块化管理。在主应用中引入和注册这些路由模块,可以使用 prefixtags 进行路由分组和管理。

结构化目录你可以将不同的路由文件分别管理,比如:

bash 复制代码
/my_project
    /app
        /main.py       # 主应用文件
        /routers
            __init__.py  # 初始化包
            items.py    # items 路由模块
            users.py    # users 路由模块

main.py

ini 复制代码
from fastapi import FastAPI
from routers.items import items_router
from routers.users import users_router

app = FastAPI()

# 引入不同的路由
app.include_router(items_router, prefix="/v1/items", tags=["items"])
app.include_router(users_router, prefix="/v1/users", tags=["users"])

items.py

python 复制代码
from fastapi import APIRouter
from pydantic import BaseModel

# 创建一个 APIRouter 实例
items_router = APIRouter()

# 定义数据模型
class Item(BaseModel):
    name: str
    description: str

# 定义路由
@items_router.get("/items/{item_id}")
async def get_item(item_id: int):
    return {"item_id": item_id, "name": "Item Name", "description": "Item Description"}

@items_router.post("/items/")
async def create_item(item: Item):
    return {"message": "Item created", "item": item}

与Flask 的蓝图 对比

  • Flask 蓝图:适用于传统 Web 应用,可以将应用分解成多个蓝图,每个蓝图管理一部分功能,支持视图函数、模板、静态文件等。

  • FastAPI APIRouter:适用于 API 应用,主要用于将路由模块化,专注于路由的分离、API 文档生成和异步支持。

相关推荐
m0_748240549 分钟前
Springboot项目:使用MockMvc测试get和post接口(含单个和多个请求参数场景)
java·spring boot·后端
恋恋西风16 分钟前
CT dicom 去除床板 去除床位,检查床去除
python·vtk·dicom·去床板
Doker 多克31 分钟前
Python Django系列—入门实例
python·django
LUCIAZZZ36 分钟前
SkyWalking快速入门
java·后端·spring·spring cloud·微服务·springboot·skywalking
geovindu1 小时前
python: SQLAlchemy (ORM) Simple example using mysql in Ubuntu 24.04
python·mysql·ubuntu
nuclear20111 小时前
Python 将PPT幻灯片和形状转换为多种图片格式(JPG, PNG, BMP, SVG, TIFF)
python·ppt转图片·ppt转png·ppt转jpg·ppt转svg·ppt转tiff·ppt转bmp
方圆想当图灵1 小时前
高性能缓存设计:如何解决缓存伪共享问题
后端·代码规范
没有晚不了安1 小时前
1.13作业
开发语言·python
刀客1231 小时前
python小项目编程-中级(1、图像处理)
开发语言·图像处理·python