FastAPI:(7)路劲操作配置与JSON编码兼容
FastAPI:(7)路劲操作配置与JSON编码兼容
由于CSDN无法展示「渐构」的「#d,#e,#t,#c,#v,#a」标签,推荐访问我个人网站进行阅读:Hkini
「渐构展示」如下:
#c 概述 文章内容
1.路劲操作装饰器配置
#d 路劲装饰器配置
路径操作装饰器配置是FastAPI中定义API接口路径与请求方法(如GET、POST等) 之间映射关系的机制。开发者通过在「路劲操作函数」前添加装饰器(如@app.get()
、@app.post()
)来绑定URL路径与处理逻辑。这一配置不仅决定了请求的访问方式,还能绑定请求参数、文档信息、标签和响应模型等元数据,使得API行为更清晰、易管理、自动文档化。
重要特征:
- 特征1:明确的请求方法绑定:每个装饰器绑定一个或多个HTTP请求方法(GET/POST/PUT/DELETE等),体现操作语义。
- 特征2:路径与逻辑强关联:装饰器配置将路径(URL)和业务逻辑函数精确绑定,提升可读性与维护性。
- 特征3:可绑定元数据:路径操作装饰器可配合参数如
summary
、description
、tags
、response_model
,增强文档生成和可维护性。 - 特征4:自动文档集成:基于装饰器配置,FastAPI可自动生成OpenAPI规范与Swagger UI界面,无需额外书写文档。
#e 电商查询接口的配置
现象:
电商平台需要为用户提供一个商品查询接口,使用GET方法访问/items/{item_id}
,函数逻辑为从数据库中查询商品信息。此接口使用路径参数item_id
绑定,并带有描述元数据和响应模型。
特征对比:
- ✔ 特征1(请求方法明确):使用GET方法,体现查询操作,符合REST语义;
- ✔ 特征2(路径-逻辑绑定):路径
/items/{item_id}
与商品查询函数一一对应; - ✔ 特征3(元数据):附带summary、description,支持自动文档;
- ✔ 特征4(自动文档):FastAPI自动将此接口展示在Swagger UI中,结构清晰。
from fastapi import FastAPI, UploadFile, File
from pydantic import BaseModelapp = FastAPI()# 正例1:商品查询接口
class Item(BaseModel):id: intname: strprice: float@app.get("/items/{item_id}", summary="获取商品信息", description="根据商品ID查询商品详细信息", response_model=Item)
def read_item(item_id: int):return {"id": item_id, "name": "Example Product", "price": 99.99}
#e status_code
状态码
status_code
用于定义_路径操作_响应中的 HTTP 状态码。可以直接传递 int
代码, 比如 404
。如果记不住数字码的涵义,也可以用 status
的快捷常量。
from typing import Set, Unionfrom fastapi import FastAPI, status
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = Nonetags: Set[str] = set()@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):return item
#e tags参数
tags
参数的值是由 str
组成的 list
(一般只有一个 str
),tags
用于为_路径操作_添加标签:
from typing import Set, Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = Nonetags: Set[str] = set()@app.post("/items/", response_model=Item, tags=["items"])
async def create_item(item: Item):return item@app.get("/items/", tags=["items"])
async def read_items():return [{"name": "Foo", "price": 42}]@app.get("/users/", tags=["users"])
async def read_users():return [{"username": "johndoe"}]
#e 摘要与描述参数
from typing import Set, Union
from fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = Nonetags: Set[str] = set()@app.post("/items/",response_model=Item,summary="Create an item",description="Create an item with all the information, name, description, price, tax and a set of unique tags",
)
async def create_item(item: Item):return item
#e 文档字符串
描述内容比较长且占用多行时,可以在函数的 docstring 中声明_路径操作_的描述,FastAPI 支持从文档字符串中读取描述内容。
文档字符串支持 Markdown,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进
from typing import Set, Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = Nonetags: Set[str] = set()@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(item: Item):"""Create an item with all the information:- **name**: each item must have a name- **description**: a long description- **price**: required- **tax**: if the item doesn't have tax, you can omit this- **tags**: a set of unique tag strings for this item"""return item
下图为 Markdown 文本在 API 文档中的显示效果:
#e 响应描述
response_description
参数用于定义响应的描述说明。
注意,response_description
只用于描述响应,description
一般则用于描述_路径操作_。
OpenAPI 规定每个_路径操作_都要有响应描述。如果没有定义响应描述,FastAPI 则自动生成内容为 “Successful response” 的响应描述。
from typing import Set, Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = Nonetags: Set[str] = set()@app.post("/items/",response_model=Item,summary="Create an item",response_description="The created item",
)
async def create_item(item: Item):"""Create an item with all the information:- **name**: each item must have a name- **description**: a long description- **price**: required- **tax**: if the item doesn't have tax, you can omit this- **tags**: a set of unique tag strings for this item"""return item
#e 弃用路劲操作
deprecated
参数可以把_路径操作_标记为弃用,无需直接删除:
from fastapi import FastAPIapp = FastAPI()@app.get("/items/", tags=["items"])
async def read_items():return [{"name": "Foo", "price": 42}]@app.get("/users/", tags=["users"])
async def read_users():return [{"username": "johndoe"}]@app.get("/elements/", tags=["items"], deprecated=True)
async def read_elements():return [{"item_id": "Foo"}]
2.JSON编码兼容
#c 场景 编码兼容
在某些情况下,可能需要将数据类型(如Pydantic模型)转换为与JSON兼容的数据类型(如dict
、list
等)。比如,如果需要将其存储在数据库中。对于这种要求, FastAPI提供了jsonable_encoder()
函数。
#e jsonable_encoder
假设有一个数据库名为fake_db
,它只能接收与JSON兼容的数据。例如,它不接收datetime
这类的对象,因为这些对象与JSON不兼容。因此,datetime
对象必须将转换为包含ISO格式化的str
类型对象。
同样,这个数据库也不会接收Pydantic模型(带有属性的对象),而只接收dict
。对此可以使用jsonable_encoder
。它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本。
from datetime import datetimefrom fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModelfake_db = {}class Item(BaseModel):title: strtimestamp: datetimedescription: str | None = Noneapp = FastAPI()@app.put("/items/{id}")
def update_item(id: str, item: Item):json_compatible_item_data = jsonable_encoder(item)fake_db[id] = json_compatible_item_data
这个例子中,它将Pydantic模型转换为dict
,并将datetime
转换为str
。调用它的结果后就可以使用Python标准编码中的json.dumps()
。
这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的str
。它将返回一个Python标准数据结构(例如dict
),其值和子值都与JSON兼容。