Home > database >  How do I return the output in dictionary or JSON format in FAST API?
How do I return the output in dictionary or JSON format in FAST API?

Time:10-31

I have been asked to upload a CSV File which contains the details of students and request the user to input the student ID (In this case the Index) and print the respective row showing the details of that particular student. The output prints fine inside the compiler, both in dictionary and JSON format. But when defining a custom route (i.e.. /student/{data_id}) and requesting the route to return the JSON or dictionary format of the student id in the input. I get this message in the URL:

{"detail":[{"loc":["query","data_json_output"],"msg":"field required","type":"value_error.missing"}]}

Here is the code.

import requests
import json
import pandas as pd
from fastapi import FastAPI
import uvicorn

#Reading the CSV file
df_data_csv = pd.read_csv("data.csv")
data_dict = df_data_csv.to_dict(orient='index')

#Input the student ID
data_id =int(input("Enter the id of the student: "))
#Converting to Dictionary (Just trying)
data_dict_output = (data_dict[data_id])
#Converting to JSON
data_json_output =  json.dumps(data_dict_output)
print(f"The JSON format is {data_json_output}")

app = FastAPI()

#The Root. Please ignore this line
@app.get("/")
def read_root():
    return {"Test"}

#Custom route (Which is where I am facing the issue)
@app.get("/student/{data_id}")
def read_item(data_json_output:str):
#Returning the input data in JSON format
    return data_json_output

uvicorn.run(app,host="0.0.0.0",port="8080")

When entering the custom route I need to get the data I requested in the code. For example, If the input was 0, the output should be

{"Name": "A", "Height": 4, "Weight": 60, "Grade": "J"}

CodePudding user response:

Could you do something like this?

import pandas as pd
from fastapi import FastAPI
import uvicorn

# Reading the CSV file
df_data_csv = pd.read_csv('data.csv')
data_dict = df_data_csv.to_dict(orient='index')

app = FastAPI()


@app.get("/")
def read_root():
    return {"Test"}


@app.get("/student/{data_id}")
def read_item(data_id: int):
    return data_dict[data_id]


uvicorn.run(app, host="0.0.0.0", port="8080")
  • Related