跳转至

表单模型

AI 编程智能体

使用与你安装的版本对应的官方 FastAPI 技能。在你的项目目录中安装:

uvx library-skills

参阅 使用 AI 开发。

🌐 由 AI 与人类协作翻译

本翻译由人类引导的 AI 生成。🤝

可能存在误解原意或不够自然等问题。🤖

你可以通过帮助我们更好地引导 AI LLM来改进此翻译。

英文版本

你可以在 FastAPI 中使用 Pydantic 模型声明表单字段。

注意

要使用表单,首先安装 python-multipart。

将它添加到你的项目:

$ uv add python-multipart

注意

自 FastAPI 版本 0.113.0 起支持此功能。🤓

表单的 Pydantic 模型

你只需声明一个 Pydantic 模型,其中包含你希望接收的表单字段,然后将参数声明为 Form:

from typing import Annotated

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class FormData(BaseModel):
    username: str
    password: str


@app.post("/login/")
async def login(data: Annotated[FormData, Form()]):
    return data
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class FormData(BaseModel):
    username: str
    password: str


@app.post("/login/")
async def login(data: FormData = Form()):
    return data

FastAPI 将从请求中的表单数据中提取出每个字段的数据,并提供你定义的 Pydantic 模型。

对于 HTML 复选框,请将布尔字段的默认值声明为 False。

检查文档

你可以在文档 UI 中验证它,地址为 /docs:

禁止额外的表单字段

在某些特殊使用情况下(可能并不常见),你可能希望将表单字段限制为仅在 Pydantic 模型中声明过的字段,并禁止任何额外的字段。

注意

自 FastAPI 版本 0.114.0 起支持此功能。🤓

你可以使用 Pydantic 的模型配置来 forbid 任何 extra 字段:

from typing import Annotated

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class FormData(BaseModel):
    username: str
    password: str
    model_config = {"extra": "forbid"}


@app.post("/login/")
async def login(data: Annotated[FormData, Form()]):
    return data
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class FormData(BaseModel):
    username: str
    password: str
    model_config = {"extra": "forbid"}


@app.post("/login/")
async def login(data: FormData = Form()):
    return data

如果客户端尝试发送一些额外的数据,他们将收到错误响应。

例如,客户端尝试发送如下表单字段:

  • username: Rick
  • password: Portal Gun
  • extra: Mr. Poopybutthole

他们将收到一条错误响应,表明字段 extra 不被允许:

{
    "detail": [
        {
            "type": "extra_forbidden",
            "loc": ["body", "extra"],
            "msg": "Extra inputs are not permitted",
            "input": "Mr. Poopybutthole"
        }
    ]
}

组合表单模型

你可以将多个表单模型与单独的 Form 参数组合使用。

from typing import Annotated

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class Profile(BaseModel):
    name: str


class Preferences(BaseModel):
    tags: list[str] = []


@app.post("/profiles/")
async def create_profile(
    profile: Annotated[Profile, Form()],
    preferences: Annotated[Preferences, Form()],
    token: Annotated[str, Form()],
):
    return {"profile": profile, "preferences": preferences, "token": token}
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class Profile(BaseModel):
    name: str


class Preferences(BaseModel):
    tags: list[str] = []


@app.post("/profiles/")
async def create_profile(
    profile: Profile = Form(),
    preferences: Preferences = Form(),
    token: str = Form(),
):
    return {"profile": profile, "preferences": preferences, "token": token}

客户端将 name、tags 和 token 作为表单字段发送。每个模型独立验证表单字段。

每个模型的 extra 配置都适用于所有表单字段,包括在其他参数或依赖项中声明的字段和文件。使用 extra="forbid" 时,该模型之外的任何字段都会被拒绝。使用 extra="allow" 时,这些字段会作为模型的额外数据被包含进来。

如果多个声明使用相同的表单字段名,每个声明都会验证该字段的值。请为共享字段使用兼容的类型和约束,以便 OpenAPI schema 能一致地描述它们。

可选表单模型

使用 | None 并将默认值设为 None 来声明表单模型,即可使这组字段变为可选。

from typing import Annotated

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class Profile(BaseModel):
    name: str
    age: int


@app.post("/profiles/")
async def create_profile(
    token: Annotated[str, Form()],
    profile: Annotated[Profile | None, Form()] = None,
):
    return {"token": token, "profile": profile}
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class Profile(BaseModel):
    name: str
    age: int


@app.post("/profiles/")
async def create_profile(
    token: str = Form(),
    profile: Profile | None = Form(default=None),
):
    return {"token": token, "profile": profile}

如果既未发送 name 也未发送 age,则 profile 为 None。如果发送了其中任意一个字段,FastAPI 就会验证模型,并要求提供这两个字段。提交空值也算作提供了字段。

使用 | None 但不设置默认值时,该参数仍然是必填的。

额外字段遵循模型的 extra 配置。被忽略的额外字段不会使模型被视为已提供。

仅包含未勾选复选框的可选模型会被省略。发送 enabled=false 这样的值可以显式提供该模型。

可选的表单模型联合类型

你也可以使用可选的模型联合类型。

from typing import Annotated, Literal

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class Person(BaseModel):
    kind: Literal["person"]
    name: str


class Company(BaseModel):
    kind: Literal["company"]
    company_name: str


@app.post("/contacts/")
async def create_contact(
    contact: Annotated[Person | Company | None, Form(discriminator="kind")] = None,
):
    return contact
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from typing import Literal

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class Person(BaseModel):
    kind: Literal["person"]
    name: str


class Company(BaseModel):
    kind: Literal["company"]
    company_name: str


@app.post("/contacts/")
async def create_contact(
    contact: Person | Company | None = Form(default=None, discriminator="kind"),
):
    return contact

如果未发送任何表单字段,则 contact 为 None。发送 kind=person 和 name,或发送 kind=company 和 company_name。判别器会选择要验证的模型。

组合表单模型联合类型

你可以将联合类型与其他表单模型、单独的 Form 参数以及 File 参数组合使用。每个联合类型都会独立验证。

from typing import Annotated, Literal

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class Person(BaseModel):
    contact_type: Literal["person"]
    name: str


class Company(BaseModel):
    contact_type: Literal["company"]
    company_name: str


class Email(BaseModel):
    notification_type: Literal["email"]
    email: str


class SMS(BaseModel):
    notification_type: Literal["sms"]
    phone: str


@app.post("/contacts/")
async def create_contact(
    contact: Annotated[Person | Company, Form(discriminator="contact_type")],
    token: Annotated[str, Form()],
    notification: Annotated[
        Email | SMS | None, Form(discriminator="notification_type")
    ] = None,
):
    return {"contact": contact, "notification": notification, "token": token}
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from typing import Literal

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class Person(BaseModel):
    contact_type: Literal["person"]
    name: str


class Company(BaseModel):
    contact_type: Literal["company"]
    company_name: str


class Email(BaseModel):
    notification_type: Literal["email"]
    email: str


class SMS(BaseModel):
    notification_type: Literal["sms"]
    phone: str


@app.post("/contacts/")
async def create_contact(
    contact: Person | Company = Form(discriminator="contact_type"),
    token: str = Form(),
    notification: Email | SMS | None = Form(
        default=None, discriminator="notification_type"
    ),
):
    return {"contact": contact, "notification": notification, "token": token}

在同一个表单中发送所有字段。例如,发送 contact_type=person、name=Rick、notification_type=email、email=rick@example.com 和 token=secret。

省略通知字段即可让 notification 保持为 None。

表单模型与文件

你也可以将表单模型与文件参数组合使用。

from typing import Annotated

from fastapi import FastAPI, Form, UploadFile
from pydantic import BaseModel

app = FastAPI()


class Profile(BaseModel):
    name: str


@app.post("/profiles/")
async def create_profile(profile: Annotated[Profile, Form()], avatar: UploadFile):
    return {"profile": profile, "filename": avatar.filename}
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, File, Form, UploadFile
from pydantic import BaseModel

app = FastAPI()


class Profile(BaseModel):
    name: str


@app.post("/profiles/")
async def create_profile(profile: Profile = Form(), avatar: UploadFile = File()):
    return {"profile": profile, "filename": avatar.filename}

这里,客户端使用 multipart/form-data 发送 name 字段和 avatar 文件。

总结

你可以使用 Pydantic 模型在 FastAPI 中声明表单字段。😎