Python Requests XML Post
If you need to send XML data to a web server using Python, the requests
module provides an easy way to do it. Here are the steps:
Step 1: Import the required modules
import requests
import xml.etree.ElementTree as ET
Step 2: Create the XML data to be sent
You can use the ElementTree
module to create an XML document. Here is an example:
root = ET.Element("person")
name = ET.SubElement(root, "name")
name.text = "John Doe"
age = ET.SubElement(root, "age")
age.text = "25"
xml_data = ET.tostring(root)
In this example, we are creating an XML document that looks like this:
<person>
<name>John Doe</name>
<age>25</age>
</person>
Step 3: Send the XML data using a POST request
Now that we have the XML data, we can use the requests.post()
method to send it to the web server. Here is an example:
url = "http://example.com/api/person"
headers = {'Content-Type': 'application/xml'}
response = requests.post(url, data=xml_data, headers=headers)
In this example, we are sending the XML data to http://example.com/api/person
using a POST request. We also set the Content-Type
header to application/xml
so that the web server knows that we are sending XML data.
Alternative Method: Using a Dictionary
If you have a small amount of XML data, you can also send it as a dictionary using the xmltodict
module. Here is an example:
import requests
import xmltodict
url = "http://example.com/api/person"
data = {'person': {'name': 'John Doe', 'age': '25'}}
xml_data = xmltodict.unparse(data)
headers = {'Content-Type': 'application/xml'}
response = requests.post(url, data=xml_data, headers=headers)
In this example, we are creating a dictionary with the same values as the previous example, and then converting it to an XML string using the xmltodict.unparse()
method. We then send this XML data to the web server using a POST request.