跳到内容

路径操作配置

你可以将多个参数传递给路径操作装饰器来进行配置。

警告

请注意,这些参数是直接传递给路径操作装饰器的,而不是传递给你的路径操作函数

响应状态码

你可以定义用于路径操作响应的 (HTTP) status_code

你可以直接传入 int 类型的代码,例如 404

但如果你记不住每个数字代码的含义,可以使用 status 模块中的快捷常量。

from fastapi import FastAPI, status
from pydantic import BaseModel

app = FastAPI()


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


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

该状态码将用于响应,并会被添加到 OpenAPI 模式中。

技术细节

你也可以使用 from starlette import status

FastAPI 提供了与 starlette.status 相同的 fastapi.status,这只是为了方便开发者使用,其底层内容直接来自 Starlette。

标签

你可以为路径操作添加标签,通过传递 tags 参数,其值为 strlist(通常只有一个 str)。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@app.post("/items/", tags=["items"])
async def create_item(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 模式中,并被自动生成的文档界面所使用。

使用枚举类型的标签

如果你的应用程序很大,最终可能会积累多个标签,你可能希望确保相关路径操作始终使用相同的标签

在这种情况下,将标签存储在 Enum 中是有意义的。

FastAPI 支持以与普通字符串相同的方式使用枚举。

from enum import Enum

from fastapi import FastAPI

app = FastAPI()


class Tags(Enum):
    items = "items"
    users = "users"


@app.get("/items/", tags=[Tags.items])
async def get_items():
    return ["Portal gun", "Plumbus"]


@app.get("/users/", tags=[Tags.users])
async def read_users():
    return ["Rick", "Morty"]

摘要和描述

你可以添加 summary(摘要)和 description(描述)。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@app.post(
    "/items/",
    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) -> Item:
    return item

从文档字符串获取描述

由于描述往往很长且跨越多行,你可以在函数内部的 文档字符串 (docstring) 中声明路径操作的描述,FastAPI 会从那里读取它。

你可以在文档字符串中使用 Markdown,它会被正确解析并显示(同时会考虑文档字符串的缩进)。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@app.post("/items/", summary="Create an item")
async def create_item(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 参数指定响应描述。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@app.post(
    "/items/",
    summary="Create an item",
    response_description="The created item",
)
async def create_item(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),但又不想将其移除,请传递 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"}]

它将在交互式文档中被清楚地标记为“已弃用”。

查看已弃用和未弃用的路径操作呈现效果。

总结

通过向路径操作装饰器传递参数,你可以轻松配置和添加路径操作的元数据。