1

I want to know how to use requests when use two image files as inputs.

server

from fastapi import FastAPI, File

app = FastAPI()

@app.post("/images")
def images(img1: bytes = File(...), img2: bytes = File(...)):
    # **do something**
    return {"message": "OK"}

I succeded to post with curl command like below,

curl -X POST \
  'http://127.0.0.1:8000/images' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'img1=@<IMG1_FILE>;type=image/<EXTENSION>' \
  -F 'img2=@<IMG2_FILE>;type=image/<EXTENSION>'

but I failed with scripts using requests like below, and got 400 BAD Request

import requests

url = "http://127.0.0.1:8000/images"
headers = {"accept": "application/json", "content-type": "multipart/form-data"}
files = {"img1": open("img1_path.jpg", "rb"), "img2": open("img2_path.jpg", "rb")}

response = requests.post(url, headres=headers, files=files)

can anyone help me??

Chris
  • 18,724
  • 6
  • 46
  • 80
ktro2828
  • 11
  • 4

1 Answers1

0

Firstly ensure you installed python-multipart package.

Then Remove the content-type from request headers like below:

import requests

url = "http://127.0.0.1:8000/images"
headers = {"accept": "application/json"}
files = {"img1": open("img1_path.jpg", "rb"), "img2": open("img2_path.jpg", "rb")}

response = requests.post(url, headers=heaers, files=files)
ahmadgh74
  • 801
  • 6
  • 10