matt snider
matt snider

Reputation: 4113

Python httplib2.Http not sending post parameters

I have been trying to make an API request to Twilio using the httplib2 Http class and no matter how I try to setup the request, it doesn't send my post DATA. I know this, because I posted to a local URL and the post arguments are empty. Here is my code:

_TWILIO_URL = 'https://api.twilio.com/2010-04-01/Accounts/%s/%s'
class Api(object):
    '''
    A Python interface to the Twilio API
    '''

    def __init__(self, AccountSid, AuthToken, From):
        self.AccountSid = AccountSid
        self.AuthToken = AuthToken
        self.From = From

    def _get_from(self, From):
        """Use the provided From number or the one defined on initialization"""
        if From:
            return From
        else:
            return self.From

    def call(self, To, Url, From=None):
        """Sends a request to Twilio having it call a number; the provided URL will indicate how to handle the call"""
        url = _TWILIO_URL % (self.AccountSid, 'Calls')
        data = dict(From=self._get_from(From), To=To, Url=Url)
        return self.request(url, body=urlencode(data))

    def request(self, url, method='POST', body=None, headers={'content-type':'text/plain'}):
        """Send the actual request"""
        h = Http()
        h.add_credentials(self.AccountSid, self.AuthToken)
        resp, content =  h.request(url, method=method, body=body, headers=headers)

        print content

        if resp['status'] == '200':
            return loads(content)
        else:
            raise TwilioError(resp['status'], content)

    def sms(self, To, Body, From=None):
        """Sends a request to Twilio having it call a number; the provided URL will indicate how to handle the call"""
        url = _TWILIO_URL % (self.AccountSid, 'SMS/Messages')
        data = dict(From=self._get_from(From), To=To, Body=Body)
        return self.request(url, body=urlencode(data))

I can't find anything on google talking about troubleshooting

Upvotes: 2

Views: 2297

Answers (2)

samplebias
samplebias

Reputation: 37929

Twilio mentions this requirement in their API docs concerning POST requests:

But be sure to set the HTTP Content-Type header to
"application/x-www-form-urlencoded" for your requests if you are writing your own client.

Upvotes: 3

matt snider
matt snider

Reputation: 4113

It turns out that the 'content-type' has to be set to 'application/x-www-form-urlencoded'. If anyone knows why, please let me know.

Upvotes: 0

Related Questions