Anh Béo
Anh Béo

Reputation: 43

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?

Upvotes: 4

Views: 7873

Answers (1)

JPG
JPG

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}

enter image description here

Upvotes: 12

Related Questions