1

I am trying to return a Pandas DataFrame using FastAPI.

My response model looks something like:

class Response(BaseModel):
    df: Dict
    date: str

I then have my function run, which creates a Pandas data frame, and a date, which I am currently trying to return via:

return Response(
        df=df.to_dict(orient="records"),
        date=f"{df.index.mean():%Y-%m-%d}",
    )

However, when doing so I get the error:

pydantic.error_wrappers.ValidationError: 2 validation errors for Response
df
  value is not a valid dict (type=type_error.dict)

I've tried changing the response model for df to be str and json, and wrapping the response with json.dumps and jsonable_encoder, but it never truly worked. If I give the df a str type in the Response model it actually somewhat worked. However, the formatting was not good at all.

I don't know if the easiest way is somewhat converting that "stringy" version of the df to something useful when I get it to the front-end, or if I'm just missing something simple to fix it from the back-end?

Chris
  • 18,724
  • 6
  • 46
  • 80
Denver Dang
  • 2,433
  • 3
  • 38
  • 68
  • Please also have a look at related answers [here](https://stackoverflow.com/a/73580096/17865804), as well as [here](https://stackoverflow.com/a/73694164/17865804) and [here](https://stackoverflow.com/a/74588435/17865804) – Chris Apr 26 '23 at 05:00

1 Answers1

2

Looking at the Pandas documentation, df.to_dict(orient="records" actually returns a list [{column: value}, … , {column: value}]. So changing your model to

from typing import Any

from pydantic import BaseModel

class Response(BaseModel):
    df: list[dict[str, Any]]
    date: str

should do the trick.

M.O.
  • 1,712
  • 1
  • 6
  • 18