Wednesday, August 24, 2011

Example #11 - Create the simplest program

Example #10 showed many uses of the API.  Let's code up one.  This will be the Hello World! example of using the API.

The code examples will be written in Python.  I'm brand new to Python and using this work as a great excuse to learn it.  If you look at any of the code and know there's a better way, use it and ignore my novice approach.

Let's pick the API request from Example #10 with the smallest amount of response data.  It'll just keep things simpler.  The winner is the API request to count the number of views in the Chicago portal since it just returns a number.

Code
Here's the code for my program called, example11.py:
import urllib2
f = urllib2.urlopen("http://data.cityofchicago.org/api/views.json?count=true")
response = f.read()
print response

Explanation
What's going on in this code?  Here's a line by line description:
  1. Import the module that has the functions to open and get data from a URL.
  2. The URL is the API request to return the number of views in the Chicago portal.  (See Example #10 for more about how the URL is determined.)  f is the filehandle to read the response from the API request.  The API is invoked during this statement.
  3. Using file I/O method, read(), to read what the URL returned, ie., the API response, into the string response.
  4. Finally, print response.
If you are new to Python as well, you can try this yourself.  First, go to the Python site and download Python.  I'm using Python 2.7. Then, setup Python on your system.  You can cut-and-paste the code into your editor, save it as example11.py, and run it with the command, python example11.py.

Here's a screenshot when I ran the program and its output:

No comments:

Post a Comment