Python soap client example

How to consume SOAP web service using Python

In this example I will show you how to consume SOAP web service using Python. In this example mainly I will show you how to call POST request with XML or JSON as a request in the body. I will use here Python package xml.dom.minidom to create the XML request in the body. I will create HTTPS connection over the SOAP webservice.

I am not going to build any SOAP service in this example, rather I will use existing SOAP service from w3schools where there is already ready made SOAP service about temperature converter which can be used for testing purpose.

Related Posts:

Prerequisites

Call SOAP Web Service using Postman

I will first test the SOAP web service using Postman tool. You can also use SOAP UI for SOAP service testing but I think Postman is light-weight tool.

Request Details

Here are the request details of the temperature converter SOAP service.

HTTPS Method: POST

Service URL: https://www.w3schools.com/xml/tempconvert.asmx

Content Type: application/soap+xml (this should go in the Headers)

Request Body:

Response Details

Clicking on the Send button will give you the following response:

Call SOAP Service using Python

Now you will see how to call SOAP web service using Python programming language.

I will write the Python code in Object Oriented way.

import http.client import urllib.parse import xml.dom.minidom class soap_consumer: def __init__(self, msg, json=False): self.msg = msg self.json = json def envelope(self): if self.json: return self.msg else: doc = xml.dom.minidom.Document() env = doc.createElement('soap12:Envelope') env.setAttribute('xmlns:soap12', 'http://www.w3.org/2003/05/soap-envelope') env.setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance') env.setAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema') #print(self.msg) #XML input request data rawdom = xml.dom.minidom.parseString(self.msg) messagenode = rawdom.firstChild #Header header = doc.createElement('soap12:Header') env.appendChild(header) #Body body = doc.createElement('soap12:Body') body.appendChild(messagenode) env.appendChild(body) doc.appendChild(env) #print(doc.toxml('utf-8')) return doc.toxml('utf-8') def send_request(self, url, path, content_type, accept, https=True): data = self.envelope() #print(data) #print(len(data)) headers = conn = '' if https: conn = http.client.HTTPSConnection(url, 443) else: conn = http.client.HTTPConnection(url, 80) #print(conn) conn.request("POST", path, data, headers) response = conn.getresponse() resp_data = response.read() #print(resp_data) if response.status == 200: conn.close() return resp_data else: return 'Status:' + str(response.status) + ': ' + str(resp_data) 

Now you will see what I have written into the above Python code.

I have imported required packages for calling the SOAP service. As I have mentioned at the beginning that I am going to use XML and JSON as requests in the body parameter of the service so I have declared json=False in the constructor. The msg variable will hold the input request passed as XML or JSON.

You can always modify the code as per your requirements and idea here is to show you how to call SOAP service using Python programming.

Next I define a function which will build the envelop if it is XML otherwise it will just return the JSON string.

The envelop which I have created here will work just for the specified service which was earlier tested using Postman tool. You have to modify the code if you have different structure.

I am using here SOAP version 1.2, hence I am using soap12 as a namespace.

Next I define send_request() function which takes a number of parameters for SOAP service.

I check whether I need to connect to HTTP or HTTPS protocol and accordingly I decide upon the last parameter of the function send_request() .

Testing the Program

XML as Request Body

I will test the SOAP service which I have tested using Postman tool in the above.

swsc = soap_consumer('36') resp = swsc.send_request('www.w3schools.com', '/xml/tempconvert.asmx', 'application/soap+xml; charset=utf-8', 'text/xml') print(resp)

JSON as Request Body

I will test different SOAP service that needs JSON as a request body.

params = urllib.parse.urlencode() swsc = soap_consumer(params, True) resp = swsc.send_request('bugs.python.org', '', 'application/x-www-form-urlencoded; charset=utf-8', 'text/plain') print(resp)

That’s all about how to consume SOAP web service using Python program.

Источник

Zeep: Python SOAP client¶

Zeep inspects the WSDL document and generates the corresponding code to use the services and types in the document. This provides an easy to use programmatic interface to a SOAP server.

The emphasis is on SOAP 1.1 and SOAP 1.2, however Zeep also offers support for HTTP Get and Post bindings.

Parsing the XML documents is done by using the lxml library. This is the most performant and compliant Python XML library currently available. This results in major speed benefits when processing large SOAP responses.

The SOAP specifications are unfortunately really vague and leave a lot of things open for interpretation. Due to this there are a lot of WSDL documents available which are invalid or SOAP servers which contain bugs. Zeep tries to be as compatible as possible but there might be cases where you run into problems. Don’t hesitate to submit an issue in this case (but please first read Reporting bugs ).

Installation¶

Zeep is a pure-python module. This means that there is no C code which needs to be compiled. However the lxml dependency does contain C code since it uses libxml2 and libxslt. For linux/bsd this means you need to install libxml2-dev and libxslt-dev packages. For Windows this is unfortunately a bit more complicated. The easiest way is to install lxml via wheel files since that contains already compiled code for your platform.

To install wheel files you need a recent pip client. See https://pip.pypa.io/en/stable/installing/ how to install pip on your platform.

If you have installed pip then run:

Note that the latest version to support Python 2.7, 3.3, 3.4 and 3.5 is Zeep 3.4, install via pip install zeep==2.4.0

This assumes that there are wheel files available for the latest lxml release. If that is not the case (https://pypi.python.org/pypi/lxml/) then first install lxml 4.2.5 since that release should have the wheel files for all platforms:

When you want to use wsse.Signature() you will need to install the python xmlsec module. This can be done by installing the xmlsec extras:

For the asyncio support in Python 3.6+ the httpx module is required, this can be installed with the async extras:

Getting started¶

The first thing you generally want to do is inspect the wsdl file you need to implement. This can be done with:

See python -mzeep —help for more information about this command.

Zeep follows semver for versioning, however bugs can always occur. So as always pin the version of zeep you tested with (e.g. zeep==4.1.0 ’).

A simple use-case¶

To give you an idea how zeep works a basic example.

import zeep wsdl = 'http://www.soapclient.com/xml/soapresponder.wsdl' client = zeep.Client(wsdl=wsdl) print(client.service.Method1('Zeep', 'is cool')) 

The WSDL used above only defines one simple function ( Method1 ) which is made available by zeep via client.service.Method1 . It takes two arguments and returns a string. To get an overview of the services available on the endpoint you can run the following command in your terminal.

python -mzeep http://www.soapclient.com/xml/soapresponder.wsdl

Note that unlike suds, zeep doesn’t enable caching of the wsdl documents by default. This means that everytime you initialize the client requests are done to retrieve the wsdl contents.

User guide¶

Оцените статью