Convert this curl cmd to Python 3

17,642

Here's a version that works both on Python 2 and 3:

import requests # pip install requests

url = 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json'
r = requests.post(url, dict(
        From='+17035551212',
        To='+17035551212',
        Body='This is a test'), auth=('foo', 'bar'))

print(r.headers)
print(r.text) # or r.json()

To make https post request with basic http authentication on Python 3.3:

from base64 import b64encode
from urllib.parse import urlencode
from urllib.request import Request, urlopen

user, password = 'foo', 'bar'
url = 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json'
data = urlencode(dict(From='+17035551212', To='+17035551212', 
                      Body='This is a test')).encode('ascii')
headers = {'Authorization': b'Basic ' +
        b64encode((user + ':' + password).encode('utf-8'))}
cafile = 'cacert.pem' # http://curl.haxx.se/ca/cacert.pem
response = urlopen(Request(url, data, headers), cafile=cafile)

print(response.info())
print(response.read().decode()) # assume utf-8 (likely for application/json)
Share:
17,642
Glen
Author by

Glen

Updated on June 19, 2022

Comments

  • Glen
    Glen almost 2 years

    The following curl command works perfectly (private data anonymized):

    curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json' \
    -d 'From=%2B14155551234' \
    -d 'To=%2B17035551212' \
    -d 'Body=This+is+a+test' \
    -u foo:bar
    

    How can I send out this exact same HTTPS POST request in the proper Python3.3 way? I don't want to have to use anything other than Python 3.3's standard library if I can avoid it (in other words, not using the twilio python module, or "requests", or pycurl, or anything outside the plain vanilla Python 3.3 installation).

    The preferred Python approach seems to keep evolving from version to version, the snippets I find by Googling never mention which version they're using or don't do the login part, the Python docs are full of "deprecated since 3.x" but never include code examples of the new way to do things....

    If curl can do this so easily, so can standard Python 3.3. But how exactly is this supposed to be done now?