网页
综合
更新时间 2026-11-17 03:11:35
Body - Fields - FastAPI
自动蜘蛛
fastapi.tiangolo.com
正文约 2083 字
Use the official FastAPI skill for your installed version. Install it from your project directory:
See Develop with AI.
The same way you can declare additional validation and metadata in path operation function parameters with Query, Path and Body, you can declare validation and metadata inside of Pydantic models using Pydantic's Field.
First, you have to import it:
Prefer to use the Annotated version if possible.
Notice that Field is imported directly from pydantic, not from fastapi as are all the rest (Query, Path, Body, etc).
You can then use Field with model attributes:
Prefer to use the Annotated version if possible.
Field works the same way as Query, Path and Body, it has all the same parameters, etc.
Actually, Query, Path and others you'll see next create objects of subclasses of a common Param class, which is itself a subclass of Pydantic's FieldInfo class.
And Pydantic's Field returns an instance of FieldInfo as well.
Body also returns objects of a subclass of FieldInfo directly. And there are others you will see later that are subclasses of the Body class.
Remember that when you import Query, Path, and others from fastapi, those are actually functions that return special classes.
Notice how each model's attribute with a type, default value and Field has the same structure as a path operation function's parameter, with Field instead of Path, Query and Body.
You can declare extra information with json_schema_extra in Field, Query, Body, etc. And it will be included in the generated JSON Schema.
You will learn more about adding extra information later in the docs, when learning to declare examples.
Extra keys passed in json_schema_extra will also be present in the resulting OpenAPI schema for your application. As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example the OpenAPI validator, may not work with your generated schema.
You can use Pydantic's Field to declare extra validations and metadata for model attributes.
You can also use json_schema_extra to pass additional JSON Schema metadata.
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。