0

I have this curl:

curl -v "http://some.url" \
    -X PUT \
    -H "X-API-Key: API_KEY" \
    -H 'Accept: application/json' \
    -H 'Content-Type: multipart/form-data' \
    -F "logo=@the_logo.png;type=image/png"

And I am trying to replicate this with Python. What I have tried so far is:

import requests


with open("the_logo.png", "rb") as file_obj:
   data = file_obj.read()
requests.put(
    "http://some.url",
    files={"logo": ("the_logo.png", data, "image/png")},
    headers={
        "X-API-Key": "API_KEY",
        "Accept": "application/json",
        "Content-Type": "multipart/form-data"}

But for some reason the curl above works, while the Python code does not and the server replies with a 422.

How can I make Python replicate what curl does?

norok2
  • 25,683
  • 4
  • 73
  • 99
  • 1
    Have you sniffed the HTTP requests to see how they differ? – Charles Duffy Jul 09 '21 at 16:11
  • BTW, you should be able to have `file_obj` itself be in the `data` location in the tuple (if you haven't read from it and the pointer is still at the front of the file, so you'd need to take out the `data = file_obj.read()` line). – Charles Duffy Jul 09 '21 at 16:13
  • 1
    try `files={"logo": ("the_logo.png", open('the_logo.png', 'rb'), "image/png")}` once. – Tarique Jul 09 '21 at 16:21
  • 1
    have you checked out http://pycurl.io/docs/latest/index.html? – mad_ Jul 09 '21 at 16:32
  • @Tarique's suggestion matches with this answer, except using POST instead of PUT: [How to upload file with python requests?](https://stackoverflow.com/a/22567429/1431750) – aneroid Jul 09 '21 at 16:45
  • Tarique's comment is what I see from https://curl.trillworks.com/#python – QHarr Jul 09 '21 at 18:03
  • @CharlesDuffy How would I go with that? It seems that Python/requests does not provide the raw data sent – norok2 Jul 12 '21 at 13:54
  • @Tarique I tried that but I get the same problem – norok2 Jul 12 '21 at 13:55
  • The word "sniff" implies use of a packet sniffer -- Wireshark, tcpdump, etc. – Charles Duffy Jul 12 '21 at 14:22

1 Answers1

0

After some reading, it appears that the trick is to NOT set Content-Type in the headers when using requests and the files parameter.

norok2
  • 25,683
  • 4
  • 73
  • 99