python requests post xml example

Python Requests Post XML Example

If you want to send XML data using Python, you can use the requests library. The requests.post() method allows you to send a POST request with data. Here's how you can use it to send XML:

Using XML String

First, you need to create the XML data as a string. You can use a variable or read the data from a file:


xml_data = "<book><title>Harry Potter</title><author>J.K. Rowling</author></book>"

Then, you can use the requests.post() method to send the data:


import requests

url = "https://example.com/api/books"

headers = {"Content-Type": "application/xml"}

response = requests.post(url, data=xml_data, headers=headers)

print(response.status_code)

This will send a POST request to the URL specified with the XML data in the data parameter and the headers in the headers parameter.

Using XML Element

You can also create the XML data using Python's xml.etree.ElementTree module. Here's an example:


import xml.etree.ElementTree as ET
import requests

url = "https://example.com/api/books"

headers = {"Content-Type": "application/xml"}

root = ET.Element("book")
title = ET.SubElement(root, "title")
title.text = "Harry Potter"
author = ET.SubElement(root, "author")
author.text = "J.K. Rowling"

xml_data = ET.tostring(root)

response = requests.post(url, data=xml_data, headers=headers)

print(response.status_code)

This will create an XML element tree with the book data and convert it to a string using ET.tostring(). Then, it will send a POST request to the URL specified with the XML data in the data parameter and the headers in the headers parameter.

Using Requests-XML Library

You can also use the requests-xml library to send XML data. First, you need to install it:


pip install requests-xml

Then, you can use the requests_xml.XMLSession() method to create a session with XML support:


from requests_xml import XMLSession

session = XMLSession()

url = "https://example.com/api/books"

headers = {"Content-Type": "application/xml"}

response = session.post(url, data={"book": {"title": "Harry Potter", "author": "J.K. Rowling"}}, headers=headers)

print(response.status_code)

This will create an XML session and use its post() method to send a POST request to the URL specified with the XML data in the data parameter and the headers in the headers parameter.