1

I am trying to send an XML file with a rest api POST. the api takes the xml and creates a new entitiy.

I am trying to open the file and then sending it through requests.

filename = 'test.xml'

response = requests.post(api_url, data=json.dumps(open(filename).readlines()))

But getting the 503 (API not able to get the right input). My intention is to send this XML as it is to api.

If I don't do json.dumps, I get ValueError: too many values to unpack

Varun
  • 1,013
  • 3
  • 17
  • 28
  • It seems that I need to pass the file object and don't have to do read() or readlines(). – Varun Aug 01 '14 at 15:57
  • possible duplicate of [How can I send an xml body using requests library?](http://stackoverflow.com/questions/12509888/how-can-i-send-an-xml-body-using-requests-library) – Seb D. Aug 01 '14 at 15:58
  • Can you point us to the documentation for your API? – Robᵩ Aug 01 '14 at 16:04
  • @Varun - If you have discovered an answer to your question, please share the details in an answer (which you may accept from yourself). – Robᵩ Aug 01 '14 at 16:07

2 Answers2

1

Your API takes XML, not JSON. When you say, data = json.dumps(...), you are passing JSON to your API. This is the reason for your first error message -- 503 (API not able to get the right input).

requests.post() takes ether a dictionary, a string, or a file-like object as its data= parameter. When you do data = foo.readlines(), you are passing in a list (which is neither a string nor a dictionary. This is the reason for your second error message -- "ValueError: too many values to unpack".

Without knowing your API, it is hard to guess what is correct. Having said that, try this:

filename = 'test.xml'
response = requests.post(api_url, data=open(filename).read())

Or, nearly equivalently, this:

filename = 'test.xml'
response = requests.post(api_url, data=open(filename))
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

I think the problem is, you are trying to convert the xml file into json data (using json.dumps()) directly and post it. I guess the API accepts JSON. Then first try to convert the xml file to a python dictionary / whatever data structure suits it. Then convert it into json.

Tamim Shahriar
  • 739
  • 4
  • 9
  • OP does say that the API takes XML. Converting it to JSON seems contrary to that. – Robᵩ Aug 01 '14 at 16:00
  • If it's the case, then no need for json.dumps, he just needs to load the xml file into a string and send it over. Thanks for pointing it out. – Tamim Shahriar Aug 01 '14 at 16:06