Como enviar Pandas Dataframes para ser consumido como json em api e disponibilizado como dado em endpoint How to send Pandas Dataframes to be consumed as json in api and available as data in endpoint.

Overview:

I have a front end model developed in reaction with BI dashboards.
I need to send the dataframes treated in pandas as json in the api to be consumed by the frontend

Structure

1st- I use sqlalchemy to connect to the firebird database

2nd- I perform a sql query with pd.readsql() to generate our dataframe and do the other treatments with pandas

What I need

These data treated as dataframes need to be sent as json in an api that will be consumed by a react frontend structure

End part

I thank you for all your help in advance.
I’m a beginner with the framework and I’m stuck in it.

Convert the DataFrame to JSON and return it as a JsonResponse in your view.
See pandas.DataFrame.to_json — pandas 1.5.2 documentation

1 Like

I already know how to convert the dataframe to json but I don’t know how to send it in the django api

I don’t know what you’re trying to refer to by making a reference to “the Django API”.

A Django view receives a request and returns a response. The contents of that response are determined entirely by the view associated with that request.

In this case, you would want your response to be an instance of a JsonResponse.

2 Likes

Thanks, I’m taking a look at the documentation and it seems to solve my problem :slight_smile:

1 Like

Hi, you have to use a to_dict; not a to_json.
The to_json returns a string.
Suposse your dataframe es df, then do this
JSonResponse(df.to_dict())
Because JSonResponse needs a dictionary to serialize to a Json.

1 Like