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


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="" xmlns:xsi="" xmlns:xsd="">
    <AutotaskIntegrations xmlns="">
      <PartnerID>partner id</PartnerID>
    <getThresholdAndUsageInfo xmlns="">

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

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')])

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:

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