If you want to start building your own apps, one of the most important things you need to know is how to access APIs. How else are you going to get all that awesome data people are posting on the Web?
When it comes to making HTTP requests with PHP, you have several options,
the most popular three being cURL,
pecl_http
, and
streams. I generally
use streams, and I’m choosing to highlight this method here, because the HTTP
streams wrapper is native to PHP. This means you can dive right in without
worrying about whether your installation of PHP has all the right libraries.
I also really like that the streams interface is very straightforward and
consistent across different request types. This means that once you know how
to do an HTTP request, it’s a simple matter of changing a few settings and
you’re on your way to doing whatever type of request you want. I’ve also
found that a lot of people aren’t very familiar with this feature, so I
wanted to make sure it was part of our PHP adventure!
I’ve chosen to highlight the Flickr API, because it’s quick and easy to
get an API key, and it’s a great example of an API done right. Flickr has
created very thorough and well-written API documentation, and there’s a lot
of potential for making cool stuff with it right away. For our
purposes — accessing data from Flickr — we’ll only need to do
a basic GET
request. This is good, because you can start doing
fun stuff with the API really quickly using the same basic streams setup for
each request.
So, let’s get to work! If you follow along here, you’ll have a quick Flickr search and display app in no time at all.
The first thing you need is an API key. Go through the request process, and you’ll receive a key immediately upon filling out the form.
Next, you’ll want to check out the Flickr API docs and decide which methods you’d like to try. To start, I recommend doing a simple search.
Once you’ve chosen a method, perform a test to make sure you have
a URL that returns the data you want. To do this, select an API method to
work with, put together a URL to access it, and paste it right in your
browser. For example, to search for photos, the API method we’ll use is
called flickr.photos.search
. It requires that you include the
parameters api_key
and text
. We should also limit the number
of results we get back, just in case, with per_page
. We know from the
documentation that the base URL is
http://api.flickr.com/services/rest/
, so we can construct the
full URL by appending the necessary parameters. For example:
http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[apikey]&text=brooklynbeta&per_page=5
Now that we’ve got a working URL, let’s write a simple PHP script to do a
GET
request with streams and pull back some XML. Here’s the
code we need:
<?php
// Define your URL. Make sure to insert your own API key.
$url = 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[apikey]&text=brooklynbeta&per_page=5';
// Specify the GET request method.
$opts = array(
'http' => array(
'method' => "GET",
)
);
// Open up a stream!
$context = stream_context_create($opts);
// Send a request to $url, and store the response.
$result = file_get_contents($url, FALSE, $context);
?>
Here’s a example of the XML that will be returned:
<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<photos page="1" pages="2" perpage="100" total="159">
<photo id="5198308489" owner="98983159@N00" secret="c10c5df7c7" server="4085" farm="5" title="Shelley Bernstein" ispublic="1" isfriend="0" isfamily="0" />
<photo id="5198448602" owner="98983159@N00" secret="5140c1ff26" server="4083" farm="5" title="Lithium" ispublic="1" isfriend="0" isfamily="0" />
<photo id="5197847253" owner="98983159@N00" secret="039ed79905" server="4144" farm="5" title="Light art" ispublic="1" isfriend="0" isfamily="0" />
</photos>
</rsp>
You can use SimpleXML to parse the XML you get back, and
a simple modification to $opts
is all you need to be able to send POST requests and
all sorts of other fun stuff. For simple GET requests, however, you don’t necessarily need streams; SimpleXML can both fetch and parse the data. Let’s try that now, and we can also add code to display some images:
<?php
// Define your URL. Make sure to insert your own API key.
$url = 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[apikey]&text=brooklynbeta&per_page=5';
$xml = simplexml_load_file($url);
foreach ($xml->photos->photo as $photo) {
$id = $photo['id'];
$owner = $photo['owner'];
$secret = $photo['secret'];
$server = $photo['server'];
$farm = $photo['farm'];
$title = $photo['title'];
$ispublic = $photo['ispublic'];
$isfriend = $photo['isfriend'];
$isfamily = $photo['isfamily'];
echo '<p><img src="' .
"http://farm{$farm}.static.flickr.com/{$server}/{$id}_{$secret}.jpg" .
'"/></p>';
}
?>
You’ll get some pictures displayed like this:
Now that we’ve got something to work with, the fun really starts! You could update the search URL to sort by interestingness. You can find out what sizes are available for a photo, so that you can create uniform displays. For photos that have been geotagged, you can get details like latitude, longitude, and the name of the neighborhood. These features don’t even require authentication. Once you get into that, there’s a whole new set of methods available.
Let’s look at one more example and request the geographical information for
this set of photos we’ve searched for. The API docs tell us that we can use
the flickr.places.getInfo
method to get really detailed
information. In order to use it, we need to get a place_id
parameter to pass in, so we need to go back and modify our original search
URL. In order to get the place_id
, we’ll need to use the
extras
parameter and pass in geo
. Also, we want to
request only photos that have geographical data available, so we’ll add the
has_geo
parameter and set it to 1
. Now, our search
URL looks like this:
http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[apikey]&text=brooklynbeta&per_page=5&has_geo=1&extras=geo
Next, we’ll add this value to be parsed out of the XML:
$place_id = $photo['place_id'];
Then, with the data we get back, we run another stream request for each
photo, passing each photo’s place_id
in the following URL:
http://api.flickr.com/services/rest/?method=flickr.places.getInfo&api_key=[apikey]&place_id=$place_id
Cool! Now you know exactly where each picture was taken and can pinpoint the locations on a map!
Now that you’re started, there are a lot of directions you can take things from here. Take a look through the Flickr API docs and just have fun trying out different requests. Once you get enough of that, check out some different APIs and think about ways you could use them. For example, you could use a map API to automatically show where all your pictures were taken. Also, now that you know how to do requests with streams, you could check out the PHP documentation to see all the other wrappers that are available in addition to HTTP and think about how that could help you. This is just the beginning, and I hope it leads you to some awesome new projects.