Home > Mobile >  422 when posting file with requests
422 when posting file with requests

Time:11-04

So I've been trying to figure this out all day but haven't been able to make any progress. I have this curl command, which works:

curl -X POST -H "x-hermes-key: <KEY>" -H "Accept: application/json"  --form file='@example_files/ex1.pdf' <URL> -kv 

When I try to run its equivalent in python with requests, I get a 422 error:

header = {
            "Accept": "application/json",
            "X-Hermes-Key": <KEY>
        }

f = {'file': open("example_files/ex1.pdf", "rb")}
r_create = requests.post(url=<URL>, headers=header, files=f)

Can anyone help me see where I'm making a mistake?

CodePudding user response:

The following should match the curl command and POST with content-type=multipart/form-data.

headers = {
            "Accept": "application/json",
            "X-Hermes-Key": <KEY>
        }

url = <URL>

files = [('upload', ('ex1.pdf', open('example_files/ex1.pdf', 'rb'),
                     'application/octet-stream'))]
r = requests.post(url=url, headers=headers, files=files)
print(r.status_code)
  • Related