2

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?

MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
Anh Béo
  • 23
  • 1
  • 3

1 Answers1

9

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

JPG
  • 82,442
  • 19
  • 127
  • 206
  • I have a question what if i don't specify ```student: Student = Depends()``` and just use ```def read_root(student: Student):```? Why do we need to use ```Depends``` here? – William Le Oct 05 '22 at 08:17
  • IIRC, you won't get the schema representation *"in this case"*. Checkout more about [`Depends(...)`](https://fastapi.tiangolo.com/tutorial/dependencies/) – JPG Oct 05 '22 at 18:02
  • how to add a description to the name and age field? – Amin Ba Apr 12 '23 at 16:56
  • question asked here https://stackoverflow.com/questions/75998227/fastapi-does-not-allow-pydantic-model-for-query-variable-how-to-fix-it – Amin Ba Apr 12 '23 at 17:18