Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI query parameter using Pydantic model

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?

like image 358
Anh Béo Avatar asked Oct 26 '25 07:10

Anh Béo


1 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

like image 176
JPG Avatar answered Oct 28 '25 19:10

JPG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!