Categories: FastAPI 教程

FastAPI教程 路径操作的高级配置

OpenAPI 的 operationId

Warning

如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。

你可以在路径操作中通过参数 operation_id 设置要使用的 OpenAPI operationId。

务必确保每个操作路径的 operation_id 都是唯一的。

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/", operation_id="some_specific_id_you_define")
async def read_items():
    return [{"item_id": "Foo"}]

使用 路径操作函数 的函数名作为 operationId

如果你想用你的 API 的函数名作为 operationId 的名字,你可以遍历一遍 API 的函数名,然后使用他们的 APIRoute.name 重写每个 路径操作 的 operation_id。

你应该在添加了所有 路径操作 之后执行此操作。

from fastapi import FastAPI
from fastapi.routing import APIRoute

app = FastAPI()


@app.get("/items/")
async def read_items():
    return [{"item_id": "Foo"}]


def use_route_names_as_operation_ids(app: FastAPI) -> None:
    """
    Simplify operation IDs so that generated API clients have simpler function
    names.

    Should be called only after all routes have been added.
    """
    for route in app.routes:
        if isinstance(route, APIRoute):
            route.operation_id = route.name  # in this case, read_items


use_route_names_as_operation_ids(app)

Tip

如果你手动调用 app.openapi(),你应该在此之前更新 operationId。

Warning

如果你这样做,务必确保你的每个 路径操作函数 的名字唯一。

即使它们在不同的模块中(Python 文件)。

从 OpenAPI 中排除

使用参数 include_in_schema 并将其设置为 False ,来从生成的 OpenAPI 方案中排除一个 路径操作(这样一来,就从自动化文档系统中排除掉了)。

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/", include_in_schema=False)
async def read_items():
    return [{"item_id": "Foo"}]

docstring 的高级描述

你可以限制 路径操作函数 的 docstring 中用于 OpenAPI 的行数。

添加一个 f (一个「换页」的转义字符)可以使 FastAPI 在那一位置截断用于 OpenAPI 的输出。

剩余部分不会出现在文档中,但是其他工具(比如 Sphinx)可以使用剩余部分。

from typing import Optional, Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[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 doesnt have tax, you can omit this
    - **tags**: a set of unique tag strings for this item
    f
    :param item: User input.
    """
    return item

andy

前端小白,在Web176教程网这个平台跟大家一起学习,加油!

Share
Published by
andy

Recent Posts

vue:页面注入js修改input值

一般会直接这样写: let z…

5 小时 ago

聊聊vue3中的defineProps

在Vue 3中,defineP…

1 周 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

2 周 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

4 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

1 月 ago