0

I want to send an XML POST request using the Python 3 Requests library.

When I create my XML body as a plaintext string, I am able to send XML bytes to the server without any issues. However, if I send my request as an ElementTree.Element, the server responds with the error message "Premature end of file".

Writing XML as plaintext (works)

import requests

root = """<?xml version = '1.0'?>
          <Kronos_WFC version = '1.0'> </Kronos_WFC>"""
headers = {'Content-Type': 'text/xml'}
print(requests.post('http://localhost/wfc/XmlService', data=root, headers=headers)).text

# Output:
# <Kronos_WFC version="1.0" WFCVersion="6.3.13.362" TimeStamp="10/30/2017 12:19PM GMT-04:00"></Kronos_WFC>

Building XML with ElementTree (fails)

from xml.etree import ElementTree as ET
import requests

root = ET.Element("Kronos_WFC", version="1.0")
headers = {'Content-Type': 'text/xml'}
print(requests.post('http://localhost/wfc/XmlService', data=root, headers=headers)).text

# Output:
# <Kronos_WFC>
#    <Response Status="Failure" ErrorCode="-1" Message="Premature end of file.">
#    </Response></Kronos_WFC>

When I tried printing my XML ElementTree to debug, I found that Python was interpreting it as an object, rather than as parsable text. I suspect that this may be the cause of the issue.

root = ET.Element("Kronos_WFC", version="1.0")
print(root)

# Output:
# <Element 'Kronos_WFC' at 0x013492D0>

Ideally I would like to build my XML POST request using ElementTree.Element, then send it to an API using Requests.

How can I send an XML ElementTree.Element to a server using Python Requests?

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225

1 Answers1

2

Use ElementTree.tostring() to create a string representation of the xml.

requests.post(
    'http://localhost/wfc/XmlService', 
    data=ET.tostring(root), 
    headers=headers
)
Håken Lid
  • 22,318
  • 9
  • 52
  • 67
  • 1
    You are right. The api is a little unintuitive. I would expect ElementTree to have some sort of `tostring` method. It does have a `write` method for writing to a file. – Håken Lid Oct 30 '17 at 17:19