Running a SOAP Webservice without a library

November 23, 2009

This is an example of some Python code to run a SOAP webservice, without using a SOAP library. It takes raw XML (I generated this from the WSDL by using OxygenXML editor) and then uses HTTP to send it across to the service.

Call code

lXml = """
  <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP-ENV:Header/>
  <SOAP-ENV:Body>
  <LoginApplicationCallParameter xmlns="http://ws.company.com/wsdl">
  <Password>%s</Password>
  <UserName>%s</UserName>
  </LoginApplicationCallParameter>
  </SOAP-ENV:Body>
  </SOAP-ENV:Envelope>""" % (self.password, self.username)
lConnection = httplib.HTTP('localhost:8000')
lConnection.putrequest("POST", "/path/to/web/service/LoginApplication")
lConnection.putheader("Host", 'localhost:8000')
lConnection.putheader("User-Agent", "MyUserAgent")
lConnection.putheader("Content-type", 'text/xml; charset="UTF-8"')
lConnection.putheader("Content-length", "%d" % len(lXml))
lConnection.putheader("SOAPAction", '""')
lConnection.endheaders()
lConnection.send(lXml)

Process Response code

lStatusCode, lStatusMessage, lHeader = lConnection.getreply()
lResponse = lConnection.getfile().read()
lTree = fromstring(lResponse)
self.security_token = 
  lTree.findtext("{http://schemas.xmlsoap.org/soap/envelope/}Body/{http://ws.company.com/wsdl}LoginApplicationResponseParameter/{http://ws.company.com/wsdl}SecurityToken")
lConnection.close()

UPDATE

Looks like httplib.HTTP is deprecated, and removed in Python 3. Here's the same code using the new HTTPConnection:

lXml = """
  <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP-ENV:Header/>
  <SOAP-ENV:Body>
  <LoginApplicationCallParameter xmlns="http://ws.company.com/wsdl">
  <Password>%s</Password>
  <UserName>%s</UserName>
  </LoginApplicationCallParameter>
  </SOAP-ENV:Body>
  </SOAP-ENV:Envelope>""" % (self.password, self.username)

lConnection = httplib.HTTPConnection("localhost:8000")
lHeaders = {"Host" : "localhost:8000",
            "User-Agent" : "MyUserAgent",
            "Content-type": 'text/xml; charset="UTF-8"',
            "Content-length": "%d" % len(pXml),
            "SOAPAction": '""',
            }
lConnection.request("POST", "/path/to/web/service/LoginApplication", pXml, lHeaders)

Process Response code

lResponseObject = lConnection.getresponse()
lStatusCode = lResponseObject.status
lResponse = lResponseObject.read()
lTree = fromstring(lResponse)
self.security_token = 
  lTree.findtext("{http://schemas.xmlsoap.org/soap/envelope/}Body/{http://ws.company.com/wsdl}LoginApplicationResponseParameter/{http://ws.company.com/wsdl}SecurityToken")
lConnection.close()

Tags: python soap http