FastAPI query parameter using Pydantic model

Question:

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,

enter image description here

So, how can I use the Pydantic model to get the from query parameter in FastAPI?

Asked By: Anh Béo

||

Answers:

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}

enter image description here

Answered By: JPG
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.