FastAPI开发文档教程-模式的额外信息-例子

admin 2026-01-10 10:52:27 编程 来源:ZONE.CI 全球网 0 阅读模式
  • Pydantic schema_extra
  • Field 的附加参数
  • Body 额外参数
  • 文档 UI 中的例子
  • 技术细节
  • 其他信息

    您可以在JSON模式中定义额外的信息。

    一个常见的用例是添加一个将在文档中显示的example

    有几种方法可以声明额外的 JSON 模式信息。

    Pydantic schema_extra

    您可以使用 Configschema_extra 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述:

    Python 3.10+ Python 3.8+

    1. from fastapi import FastAPI
    2. from pydantic import BaseModel
    3. app = FastAPI()
    4. class Item(BaseModel):
    5. name: str
    6. description: str | None = None
    7. price: float
    8. tax: float | None = None
    9. model_config = { "json_schema_extra": { "examples": [ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, } ]
    10. }
    11. }
    12. @app.put("/items/{item_id}")
    13. async def update_item(item_id: int, item: Item):
    14. results = {"item_id": item_id, "item": item}
    15. return results`
    1. from typing import Union
    2. from fastapi import FastAPI
    3. from pydantic import BaseModel
    4. app = FastAPI()
    5. class Item(BaseModel):
    6. name: str
    7. description: Union[str, None] = None
    8. price: float
    9. tax: Union[float, None] = None
    10. model_config = { "json_schema_extra": { "examples": [ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, } ]
    11. }
    12. }
    13. @app.put("/items/{item_id}")
    14. async def update_item(item_id: int, item: Item):
    15. results = {"item_id": item_id, "item": item}
    16. return results`

    这些额外的信息将按原样添加到输出的JSON模式中。

    Field 的附加参数

    Field, Path, Query, Body 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 example:

    Python 3.10+Python 3.8+

    1. from fastapi import FastAPI
    2. from pydantic import BaseModel, Field
    3. app = FastAPI()
    4. class Item(BaseModel):
    5. name: str = Field(examples=["Foo"]) description: str | None = Field(default=None, examples=["A very nice Item"]) price: float = Field(examples=[35.4]) tax: float | None = Field(default=None, examples=[3.2])
    6. @app.put("/items/{item_id}")
    7. async def update_item(item_id: int, item: Item):
    8. results = {"item_id": item_id, "item": item}
    9. return results`
    1. from typing import Union
    2. from fastapi import FastAPI
    3. from pydantic import BaseModel, Field
    4. app = FastAPI()
    5. class Item(BaseModel):
    6. name: str = Field(examples=["Foo"]) description: Union[str, None] = Field(default=None, examples=["A very nice Item"]) price: float = Field(examples=[35.4]) tax: Union[float, None] = Field(default=None, examples=[3.2])
    7. @app.put("/items/{item_id}")
    8. async def update_item(item_id: int, item: Item):
    9. results = {"item_id": item_id, "item": item}
    10. return results`

    Warning

    请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。

    Body 额外参数

    你可以通过传递额外信息给 Field 同样的方式操作Path, Query, Body等。

    比如,你可以将请求体的一个 example 传递给 Body:

    Python 3.10+Python 3.9+Python 3.8+Python 3.10+ non-AnnotatedPython 3.8+ non-Annotated

    1. from typing import Annotated
    2. from fastapi import Body, FastAPI
    3. from pydantic import BaseModel
    4. app = FastAPI()
    5. class Item(BaseModel):
    6. name: str
    7. description: str | None = None
    8. price: float
    9. tax: float | None = None
    10. @app.put("/items/{item_id}")
    11. async def update_item(
    12. item_id: int,
    13. item: Annotated[
    14. Item,
    15. Body(
    16. examples=[ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }
    17. ],
    18. ),
    19. ],
    20. ):
    21. results = {"item_id": item_id, "item": item}
    22. return results`
    1. from typing import Annotated, Union
    2. from fastapi import Body, FastAPI
    3. from pydantic import BaseModel
    4. app = FastAPI()
    5. class Item(BaseModel):
    6. name: str
    7. description: Union[str, None] = None
    8. price: float
    9. tax: Union[float, None] = None
    10. @app.put("/items/{item_id}")
    11. async def update_item(
    12. item_id: int,
    13. item: Annotated[
    14. Item,
    15. Body(
    16. examples=[ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }
    17. ],
    18. ),
    19. ],
    20. ):
    21. results = {"item_id": item_id, "item": item}
    22. return results`
    1. from typing import Union
    2. from fastapi import Body, FastAPI
    3. from pydantic import BaseModel
    4. from typing_extensions import Annotated
    5. app = FastAPI()
    6. class Item(BaseModel):
    7. name: str
    8. description: Union[str, None] = None
    9. price: float
    10. tax: Union[float, None] = None
    11. @app.put("/items/{item_id}")
    12. async def update_item(
    13. item_id: int,
    14. item: Annotated[
    15. Item,
    16. Body(
    17. examples=[ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }
    18. ],
    19. ),
    20. ],
    21. ):
    22. results = {"item_id": item_id, "item": item}
    23. return results`

    Tip

    尽可能选择使用 Annotated 的版本。

    1. from fastapi import Body, FastAPI
    2. from pydantic import BaseModel
    3. app = FastAPI()
    4. class Item(BaseModel):
    5. name: str
    6. description: str | None = None
    7. price: float
    8. tax: float | None = None
    9. @app.put("/items/{item_id}")
    10. async def update_item(
    11. item_id: int,
    12. item: Item = Body(
    13. examples=[ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }
    14. ],
    15. ),
    16. ):
    17. results = {"item_id": item_id, "item": item}
    18. return results`

    Tip

    尽可能选择使用 Annotated 的版本。

    1. from typing import Union
    2. from fastapi import Body, FastAPI
    3. from pydantic import BaseModel
    4. app = FastAPI()
    5. class Item(BaseModel):
    6. name: str
    7. description: Union[str, None] = None
    8. price: float
    9. tax: Union[float, None] = None
    10. @app.put("/items/{item_id}")
    11. async def update_item(
    12. item_id: int,
    13. item: Item = Body(
    14. examples=[ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }
    15. ],
    16. ),
    17. ):
    18. results = {"item_id": item_id, "item": item}
    19. return results`

    文档 UI 中的例子

    使用上面的任何方法,它在 /docs 中看起来都是这样的:

    模式的额外信息 - 例子 - 图1

    技术细节

    关于 exampleexamples

    JSON Schema在最新的一个版本中定义了一个字段 examples ,但是 OpenAPI 基于之前的一个旧版JSON Schema,并没有 examples.

    所以 OpenAPI为了相似的目的定义了自己的 example (使用 example, 而不是 examples), 这也是文档 UI 所使用的 (使用 Swagger UI).

    所以,虽然 example 不是JSON Schema的一部分,但它是OpenAPI的一部分,这将被文档UI使用。

    其他信息

    同样的方法,你可以添加你自己的额外信息,这些信息将被添加到每个模型的JSON模式中,例如定制前端用户界面,等等。

    FastAPI开发文档教程-额外数据类型 编程

    FastAPI开发文档教程-额外数据类型

    额外数据类型其他数据类型例子 FastAPI学习教程 - 用户指南 额外数据类型到目前为止,您一直在使用常见的数据类型,如:intfloatstrbool 但是您也可以使用更复杂的数据类型。 您仍然会
    FastAPI开发文档教程-请求体-嵌套模型 编程

    FastAPI开发文档教程-请求体-嵌套模型

    List 字段具有子类型的 List 字段从 typing 导入 List声明具有子类型的 ListSet 类型嵌套模型定义子模型将子模型用作类型特殊的类型和校验带有一组子模型的属性深度嵌套模型纯列表
    评论:0   参与:  0