10 September 2011

Requests - Easiest, Most Enjoyable Way to Make HTTP Requests in Python

I've been working for the last week designing and implementing an API for in-house use at a company in Georgia. The API is being built with PHP5 and a micro-framework called Slim. I would have preferred to build it in web.py but because ultimately this decision was left to the owners who are responsible for maintaining it's being done in PHP (a language that they're familiar with).

One of the sore spots has been testing the API as we put it together. In the end it will be used by the developers that they hired to write mobile phone applications. I settled on using a Python script for testing the API but quickly tired of writing the HTTP request code using httplib2 and urllib2. I set out for a better HTTP Request library and quickly found Requests; an elegant and dead-simple library that makes writing code to work with HTTP Requests actually enjoyable.

>>> import requests
>>> r = requests.get("http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2&alt=jsonc")
>>> r.status_code
200
>>> print r.content
{"apiVersion":"2.1","data":{"updated":"2011-09-09T19:54:17.000-07:00","totalItems":99,"startIndex":1,"itemsPerPage":25,"items":[{"id":"X9YMU0WeBwU","uploaded":"2011-08-17T00:52:31.000Z","updated":"2011-09-11T01:09:51.000Z","uploader":"LadyGagaVEVO","category":"Music","title":"Lady Gaga - Yoü And I (Official Video)","description":"Music video by Lady Gaga performing Yoü And I (Official Video). Lady Gaga's \"Yoü And I\" video received 1,054,214 video views on YouTube prior to the official VEVO video release.  © 2011 Interscope Records","tags":["You","and","new","video","song","official","Laurieann","Gibson","haus","of","gaga","Mother","Monster"],"thumbnail":{"sqDefault":"http://i.ytimg.com/vi/X9YMU0WeBwU/default.jpg","hqDefault

[ ... cut for space ... ]
I think I will also go back through and rewrite a bunch of my YQL code to use Requests instead for it's HTTP request needs. This should be a standard part of your Python toolbox for sure.

No comments:

Post a Comment