Categories
fastapi python python-3.x python-requests

Send and receive file using Python: FastAPI and requests

I’m trying to upload a file to a FastAPI server using requests.

I’ve boiled the problem down to its simplest components.

The client using requests:

import requests
files = {'file': ('foo.txt', open('./foo.txt', 'rb'))}
response = requests.post('http://127.0.0.1:8000/file', files=files)
print(response)
print(response.json())

The server using fastapi:

from fastapi import FastAPI, File, UploadFile
import uvicorn
app = FastAPI()
@app.post('/file')
def _file_upload(my_file: UploadFile = File(...)):
print(my_file)
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, log_level="debug")

Packages installed:

  • fastapi
  • python-multipart
  • uvicorn
  • requests

Client Output:
<Response [422]>
{‘detail’: [{‘loc’: [‘query’, ‘my_file’], ‘msg’: ‘field required’, ‘type’: ‘value_error.missing’}]}

Server Output:
INFO: 127.0.0.1:37520 – “POST /file HTTP/1.1” 422 Unprocessable Entity

What am I missing here?

FastAPI expecting the file in the my_file field and you are sending it to the file field.

it should be as

import requests
url = "http://127.0.0.1:8000/file"
files = {'my_file': open('README.md', 'rb')}
res = requests.post(url, files=files)

Also, you don’t need a tuple to manage the upload file (we’re dealing with a simple upload, right?)