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

4
  • It seems that I need to pass the file object and don't have to do read() or readlines(). Commented Aug 1, 2014 at 15:57
  • possible duplicate of How can I send an xml body using requests library? Commented Aug 1, 2014 at 15:58
  • Can you point us to the documentation for your API? Commented Aug 1, 2014 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). Commented Aug 1, 2014 at 16:07

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

OP does say that the API takes XML. Converting it to JSON seems contrary to that.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.