CURL alternative in Python CURL alternative in Python python python

CURL alternative in Python


You can use HTTP Requests that are described in the Requests: HTTP for Humans user guide.


import urllib2manager = urllib2.HTTPPasswordMgrWithDefaultRealm()manager.add_password(None, 'https://app.streamsend.com/emails', 'login', 'key')handler = urllib2.HTTPBasicAuthHandler(manager)director = urllib2.OpenerDirector()director.add_handler(handler)req = urllib2.Request('https://app.streamsend.com/emails', headers = {'Accept' : 'application/xml'})result = director.open(req)# result.read() will contain the data# result.info() will contain the HTTP headers# To get say the content-length headerlength = result.info()['Content-Length']

Your cURL call using urllib2 instead. Completely untested.


Here's a simple example using urllib2 that does a basic authentication against GitHub's API.

import urllib2u='username'p='userpass'url='https://api.github.com/users/username'# simple wrapper function to encode the username & passdef encodeUserData(user, password):    return "Basic " + (user + ":" + password).encode("base64").rstrip()# create the request object and set some headersreq = urllib2.Request(url)req.add_header('Accept', 'application/json')req.add_header("Content-type", "application/x-www-form-urlencoded")req.add_header('Authorization', encodeUserData(u, p))# make the request and print the resultsres = urllib2.urlopen(req)print res.read()

Furthermore if you wrap this in a script and run it from a terminal you can pipe the response string to 'mjson.tool' to enable pretty printing.

>> basicAuth.py | python -mjson.tool

One last thing to note, urllib2 only supports GET & POST requests.
If you need to use other HTTP verbs like DELETE, PUT, etc you'll probably want to take a look at PYCURL