Making SOAP API calls using Python - GeeksforGeeks

18 Jul, 2021
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:
CURL Output
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.
Code:
Python3
import requests# SOAP request URLurl = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso"  # structured XMLpayload = """<?xml version=\"1.0\" encoding=\"utf-8\"?>            <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">                <soap:Body>                    <CountryIntPhoneCode xmlns=\"http://www.oorsprong.org/websamples.countryinfo\">                        <sCountryISOCode>IN</sCountryISOCode>                    </CountryIntPhoneCode>                </soap:Body>            </soap:Envelope>"""# headersheaders = {    'Content-Type': 'text/xml; charset=utf-8'}# POST requestresponse = requests.request("POST", url, headers=headers, data=payload)  # prints the responseprint(response.text)print(response)
Output:
<?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 [200]>
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
Approach:
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.
Code:
Python3
import zeep  # set the WSDL URLwsdl_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL"  # set method URLmethod_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryIntPhoneCode"  # set service URLservice_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso"  # create the header elementheader = zeep.xsd.Element(    "Header",    zeep.xsd.ComplexType(        [            zeep.xsd.Element(                "{http://www.w3.org/2005/08/addressing}Action", zeep.xsd.String()            ),            zeep.xsd.Element(                "{http://www.w3.org/2005/08/addressing}To", zeep.xsd.String()            ),        ]    ),)# set the header value from header elementheader_value = header(Action=method_url, To=service_url)  # initialize zeep clientclient = zeep.Client(wsdl=wsdl_url)  # set country code for Indiacountry_code = "IN"  # make the service callresult = client.service.CountryIntPhoneCode(    sCountryISOCode=country_code,    _soapheaders=[header_value])# print the resultprint(f"Phone Code for {country_code} is {result}")  # set country code for United Statescountry_code = "US"  # make the service callresult = client.service.CountryIntPhoneCode(    sCountryISOCode=country_code,    _soapheaders=[header_value])  # print the resultprint(f"Phone Code for {country_code} is {result}")print(response)
Output:
Phone Code for IN is 91
Phone Code for US is 1
<Response [200]>
Python-requests
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()