FastAPI 教程翻译 - 用户指南 22 - 路径操作配置

FastAPI 教程翻译 - 用户指南 22 - 路径操作配置

FastAPI Tutorial - User Guide - Path Operation Configuration

There are several parameters that you can pass to your path operation decorator to configure it.

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

Warning

警告

Notice that these parameters are passed directly to the path operation decorator, not to your path operation function.

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

Response Status Code

响应状态码

You can define the (HTTP) status_code to be used in the response of your path operation.

您可以定义(HTTP)status_code 以在路径操作的响应中使用。

You can pass directly the int code, like 404.

您可以直接传递 int 代码,例如 404

But if you don’t remember what each number code is for, you can use the shortcut constants in status:

但是,如果您不记得每个数字代码的用途,则可以在 status 中使用快捷的常量:

from typing import Set

from fastapi import FastAPI, status
from pydantic import BaseModel

app = FastAPI()


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


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

That status code will be used in the response and will be added to the OpenAPI schema.

该状态码将在响应中使用,并将添加到 OpenAPI 架构中。

Technical Details

技术细节

You could also use from starlette import status.

您也可以使用 from starlette import status

FastAPI provides the same starlette.status as fastapi.status just as a convenience for you, the developer. But it comes directly from Starlette.

FastAPI 提供与 starlette.status 相同的 fastapi.status,以方便开发人员。但它直接来自 Starlette。

Tags

标签

You can add tags to your path operation, pass the parameter tags with a list of str (commonly just one str):

您可以将标签添加到路径操作中,并通过带有 str 的列表的参数 tags(通常只有一个 str)传递:

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@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"}]

They will be added to the OpenAPI schema and used by the automatic documentation interfaces:

它们将被添加到 OpenAPI 架构中,并由自动文档界面使用:

在这里插入图片描述

Summary and description

摘要和说明

You can add a summary and description:

您可以添加 summarydescription

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@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

Description from docstring

来自文档字符串的描述

As descriptions tend to be long and cover multiple lines, you can declare the path operation description in the function docstring and FastAPI will read it from there.

由于描述可能会很长并且涵盖多行,因此您可以在函数的文档字符串中声明路径操作描述,并且 FastAPI 将从那里读取它。

You can write Markdown in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation).

您可以在文档字符串中写入 Markdown,它将被正确解释和显示(考虑到文档字符串缩进)。

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@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

It will be used in the interactive docs:

它将在交互式文档中使用:

在这里插入图片描述

Response description

响应说明

You can specify the response description with the parameter response_description:

您可以使用参数 response_description 指定响应描述:

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@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

Info

信息

Notice that response_description refers specifically to the response, the description refers to the path operation in general.

请注意,response_description 特别指响应,description 通常指路径操作

Check

检查

OpenAPI specifies that each path operation requires a response description.

OpenAPI 指定每个路径操作都需要响应描述。

So, if you don’t provide one, FastAPI will automatically generate one of “Successful response”.

因此,如果您不提供任何一种,FastAPI 将自动生成『成功响应』之一。

在这里插入图片描述

Deprecate a path operation

弃用路径操作

If you need to mark a path operation as deprecated, but without removing it, pass the parameter 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"}]

It will be clearly marked as deprecated in the interactive docs:

在交互式文档中,它将被明确标记为不推荐使用:

在这里插入图片描述

Check how deprecated and non-deprecated path operations look like:

检查已弃用和未弃用的路径操作如下:

在这里插入图片描述

Recap

回顾

You can configure and add metadata for your path operations easily by passing parameters to the path operation decorators.

您可以通过将参数传递给路径操作修饰符,轻松地为路径操作配置和添加元数据。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值