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='/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' '/' \
-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 '[email protected];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!
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 '[email protected];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!
Share Improve this question asked Feb 6 at 3:22 ChristianChristian 3113 silver badges12 bronze badges 2 |1 Answer
Reset to default 0By removing the header:
'Content-Type': 'multipart/form-data',\
it finally works!
files = {'file': open('Test.pdf', 'rb')}
hayageek.com/httpx-file-upload – Andrew Ryan Commented Feb 6 at 5:05