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?