Using APIs in Python: a quick example

Python has an extremely intuitive and straightforward way of dealing with APIs, and makes it simple for people like you or me to access and retrieve information from databases. Before I quickly describe how to use APIs in Python, maybe we should begin with: What is an API?

API (Application Programming Interface): An API is a software intermediary that makes it possible for application programs to interact with each other and share data. It’s often an implementation of REST that exposes a specific software functionality while protecting the rest of the application. (definition taken straight from Google itself). Here, it is important to also define the REST acronym (Representational State Transfer), which is a fancy way of describing a protocol for sending and receiving data (in JSON, XML and even text format) between a client and server.

A typical (and popular!) use of API revolves around the twitter API, which many people have used to predict outcomes, perform sentiment analysis, geomapping etc.. (for example: http://www.kazemjahanbakhsh.com/codes/election.html)

But with no further ado, I will show how to use APIs in Python with the awesome Capitol Words API (heavily inspired from the highly recommended CodeAcademy tutorial):

# import required libraries
import requests
import pprint

# set query parameters
query_params = { 'apikey': 'XXXXXXXXXXXXXX',
  'per_page': 100,
  'phrase': 'debt',
  'sort': 'count desc',
  'start_date': '2012-01-01',
  'end_date': '2013-12-31'
}

# define the endpoint database we wish to search
endpoint =  'http://capitolwords.org/api/phrases/state.json'

# extract data
response = requests.get(endpoint, params=query_params)
data = response.json()

# print data to file
out_file = open('debt_reference.txt', 'w')
for i in range(len(data['results'])):
  out_file.write('%s,%s\n' % (data['results'][i]['count'], data['results'][i]['state']))

out_file.close()

Here, we used the ‘phrases/states.json’ endpoint to find how many times the word debt was uttered by senators of each US state between the period of January 1 2012 and December 31 2013.

In order for the code above to work, you will need to obtain your own API key and insert in the code. You can obtain an API key by simply registering (for free) to the Capitol Words API: http://sunlightlabs.github.io/Capitol-Words/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s