使用 Pydantic 模型的 FastAPI 查询参数

Anh*_*Béo 3 python pydantic fastapi

我有一个 Pydantic 模型如下

class Student(BaseModel):
    name:str
    age:int
Run Code Online (Sandbox Code Playgroud)

通过此设置,我希望获得如下 OpenAPI 架构:

在此输入图像描述

那么,如何使用 Pydantic 模型来获取 FastAPI 中的 from 查询参数呢?

JPG*_*JPG 11

你可以做这样的事情,


from fastapi import FastAPI, Depends

from pydantic import BaseModel

app = FastAPI()


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


@app.get("/")
def read_root(student: Student = Depends()):
    return {"name": student.name, "age": student.age}
Run Code Online (Sandbox Code Playgroud)

另请注意,查询参数通常是“可选”字段,如果您希望将它们设为可选,请使用Optional类型提示,

from fastapi import FastAPI, Depends
from typing import Optional
from pydantic import BaseModel

app = FastAPI()


class Student(BaseModel):
    name: str
    age: Optional[int]


@app.get("/")
def read_root(student: Student = Depends()):
    return {"name": student.name, "age": student.age}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述