2

Intro:

In FastAPI, when the input of a POST request is a Pydantic model (like in this example) The automatic docs generated by Fastapi contains a schema of that object ($ref) (as shown here).

Question:

Although the input of a GET request cannot be a Pydantic model (because Pydantic objects need to be sent inside the body section of the request, and get requests does not have a body - link,

Q1. Is it possible to use a Pydantic model for the auto generated docs? Edit - Yes: the answer is in Chris's response here

Q2. Is it possible to do that with nested Pydantic objects (to flatten the fields)? Something like this:

class AnotherBase(BaseModel):
    c: str
    d: str

class MyBase(BaseModel):
    a: str = Query()
    b: AnotherBase = Query()

@router.get("/myget")
def my_func(arg: MyBase = Depends()) -> MyBase:
    return MyBase(a="1", b="2")

What I have tried:

  1. To use a pydantic model as the input of a get request - the result was that it is not possible because get requests does not have a body

  2. I have tried following this thread but still, using Depends, some of the input parameters need to be sent inside the body - so I receive this error from Fastapi "TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body."

  3. I have tried following Cris's answer1 but the inner object (b: AnotherBase) is for some reason in the body section (which does not exists)

Guy
  • 21
  • 3
  • Does this answer your question? [OpenAPI is missing schemas for some of the Pydantic models in FastAPI app](https://stackoverflow.com/questions/71941127/openapi-is-missing-schemas-for-some-of-the-pydantic-models-in-fastapi-app) – Chris Mar 19 '23 at 15:55
  • Please take a look at related posts [here](https://stackoverflow.com/a/73067473/17865804), as well as [here](https://stackoverflow.com/a/70845425/17865804) and [here](https://stackoverflow.com/a/70642064/17865804) – Chris Mar 19 '23 at 15:56
  • Please provide enough code so others can better understand or reproduce the problem. – Community Mar 19 '23 at 15:59

0 Answers0