Cogs and Levers A blog full of technical stuff

requests

Getting your program to make simple HTTP has become a feature that is just a given these days. The python library requests makes life a lot easier.

Requests is the only Non-GMO HTTP library for Python, safe for human consumption.

Today’s post will focus on this library, to show you how you can be immediately productive.

How things were

One of the best comparisons comes directly from the requests documentation. Prior to its existence, you needed to do the following to perform a GET request with Basic Authentication:

import urllib2

gh_url = 'https://api.github.com'

req = urllib2.Request(gh_url)

password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, 'user', 'pass')

auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)

urllib2.install_opener(opener)

handler = urllib2.urlopen(req)

print handler.getcode()
print handler.headers.getheader('content-type')

Bringing this code forward to use the requests library, the code simplifies:

import requests

r = requests.get('https://api.github.com', auth=('user', 'pass'))

print r.status_code
print r.headers['content-type']

Clearly, you can see that the code using the requests library is far simpler. Let’s look at some more examples.

Simple verbs

The simple verbs can be used quite simply by name:

requests.get('http://api.me.com/people/1')
requests.put('http://api.me.com/people/1', data = { 'name': 'john' })
requests.post('http://api.me.com/people', data = { 'name': 'john' })
requests.delete('http://api.me.com/people/1')

Of course the likes of OPTIONS and HEAD are also available.

Finishing up

The rest of this blog post could easily replicate all of the content in the documentation, but instead I’ll link to all of the good stuff: