2

I want to post a payload dict to my FastAPI endpoint that holds metadata like a file name and a bytesObject.

I accomplished to send the bytes object stand-alone using the File() Class of Fast API, but not in a dict structure.

For my FastAPI Endpoint I tried two approches.

Approach 1

@app.post("/process_file/", tags=["File porcessing"])
def process_excel_file(payload_dict: dict):
    file_name =  payload_dict["file_name"]
    pyld = payload_dict["payload"]
    data = FlatFileParser(file_name, pyld)
    logger.debug(f"Received: {data}")

    return {"Validator Response": data}

Approach 2

from fastapi import FastAPI, File, Request

@app.post("/process_file/", tags=["File porcessing"])
def process_excel_file(payload_dict: Request):
    
    file_name = payload_dict.body()["file_name"]
    payload = payload_dict.body()["payload"]
    data = FlatFileParser(file_name, payload)
    logger.debug(f"Received: {data}")
    data = strip_cols(data)
    data = clean_columns(data)
    data = prep_schema_cols(data)
    data = drop_same_name_columns(data)

    return {"Validator Response": data}

My Post request looks the following:

url = "http://localhost:8000/process_file/"
file_path = r'sample_file.xlsx'

with open(file_path, 'rb') as f:
    file = f.read()
      
    

payload = {
    "file_name": file_path,
    "payload": file
}

response = requests.post(url, data=payload)

But I receive following error for Approach 1:

Out[34]: b'{"detail":[{"loc":["body"],"msg":"value is not a valid dict","type":"type_error.dict"}]}'

And for Approach 2 i am unable to parse the body() in a way to retrieve the necessary data.

Any suggestions or advice?

Chris
  • 18,724
  • 6
  • 46
  • 80
Maeaex1
  • 703
  • 7
  • 36
  • Is it possible, that you want to send your payload as `application/json` in the body? In that case you would use `requests.post(url, json=payload)`. But in general, for receiving files, you probabl want the as `multipart/form-data` - FastAPI provides an `UploadFile` class to do that: https://fastapi.tiangolo.com/tutorial/request-files/ . – Simon Schoelly Jan 29 '23 at 16:58
  • Related answers can also be found [here](https://stackoverflow.com/a/70711176/17865804), as well as [here](https://stackoverflow.com/a/74015930/17865804) and [here](https://stackoverflow.com/a/70689003/17865804). – Chris Feb 13 '23 at 06:46

0 Answers0