3.5.1.2 Python

Authentication against the SOAP API using Python and the Suds library is simple. Assuming that you have already instantiated a client object using the instructions provided in Notes on the Python samples provided in these examples, you need only call the API login method:

client.service.login('user','password')

Note that once the client object is instantiated, all methods supported by the API become available under the service namespace within the client object.

Once authenticated, Suds maintains your session for you and you can continue to make other API calls. Your session is either terminated through a timeout, or by calling the logout method supported by the API.

client.service.logout()
What about Certificate-based Authentication?

The Suds library does not have built-in support for SSL authentication. This makes it difficult to use Python and SOAP in conjunction with certificate-based authentication. Typically, to achieve this, you need to configure your own HTTP transports to use with Suds and ensure that you include a facility to handle SSL authentication. Often it is easier to change the underlying transport used by Suds to make use of the Requests library, which provides good support for handling SSL certificates. There are many approaches to this, but the following example shows how we override the default transport to use the Requests library to handle all of our HTTP requests:

import requests
from suds.transport.http import HttpAuthenticated
from suds.transport import Reply, TransportError

class RequestsTransport(HttpAuthenticated):
    def __init__(self, **kwargs):
        self.cert = kwargs.pop('cert', None)
        HttpAuthenticated.__init__(self, **kwargs)

    def send(self, request):
        self.addcredentials(request)
        resp = requests.post(request.url, data=request.message,
                             headers=request.headers, cert=self.cert, verify=False)
        result = Reply(resp.status_code, resp.headers, resp.content)
        return result

Note that in this case, we have chosen not to perform SSL verification on the CA certificate, but this option can be left out of the method if you have added the CA certificate to your trusted certificates on the system where the application runs. Once you have defined this class, you can instantiate your client object in the following way:

t = RequestsTransport(cert='/path/to/mycertificate.pem')
headers = {"Content-Type" : "text/xml;charset=UTF-8", "SOAPAction" : ""}
client = Client(url,headers=headers,transport=t)

Once your client is instantiated, you are able to perform any of the SOAP API calls available, without the requirement to login using standard plain text authentication credentials.