'How to write a FAST API function taking .csv file and making some preprocessing in pandas

I am trying to create an API function, that takes in .csv file (uploaded) and opens it as pandas DataFrame. Like that:

from fastapi import FastAPI
from fastapi import UploadFile, Query, Form
import pandas as pd

app = FastAPI()

@app.post("/check")
def foo(file: UploadFile):
    df = pd.read_csv(file.file)
    return len(df)

Then, I am invoking my API:

import requests

url = 'http://127.0.0.1:8000/check'
file = {'file': open('data/ny_pollution_events.csv', 'rb')}

resp = requests.post(url=url, files=file)
print(resp.json())

But I got such error: FileNotFoundError: [Errno 2] No such file or directory: 'ny_pollution_events.csv'

As far as I understand from doc pandas is able to read .csv file from file-like object, which file.file is supposed to be. But it seems, that here in read_csv() method pandas obtains name (not a file object itself) and tries to find it locally.

Am I doing something wrong? Can I somehow implement this logic?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source