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
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:
- Import the module that has the functions to open and get data from a URL.
- 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.
- Using file I/O method, read(), to read what the URL returned, ie., the API response, into the string response.
- Finally, print response.
Here's a screenshot when I ran the program and its output:
No comments:
Post a Comment