表单模型¶
您可以使用 Pydantic 模型在 FastAPI 中声明表单字段。
Note
自 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
from fastapi import FastAPI, Form
from pydantic import BaseModel
from typing_extensions import Annotated
app = FastAPI()
class FormData(BaseModel):
username: str
password: str
@app.post("/login/")
async def login(data: Annotated[FormData, Form()]):
return data
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 模型。
检查文档¶
您可以在文档 UI 中验证它,地址为 /docs
:
禁止额外的表单字段¶
在某些特殊使用情况下(可能并不常见),您可能希望将表单字段限制为仅在 Pydantic 模型中声明过的字段,并禁止任何额外的字段。
Note
自 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
from fastapi import FastAPI, Form
from pydantic import BaseModel
from typing_extensions import Annotated
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
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"
}
]
}
总结¶
您可以使用 Pydantic 模型在 FastAPI 中声明表单字段。😎