1

I am trying to get files as CSV or XLSX from the user and convert it to YAML. I have already made python scripts to convert the files from CSV to YAML and XLSX to YAML locally but I can't do it by taking the file from user. how can i read the file which gets uploaded?

@app.post("/cqa/uploadFile")
def create_upload_file(file: UploadFile = File(...)):
    if file.filename.endswith('.csv') or file.filename.endswith('.xlsx'):
        toYAML(file)
        return {"filename": file.filename}
    else:
         raise HTTPException( status_code=status.HTTP_405_METHOD_NOT_ALLOWED)


 def toYAML(file):
     if file.filename.endswith('.csv'):
         convert_yaml(codecs.iterdecode(file.file,'utf-8'))
     else:
         xlsx_to_csv(file)
         convert_yaml("xlsxCSV.csv")

This is how I am converting to XLSX to CSV:

def xlsx_to_csv(file):
    data_xls = pd.read_excel(file, index_col=None)
    data_xls.to_csv("xlsxCSV.csv", encoding='utf-8', index=False)

This is how I convert CSV to YAML:

def convert_yaml(file):
    file=open(file)

    x = csv.reader(file)
    file_arr=[]
    for  r in x :
        file_arr.append(r)
Chris
  • 18,724
  • 6
  • 46
  • 80
hsinha22
  • 11
  • 1
  • 3
  • Related answers on how to upload a CSV file in FastAPI and then read/convert it can be found [here](https://stackoverflow.com/a/70655118/17865804) and [here](https://stackoverflow.com/a/74588435/17865804) as well. – Chris Apr 08 '23 at 16:47

2 Answers2

0

Fastapi is an API, so don't expect users to be able to submit files via a nice UI.

The API is correct. I don't see any problem.

Since I have no clue what the upload part looks like (i.e. interface), I can't advise here, but if you are uploading a file via javascript, then you should use a FormData and call the entry to the file the same way it is specified in the route's parameter (i.e. file).

You can check my other answer on a really similar problem here. In this reply I only summarized what've written in the answer. Hope it's what you're looking for.

How to send a file (docx, doc, pdf or json) to fastapi and predict on it without UI (i.e., HTML)?

lsabi
  • 3,641
  • 1
  • 14
  • 26
0

**

def create_upload_file(file: UploadFile = File(...)):

**

IMO, the only issue here might be the name "file" in query params. Same name should be given in the form data input name(in frontend file upload form).

to keep it simple, input name in below body should match the query param of upload_file in api

<body>
<form action="/files/" enctype="multipart/form-data" method="post">
<input name="file" type="file" multipart>
<input type="submit">
</form>
</body>
Krish Na
  • 91
  • 1
  • 2