0

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"}
0

1 Answer 1

1

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")
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But in your code, you are not requesting the user for the input. It needs to be an input and that has to be printed as a dictionary or Json in the custom route.
I must not be understanding what you are trying to do. Why would you get initial input when the script is run if the user can define the id when invoking the route? Are you trying to log the value the user is querying?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.