路径操作的高级配置

OpenAPI 的 operationId

Warning

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

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

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

  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. @app.get("/items/", operation_id="some_specific_id_you_define")
  4. async def read_items():
  5. return [{"item_id": "Foo"}]

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

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

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

  1. from fastapi import FastAPI
  2. from fastapi.routing import APIRoute
  3. app = FastAPI()
  4. @app.get("/items/")
  5. async def read_items():
  6. return [{"item_id": "Foo"}]
  7. def use_route_names_as_operation_ids(app: FastAPI) -> None:
  8. """
  9. Simplify operation IDs so that generated API clients have simpler function
  10. names.
  11. Should be called only after all routes have been added.
  12. """
  13. for route in app.routes:
  14. if isinstance(route, APIRoute):
  15. route.operation_id = route.name # in this case, 'read_items'
  16. use_route_names_as_operation_ids(app)

Tip

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

Warning

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

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

从 OpenAPI 中排除

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

  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. @app.get("/items/", include_in_schema=False)
  4. async def read_items():
  5. return [{"item_id": "Foo"}]

docstring 的高级描述

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

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

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

  1. from typing import Optional, Set
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. description: Optional[str] = None
  8. price: float
  9. tax: Optional[float] = None
  10. tags: Set[str] = []
  11. @app.post("/items/", response_model=Item, summary="Create an item")
  12. async def create_item(item: Item):
  13. """
  14. Create an item with all the information:
  15. - **name**: each item must have a name
  16. - **description**: a long description
  17. - **price**: required
  18. - **tax**: if the item doesn't have tax, you can omit this
  19. - **tags**: a set of unique tag strings for this item
  20. \f
  21. :param item: User input.
  22. """
  23. return item