Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST multipart/form-data in Python with requests

Currently working on a project and I need to post this request:

curl -X POST "http://localhost:8000/api/v1/recognition/recognize" \
-H "Content-Type: multipart/form-data" \
-H "x-api-key: xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxx" \
-F "file=@<image>.jpg"  #image

Tried several times with this code snippet had no luck:

import requests
headers = {
    'Content-Type': 'multipart/form-data',
    'x-api-key': 'xxxxxxxxxxxx',
}
files = {
    'file': ('image.jpg', open('image.jpg', 'rb')),
}
response = requests.post('http://localhost:8000/api/v1/recognition/recognize', headers=headers, files=files)
print(response)

Am I doing something wrong or missing something?

like image 873
Javokhir169 Avatar asked Nov 18 '25 05:11

Javokhir169


2 Answers

try with this

import requests

headers = {
    'Content-Type': 'multipart/form-data',
    'x-api-key': 'xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxx',
}

files = {
    'file': ('<image>.jpg', open('<image>.jpg', 'rb')),
}

response = requests.post('http://localhost:8000/api/v1/recognition/recognize', headers=headers, files=files)
like image 185
buran Avatar answered Nov 19 '25 18:11

buran


I made it work with this code:

import requests
url = "http://10.0.38.119:8000/api/v1/recognition/recognize"
payload = {}
files = [('file', ('<image>.jpg', open('<image>.jpg', 'rb'), 'image/jpeg'))]
headers = {
  'x-api-key': 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
like image 21
Javokhir169 Avatar answered Nov 19 '25 20:11

Javokhir169



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!