Making SOAP API calls using Python
SOAP stands for Simple Object Access Protocol, as the name suggests nothing but a protocol for exchanging structured data between nodes. It uses XML instead of JSON.
In this article, we are going to see how to make SOAP API calls using python. If you want to test out what exactly the payload and response would look like, you can use the below curl command:
Method 1: Using request
First, we import requests library, then we define the SOAP URL.
The next and the most important step is to format the XML body according to the structure provided in the SOAP URL. To know the format, simply visit the SOAP URL and click on CountryISOCode link and format the XML accordingly.
Then you simply prepare the headers and make the POST call.
<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <m:CountryIntPhoneCodeResponse xmlns:m="http://www.oorsprong.org/websamples.countryinfo"> <m:CountryIntPhoneCodeResult>91</m:CountryIntPhoneCodeResult> </m:CountryIntPhoneCodeResponse> </soap:Body> </soap:Envelope> <Response >
Method 2: Using Zeep
Now that we have seen how to make SOAP calls with requests, we are going to see how easy it is to make it through Zeep. First, you need to install zeep.
pip3 install zeep
- First, set the WSDL URL. You can get the WSDL URL simply by visiting the base URL and click on Service Description. That will take you to the WSDL URL. The base URL will be service_url and append the service name after the base URL.
- Next, you need to create a header element. Now, you need to set the header element with method_url and service_url.
- Now, initialize a zeep client with the WSDL URL.
- All the setup is done, now you just need to call the zeep service with the service name, here the service name is CountryIntPhoneCode. You need to pass the parameters with the country_code and also pass the header to _soapheaders as a list.
- Now, this would directly return the phone code of the country.
Phone Code for IN is 91 Phone Code for US is 1 <Response >
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course