Home > Net >  How to properly return dataframe as JSON using FastAPI?
How to properly return dataframe as JSON using FastAPI?

Time:01-31

I created an API using FastAPI that returned a JSON. First, I used to turn the Dataframe to JSON using the Pandas .to_json() method, which allowed me to choose the correct "orient" parameter. This saved a .json file and then opened it to make fastAPI return it as it follows:

DATA2.to_json("json_records.json",orient="records")

with open('json_records.json', 'r') as f:
data = json.load(f)

return(data)

This worked perfectly, but i was told that my script shouldn't save any files since this script would be running on my company's server, so I had to directly turn the dataframe into JSON and return it. I tried doing this:

data = DATA2.to_json(orient="records")

return(data)

But now the API's output is a JSON full of "\". I guess there is a problem with the parsing but i can't really find a way to do it properly. The output now looks like this:

"[{\"ExtraccionHora\":\"12:53:00\",\"MiembroCompensadorCodigo\":117,\"MiembroCompensadorDescripcion\":\"OMEGA CAPITAL S.A.\",\"CuentaCompensacionCodigo\":\"1143517\",\"CuentaNeteoCodigo\":\"160234117\",\"CuentaNeteoDescripcion\":\"UNION FERRO SRA A\",\"ActivoDescripcion\":\"X17F3\",\"ActivoID\":8,\"FinalidadID\":2,\"FinalidadDescripcion\":\"Margenes\",\"Cantidad\":11441952,\"Monto\":-16924935.3999999985,\"Saldo\":-11379200.0,\"IngresosVerificados\":11538288.0,\"IngresosNoVerificado\":0.0,\"MargenDelDia\":0.0,\"SaldoConsolidadoFinal\":-16765847.3999999985,\"CuentaCompensacionCodigoPropia\":\"80500\",\"SaldoCuentaPropia\":-7411284.3200000003,\"Resultado\":\"0\",\"MiembroCompensadorID\":859,\"CuentaCompensacionID\":15161,\"CuentaNeteoID\":7315285}.....

What would be a proper way of turning my dataframe into a JSON using the "records" orient, and then returning it as the FastAPI output? Thanks!

CodePudding user response:

update: i changed the to_json() method to to_dict() using the same parameters and seems to work... don't know if its correct.

    data = DATA2.to_dict(orient="records")

return(data)

CodePudding user response:

FastAPI provides a convenient way to return data as JSON using the pandas library.

Here's an example:

from fastapi import FastAPI
import pandas as pd

app = FastAPI()

@app.get("/data")
async def get_data():
    df = pd.DataFrame({"column_1": [1, 2, 3], "column_2": [4, 5, 6]})
    return df.to_dict()
  • Related