In Working with APIs (part 1), I talked about the concept of the API, why you might want to work with APIs, and what you will need to get started. In this second installment of the “Working with APIs” series, I’ll discuss instances of pulling data from an API without server-side programming knowledge. We will leverage APIs available from Google Developer Resources to retrieve results based on information sent solely via a query string.
Even if you didn’t know the term before now, I’m willing to bet you have manipulated a query string at some point in your life. A query string is the part of a URL that contains data that is passed to the script indicated in that URL—like all the “extra stuff” that causes line breaks in bad places when you copy and paste that URL into an e-mail. If you’re crazy geeky (like I am), you try to read query strings and figure out how applications are put together on the back end, try to break applications with exposed query strings (all in the name of testing, I swear), and often use query strings to navigate the web because you couldn’t be bothered to find the link or tool in the user interface. Yes, I am fun at parties, thanks for asking.
A typical URL with a query string looks something like this:
For example, one way to get a list of all the posts within a given month from ProfHacker would be to use this query string:
From left to right this is:
- www.profhacker.com—domain name
- ?—separator, essentially says “variables are on the way!”
- m—variable name, in this case m stands for “month”
- =—assignment operator, indicating that the value that will follow should be assigned to variable m
- 200909—value assigned to the variable m, in this case 2000909 is a date in YYYYMM format (4-digit year, 2-digit month)
This query string thus says to the WordPress installation running on ProfHacker.com “before interpreting the script called index.php, send it a variable called m with a value of 200909″ (actually, in PHP, this would turn into a variable on the backend called $_GET[“m”]) do with it what you will, and send back the results. The result in this case is the generation of the archives for the month of September 2009 in the ProfHacker template (plus some URL rewriting as “index.php?m=200909″ turns into “/2009/09/” and goes to show that there are a lot of query strings out there that don’t look like query strings and just look like regular old directories and pages on a web server, but they aren’t.)
You can—and often will—send more than one variable in a query string, and when you do, you separate the first value from the second variable name with an ampersand (&):
So, why is all this talk about query strings important? Because one way of accessing an API is directly through the query string, often requiring no programming knowledge to do something with the results that are sent. This would be the part of the post where I digress into a discussion of the rhetoric of the query string, but I’m already the resident ProfHacker technoweirdo so…onward to an example of query string power.
In “Working with APIs (part 1)” I used the graphic you see here but didn’t explain what it’s all about. It is, in fact, an example of using a query string to retrieve data from the Google Charts API. The data in this case is a binary stream that, because it has the appropriate content headers sent along with it, magically turns into an image when viewed in your browser.
If you were to view the source of this web page and look at the tag that calls this little chart image, you would see the HTML looks something like this:
If you’ve ever created a web site (or even just placed a graphic in a page) you might be looking at the <img alt="" /> tag, and especially the src (source) attribute, and wondering where’s the image name? Typically an <img alt="" /> tag looks something like this, where image.gif is a file on your web server:
<img src="/path/to/image.gif” alt="" />
In the case of the Google Chart API-driven graphic, the “file” is actually a bunch of binary data generated on-demand from the API and streamed out to the browser. The data never exists as a file on a server unless you save it and give it a name, at which point it becomes a static file and not a dynamically generated graphic. It’s the query string that tells the API which data we want. In this case there are four sets of variable name/value pairs that are sent to the script called “chart” at “chart.apis.google.com”:
API documentation tells you how to ask for what you want to retrieve. In this case, the URL format or query string parameters tell the API we want the following:
- a chart size (chs) of 275 pixels wide and 100 pixels high (275×100)
- chart data (chd) that is text encoded (t:) and shows areas of 90% and 10% (90,10) in the chart type
- a chart type (cht) called p3, which is one of Google’s standard chart types. In this case it is a 3-dimensional pie chart.
- two chart labels (chl), one that says “Caffeinated” and one that says “Sleepy” (Caffeinated|Sleepy). In the query string, these labels are separated by a pipe (|) and are in the order matching the numbers in the chart data variable: “Caffeinated” is the label for the 90% area and “Sleepy” is the label for the 10% area.
The chart script interprets the request in the query string, prepares the resulting binary data, then sends a
header and the stream of data to your browser. The Content-type header tells the browser how to interpret the data being sent; in this case when put back together by the browser the data will create an image in PNG format.
Let’s say you know exactly the type of chart you want to create for a presentation but you don’t have a drawing program handy or you want the image to be dynamic based on data that you feed to a script that is constantly running (that’s often how visualizations such as the ones you see here are created). All you have to do is access the Google Chart API and create charts and graphs to your heart’s content, based on your own manipulations with the query string.
The same concept allows you to use the Google Maps API to create maps—no need to copy, crop, or otherwise manipulate maps in a graphics program when you can just tell the Maps API what you want in almost-English. The Google Maps API allows you to access it thusly for static maps (once you get your own API key):
The parameters of the Google Maps API are numerous, and also have several options within each action you might want to take. For instance, two parameters are latitude and longitude. But, as the documentation clearly states—and matches what I’ve experienced in real life—”Most people don’t speak in latitudes and longitudes; they denote locations using addresses.” Shocker! The Google Maps API takes addresses too: “The process of turning an address into a geographic point is known as geocoding and the Static Maps service can perform geocoding for you if you provide valid addresses.”
This URL generates a basic static map for my current location, using geocoding rather than latitude/longitude:
Let’s break down the query string:
- the center (center) of the map is Spokane, WA (Spokane,+WA). Note that + in there? That’s part of URL encoding, which makes sure spaces and special characters can be interpreted properly. The + in this case stands for a space. A space in a URL just won’t do; it has to be a full, unbroken string, thus the + represents “space”.
- the zoom level (zoom) is 6; zoom levels range from 0 (whole earth) to 21 (road level, or really really zoomed).
- make the image (size) 200 pixels wide and 200 pixels high (200×200)
- tell Google we’re not using a sensor (sensor=false) such as a GPS locator
- place a marker (markers) that is blue (color:blue) with the label “J” (label:J) in Pullman, WA
- use the API Key (key) value of “ABQIAAAA7eUPzCXR...lePZBKHr-ZeIGg” (that’s my key—get your own!)
Put that code in the src of an <img alt="" /> tag and voila—there’s where you can find me.
But since that’s a little boring, let’s use the Google Maps API to show where you can find the rest of the ProfHacker team members (give or take):
Your ability to work with APIs directly through a query string depends on the API, its parameters, and the results it returns. Many APIs allow access via the query string but return results that are more complex than image data that can be handled with an tag. For instance, if we access the Twitter API via the query string, we will get results in Atom or JSON formatting, which then require some sort of server-side interaction to work with the results.
But there’s another possibility between query string API access as described in this post, and server-side programming which will be discussed in “Working with APIs (part four)”—using client-side libraries to do more dynamic things with APIs. “Working with APIs (part three)” will continue to work with Google Code but will combine simple query strings with powerful—and already created!—tools that you can modify in almost-plain-English. Stay tuned!