How to Talk to an Application Program Interface (“API”)

This post will focus on how to talk to an application program interface.

As you talk to APIs or web services, you have to understand how they think. You will need to read the set of rules for the API. The rules will tell you how to interface with the application.

API

There are a couple of choices for web service technologies. SOAP is considered difficult to work with. It is much easier to work with REST.

SOAP

A nice API to learn is the Google Maps Geocoding. It is always a good idea to read the API documentation.

Run the program geojson.py, and enter “Ann Arbor, MI” for the user input. The program will return the following JSON object:

JSON
This JSON data results from entering the URL for “Ann Arbor, MI” in the Google Geocoding API.

The nice thing about a REST based service is you can take the URL and paste it in a browser. You derive how to put the URL together from the API documentation.

The URL will retrieve JSON that gives you lots of data about the location. You can parse it with the JSON library in Python.

The following picture shows the entire geojson.py program:

longer code

Running the program prompts the user for a location. This example showed the JSON results data for entering “Ann Arbor, MI”.

Notice the program imports the “urllib” library, which gives you power to retrieve data on the internet. The “json” library gives you power to parse data that comes back.

The “serviceurl” is the one you get from reading the API documentation, but Python is able to encode it automatically. Look at the line which calls the method “urllib.urlencode”. This line of code is what encodes the URL.

The use of a “try” and “except” checks if the data is bad. If the data is bad then the loop breaks and the user is prompted to enter in a new location.

The line “print json.dumps(js, indent=4)” will dump the JSON object into a string and print it out nicely with indentation.

The lines of code for “lat” and “lng” are a bit tricky. It parses through dictionaries inside dictionaries from the JSON object.

The data this API provides can be very valuable, so do not assume the API is always free.