17

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?

0

3 Answers 3

27

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?)

Sign up to request clarification or add additional context in comments.

Comments

1

Remove the 'foo.txt' from your request.

It should look like

files = {'file': open('./foo.txt', 'rb')}

1 Comment

the ('foo.txt', ... is to add a file-name to the post-request: requests.readthedocs.io/en/master/user/quickstart I tried it without, and get same result.
0

based on the documentation: https://requests.readthedocs.io/en/master/user/quickstart/

the following code should work (worked for me):

image = {'file':("your_file_name.extension", open("your_file_name.extension", 'rb'))}

resp = requests.post(url="your url", files=image)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.