Python – Using urllib2 to do a SOAP POST, but I keep getting an error

apipostpythonsoaptypeerror

I am trying to do an API call via a SOAP POST and I keep getting
"TypeError: not a valid non-string sequence or mapping object." @ data = urllib.urlencode(values)

SM_TEMPLATE = """<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Header>
    <AutotaskIntegrations xmlns="http://Autotask.net/ATWS/v1_5/">
      <PartnerID>partner id</PartnerID>
    </AutotaskIntegrations>
  </soap:Header>
  <soap:Body>
    <getThresholdAndUsageInfo xmlns="http://Autotask.net/ATWS/v1_5/">
    </getThresholdAndUsageInfo>
  </soap:Body>
</soap:Envelope>"""

values = SM_TEMPLATE%()
data = urllib.urlencode(values)
req = urllib2.Request(site, data)
response = urllib2.urlopen(req)
the_page = response.read()

Any help would be much appreciated.

Best Solution

The urllib.urlencode function expects a sequence of key-value pairs or a mapping type like dict:

>>> urllib.urlencode([('a','1'), ('b','2'), ('b', '3')])
'a=1&b=2&b=3'

To perform an SOAP HTTP POST, you should leave the SM_TEMPLATE blob as-is and set it as the POST body, then add a Content-Type header for the POST body's encoding and charset. For example:

data = SM_TEMPLATE
headers = {
    'Content-Type': 'application/soap+xml; charset=utf-8'
    }
req = urllib2.Request(site, data, headers)
Related Question