简体   繁体   English

使用 Pydantic model 的 FastAPI 查询参数

[英]FastAPI query parameter using Pydantic model

I have a Pydantic model as below我有一个 Pydantic model 如下

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

With this setup, I wish to get the OpenAPI schema as following,通过这个设置,我希望得到如下的 OpenAPI 模式,

在此处输入图像描述

So, how can I use the Pydantic model to get the from query parameter in FastAPI?那么,如何使用 Pydantic model 在 FastAPI 中获取 from 查询参数?

You can do something like this,你可以做这样的事情,


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}

Also, note that the query parameters are usually " optional " fields and if you wish to make them optional, use Optional type hint as,另外,请注意查询参数通常是“可选”字段,如果您希望将它们设为可选,请使用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}

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Pydantic model (FastAPI) 在 swagger 文档中设置查询参数的描述 - Set description for query parameter in swagger doc using Pydantic model (FastAPI) 如何在 pydantic model for fastapi 中允许 List 作为查询参数而不是 requestbody - How to allow List as query params instead of requestbody in pydantic model for fastapi pydantic 模型返回 empy (fastapi) - pydantic model returns empy (fastapi) 如何使用字段别名而不是 FastAPI 中的名称返回 Pydantic 模型? - How to return Pydantic model using Field aliases instead of names in FastAPI? 如何使用 FastAPI 从 Pydantic model 中排除可选的未设置值? - How to exclude Optional unset values from a Pydantic model using FastAPI? 使用 pydantic @validator 装饰器捕获错误以进行 fastapi 输入查询 - catch errors using pydantic @validator decorator for fastapi input query FastApi 中使用 Pydantic 的动力体 - Dynamical body in FastApi using Pydantic 如何在 FastAPI 中使用带有表单数据的 Pydantic model? - How to use a Pydantic model with Form data in FastAPI? Python / pydantic / FastAPI - 将此数据结构描述为模式模型? - Python / pydantic / FastAPI - describe this datastructure as a Schema Model? 我们可以使用 FastAPI 直接在 model.predict() 内部使用 Pydantic 模型(Basemodel)吗?如果不能,为什么? - Can we use Pydantic models (Basemodel) directly inside model.predict() using FastAPI, and if not ,why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM