Backend Development 5 min read

Sending XML Data with Python requests: Build, Post, and Parse

This tutorial explains how to construct XML data in Python, set the appropriate Content-Type header, send it via a POST request using the requests library, and parse the XML response, providing complete example code for developers working with web APIs.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Sending XML Data with Python requests: Build, Post, and Parse

In web development and API interaction, XML is a common data exchange format, especially in enterprise systems. Python's requests library provides a simple interface to send HTTP requests, including POST, which is convenient for sending XML data. This article explores how to use requests to send XML data, covering XML construction, setting the correct Content-Type, and handling the response.

1. Construct XML data

First, we need to build the XML. You can write an XML string manually or use Python's xml.etree.ElementTree library.

import xml.etree.ElementTree as ET
# Create root element
root = ET.Element("root")
# Add child nodes
child1 = ET.SubElement(root, "child1")
child1.text = "Child 1 content"
child2 = ET.SubElement(root, "child2")
child2.text = "Child 2 content"
# Convert ElementTree to string
xml_data = ET.tostring(root, encoding="utf-8", method="xml").decode()

2. Set Content-Type

When sending XML, the Content-Type header must be set to application/xml or text/xml , depending on the API requirements.

3. Send POST request

Use requests.post to send the POST request, passing the XML string as the data parameter and including the headers.

import requests
url = "http://example.com/api/endpoint"
# Build XML data
xml_data = """
   Child 1 content
   Child 2 content
"""
# Set headers
headers = {
    "Content-Type": "application/xml",
}
# Send POST request
response = requests.post(url, data=xml_data, headers=headers)
# Check response status
if response.status_code == 200:
    print("Request was successful!")
    print(response.text)
else:
    print(f"Request failed with status code {response.status_code}.")

4. Process response

After receiving the response, you can access response.text . If the response is also XML, parse it with xml.etree.ElementTree .

# Parse XML response
root = ET.fromstring(response.text)
for child in root:
    print(child.tag, child.text)

Below is a complete example that demonstrates constructing XML, sending it with requests , and parsing the XML response.

import requests
import xml.etree.ElementTree as ET
# Build XML data
xml_data = """
   Child 1 content
   Child 2 content
"""
# Set headers
headers = {
    "Content-Type": "application/xml",
}
# Send POST request
url = "http://example.com/api/endpoint"
response = requests.post(url, data=xml_data, headers=headers)
# Check response status
if response.status_code == 200:
    print("Request was successful!")
    # Parse XML response
    root = ET.fromstring(response.text)
    for child in root:
        print(child.tag, child.text)
else:
    print(f"Request failed with status code {response.status_code}.")

By following this code, you can use Python's requests library to send and receive XML data, a valuable skill for interacting with web services that require XML, enhancing both beginner and experienced developers' ability to work with Web APIs.

backendPythonHTTPAPIXMLRequests
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.