With the DataFrame.to_dict() method, not all Pandas datatypes are serializable by the json package:
df = pd.DataFrame({
"TrainID": ["T001", "T002", "T003"],
"Route": ["Amsterdam - Utrecht", "Rotterdam - Den Haag", "Eindhoven - Tilburg"],
"DepartureTime": [
pd.Timestamp("2022-03-09 08:00:00"),
pd.Timestamp("2022-03-09 09:15:00"),
pd.Timestamp("2022-03-09 10:30:00"),
],
"ArrivalTime": [
pd.Timestamp("2022-03-09 09:00:00"),
pd.Timestamp("2022-03-09 09:45:00"),
pd.Timestamp("2022-03-09 11:00:00"),
],
"Status": ["On Time", "Delayed", "Cancelled"],
})
json.dumps(df.to_dict(orient="records"))
TypeError: Object of type Timestamp is not JSON serializable
I have a DataFrameJSONResponse class to use the pandas.DataFrame.to_json instead of the json.dumps:
from fastapi.responses import Response
from typing import Any
class DataFrameJSONResponse(Response):
media_type = "application/json"
def render(self, content: Any) -> bytes:
return content.to_json(orient="records", date_format='iso').encode("utf-8")
@app.get("/test", response_class=DataFrameJSONResponse)
async def test_dataframe():
df = pd.DataFrame(
{
"TrainID": ["T001", "T002", "T003"],
"Route": [
"Amsterdam - Utrecht",
"Rotterdam - Den Haag",
"Eindhoven - Tilburg",
],
"DepartureTime": [
pd.Timestamp("2022-03-09 08:00:00"),
pd.Timestamp("2022-03-09 09:15:00"),
pd.Timestamp("2022-03-09 10:30:00"),
],
"ArrivalTime": [
pd.Timestamp("2022-03-09 09:00:00"),
pd.Timestamp("2022-03-09 09:45:00"),
pd.Timestamp("2022-03-09 11:00:00"),
],
"Status": ["On Time", "Delayed", "Cancelled"],
}
)
return DataFrameJSONResponse(df)
render- what do you mean? In general, FastAPI returns data as JSON. If you want to have a different response format, you can use one of the built-in custom response formats, or create your own: fastapi.tiangolo.com/advanced/custom-responseto_jsona JSON string is returned directly. You can then pair this withreturn Response(content=json_str, media_type="application/json")to return the string directly from FastAPI with a JSON header. Would that work? (you can also give a File-like object and get output written to that, so something likeStringIOshould work as well)