4

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?

1 Answer 1

12

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

Sign up to request clarification or add additional context in comments.

4 Comments

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?
IIRC, you won't get the schema representation "in this case". Checkout more about Depends(...)
how to add a description to the name and age field?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.