3

This is the goal of post request I need in python:

I got XML file, url and authentication-token. Depending on the xml file I get the xml response from the server back.

req = requests.post(url='http://abc123.com/index.php/plan/', \     
            headers={'auth-token': 'abCdeFgh'}, \
            data={'data': open('sample_plan.xml', 'rb')})

Post request status code is 200, but there is error in xml response like "<error>invalid XML for request</error>". Supposedly that xml file is filled in wrong parameter in my post request. But in another tool - Postman - https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en? it works and succeeds with the correct xml response. What I have in Postman:

  • in Headers: Key: Auth-token Value: abCdeFgh

  • in Body: form-data option chosen.. Key: data Value: sample_plan.xml file chosen..

Goal for parameters (all parameters are mandatory) of post request: 1. in header - Authentication-Token 2. in body - XML file with name/contentID = data

Which parameter should I put the file of the post request into? I've tried almost everything - based on python-requests documentation...

Thanks for your help!

xdaniel
  • 113
  • 1
  • 11

1 Answers1

5

Somehow after hours of trying I got it!

The right parameter was files and there had to be 'data' key with value of tuple with 3 arguments. Otherwise it didn't function properly...

From the requests documentation I used files parameter for multipart encoding upload http://docs.python-requests.org/en/master/api/ with key 'data' which I was urged by + value of 3-tuple ('filename', fileobj, 'content_type')

Therefore the answer for my problem is (also using 'with' keyword so the file is properly closed after its suite finishes)

with open('sample_plan.xml', 'rb') as payload:
    headers = {'auth-token': 'abCdeFgh'}
    files = {'data': ('sample_plan.xml', payload, 'text/xml')}
    req = requests.post(url='http://abc123.com/index.php/plan/', \
            headers=headers, files=files)
xdaniel
  • 113
  • 1
  • 11