Reputation: 43
I have a Pydantic model as below
class Student(BaseModel):
name:str
age:int
With this setup, I wish to get the OpenAPI schema as following,
So, how can I use the Pydantic model to get the from query parameter in FastAPI?
Upvotes: 4
Views: 7873
Reputation: 88639
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,
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}
Upvotes: 12