三周精通FastAPI:17 Path Operation Configuration路径操作配置

路径操作配置

路径操作装饰器支持多种配置参数。

"警告"

注意:以下参数应直接传递给路径操作装饰器,不能传递给路径操作函数

status_code 状态码

status_code 用于定义路径操作响应中的 HTTP 状态码。

可以直接传递 int 代码, 比如 404。如果记不住数字码的涵义,也可以用 status 的快捷常量:

from typing import Set, Union

from fastapi import FastAPI, status
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: Set[str] = set()


@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
    return item

状态码在响应中使用,并会被添加到 OpenAPI 概图。

"技术细节"

也可以使用 from starlette import status 导入状态码。

FastAPI 的fastapi.status 和 starlette.status 一样,只是快捷方式。实际上,fastapi.status 直接继承自 Starlette。

tags 参数

tags 参数的值是由 str 组成的 list (一般只有一个 str ),tags 用于为路径操作添加标签:

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: 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"}]

OpenAPI 概图会自动添加标签,供 API 文档接口使用:

summary 和 description 参数

路径装饰器还支持 summary 和 description 这两个参数:

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: 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

文档字符串(docstring

描述内容比较长且占用多行时,可以在函数的 docstring 中声明路径操作的描述,FastAPI 支持从文档字符串中读取描述内容。文档字符串支持 Markdown,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: 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 文档中的显示效果:

响应描述

response_description 参数用于定义响应的描述说明:

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: 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

"说明"

注意,response_description 只用于描述响应,description 一般则用于描述路径操作

"检查"

OpenAPI 规定每个路径操作都要有响应描述。

如果没有定义响应描述,FastAPI 则自动生成内容为 "Successful response" 的响应描述。

 

弃用路径操作

deprecated 参数可以把路径操作标记为弃用,无需直接删除:

from fastapi import FastAPI

app = 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"}]

API 文档会把该路径操作标记为弃用:

下图显示了正常路径操作与弃用路径操作 的区别:

小结

通过传递参数给路径操作装饰器 ,即可轻松地配置路径操作、添加元数据。

实践

用一个综合代码片段进行实践

源代码

将代码写入pathop.py文件

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: 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",
    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


@app.get("/elements/", tags=["items"], deprecated=True)
async def read_elements():
    return [{"item_id": "Foo"}]

启动服务

uvicorn pathop:app --reload

测试服务

浏览器浏览docs

浏览网址:http://127.0.0.1:8000/docs

仔细观察设定的tags、summary以及文档字符串等。

curl命令进行测试

curl -X POST "http://127.0.0.1:8000/items/" -H "Content-Type: application/json" -d '{ "name": "Example Item", "description": "This is an example item description.", "price": 19.99, "tax": 2.5, "tags": ["example", "test"]  }'

输出:

{"name":"Example Item","description":"This is an example item description.","price":19.99,"tax":2.5,"tags":["example","test"]}

总结:

实践中获得:

若写了description参数,则文档字符串不显示。

弃用还是可以用curl通信的

curl -X GET "http://127.0.0.1:8000/elements/"
[{"item_id":"Foo"}]

猜你喜欢

转载自blog.csdn.net/skywalk8163/article/details/143267353