Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

hey I wanna make fastapi server that reads and sends data from xlsx file

  1. User

    hey I wanna make fastapi server that reads and sends data from xlsx file

  2. Assistant

    Sure! Here's an example of a FastAPI server that can read data from an xlsx file and send it as a response:

    from fastapi import FastAPI
    import pandas as pd
    
    app = FastAPI()
    
    @app.get("/data")
    async def get_data():
        try:
            df = pd.read_excel("data.xlsx")  # Replace "data.xlsx" with your actual file path
            return df.to_json(orient="records")
        except Exception as e:
            return {"error": str(e)}
    
    if __name__ == "__main__":
        import uvicorn
    
        uvicorn.run(app, host="0.0.0.0", port=8000)
    

    In this example, we're using the pandas library to read the xlsx file and convert it to a JSON format. The get_data endpoint will return the data as JSON. Replace "data.xlsx" with the actual file path where your xlsx file is located.

    To run the server, save the code to a Python file (e.g., main.py) and execute the following command in your terminal:

    uvicorn main:app --reload
    

    This will start the FastAPI server on http://localhost:8000/data. You can access the data by sending a GET request to that URL.

    Note: Make sure you have the necessary dependencies installed. You can use pip install fastapi pandas uvicorn to install them.

  3. User

    I got this error ValueError: Out of range float values are not JSON compliant

  4. Assistant

    The error "ValueError: Out of range float values are not JSON compliant" is raised when there is a float value in your Excel file that exceeds the range of JSON number representation.

    To fix this issue, you can convert the float values to strings before returning the JSON response. Here's an updated version of the code that handles this conversion:

    from fastapi import FastAPI
    import pandas as pd
    
    app = FastAPI()
    
    @app.get("/data")
    async def get_data():
        try:
            df = pd.read_excel("data.xlsx")  # Replace "data.xlsx" with your actual file path
    
            # Convert float columns to string
            for column in df.select_dtypes(include="float"):
                df[column] = df[column].astype(str)
    
            return df.to_json(orient="records")
        except Exception as e:
            return {"error": str(e)}
    
    if __name__ == "__main__":
        import uvicorn
    
        uvicorn.run(app, host="0.0.0.0", port=8000)
    

    Now, the float columns will be converted to strings, allowing them to be JSON compliant.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.