python requests post xml soap

Python Requests Post XML SOAP

Python is a versatile programming language that can be used for various purposes. Requests is a python module that allows you to send HTTP/1.1 requests using python. SOAP (Simple Object Access Protocol) is a messaging protocol that allows you to communicate between different systems over the network using XML (Extensible Markup Language). In this article, we will discuss how to send a POST request with an XML SOAP payload using the Python Requests module.

Using Python Requests POST Method

The Python Requests library provides the post() method to send a POST request to the server. The post() method takes two arguments, the URL and the data to be sent in the request body.


import requests

url = 'http://example.com/soap'
headers = {'content-type': 'application/soap+xml'}
data = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header/><soapenv:Body><ns:getQuote xmlns:ns="http://example.com/stockquote"><ns:symbol>AAPL</ns:symbol></ns:getQuote></soapenv:Body></soapenv:Envelope>'

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

print(response.text)
    

In the above code, we have created a POST request to the URL 'http://example.com/soap' with a SOAP body in the XML format. We have set the header "content-type" to "application/soap+xml" to indicate that we are sending a SOAP request. We have used the post() method of the Python Requests module to send the request to the server. The response from the server is stored in the "response" variable.

Using Python Requests With XML Payload

If you have an XML payload that you want to send in a POST request using Python Requests, you can simply pass the XML data as a string in the data parameter of the post() method.


import requests

url = 'http://example.com/xml'
headers = {'content-type': 'application/xml'}
data = '<example><name>John</name><age>30</age></example>'

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

print(response.text)
    

In the above code, we have created a POST request to the URL 'http://example.com/xml' with an XML payload in the data parameter. We have set the header "content-type" to "application/xml" to indicate that we are sending an XML request. We have used the post() method of the Python Requests module to send the request to the server. The response from the server is stored in the "response" variable.