pythoncurlposthttpx

httpx Library vs curl program


I am trying to use the httpx library to POST a file through a website provided API. The API requests some additional headers. Here is my Pyhton script:

#!/usr/bin/python3
import httpx

files = {'file': ('Test.pdf', open('Test.pdf', 'rb'), 'application/pdf')}

url='https://some.api.domain/Api/1/documents/mandant'
headers= {\
        'accept': 'application/json',\
        'APPLICATION-ID': '42fxxxxxxx',\
        'USER-TOKEN': '167axxxxx',\
        'Content-Type': 'multipart/form-data',\
        }
data={\
        'year': 2024,\
        'month': 1,\
        'folder': 3,\
        'notify': False\
        }

response = httpx.post(url, headers=headers, data=data, files=files)
print(response.status_code)
    

And here's the curl command line call to do the same:

curl -i -v -X 'POST' 'http://www.some.domain/' \
-H 'accept: application/json' \
-H 'APPLICATION-ID: 42xxxx' \
-H 'USER-TOKEN: 167axxxxx'\
-H 'Content-Type: multipart/form-data'\
-F 'year=2024'\
-F 'month=1'\
-F 'file=@Test.pdf;type=application/pdf'\
-F 'folder=3'\
-F 'notify=false'

Running the Python script I am getting a 412 response, which means some parameters missing, incomplete or invalid. Running the curl command it works fine and I am getting 200 and the file is transferred.

So how do I "translate" the correct curl call into a correct httpx call?

Thanks!


Solution

  • By removing the header: 'Content-Type': 'multipart/form-data',\ it finally works!