Reputation: 26762
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".
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>
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?
Upvotes: 0
Views: 3292
Reputation: 23064
Use ElementTree.tostring() to create a string representation of the xml.
requests.post(
'http://localhost/wfc/XmlService',
data=ET.tostring(root),
headers=headers
)
Upvotes: 2