[英]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.