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?

1
  • Please also have a look at related answers here, as well as here and here Commented Apr 26, 2023 at 5:00

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.