Sunday, November 14, 2021

[SOLVED] How do I replicate a `curl` with `-F` in Python 3?

Issue

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?


Solution

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



Answered By - norok2