Creating a Simple Online Application using the Flickr API

Photo Credit: *dans

The Flickr API is one of the most widely used APIs out there. In this article I will show you how to build your own simple online application using PHP and the Flickr API.

The sample online application we build today will be one that takes a Flickr image URL (e.g. http://www.flickr.com/photos/dans180/854998249/), then outputs the code needed for you to properly display the photo's credit. Remember, every time you use a Creative Commons licensed photo from Flickr, you need to provide the proper attribution and that is usually considered a link back to the photo while mentioning the photographer's name. This is an example of the kind of output that we hope to get:

Real Link:
Photo Credit: *dans

HTML Code Output:
Photo Credit: <a href="http://www.flickr.com/photos/dans180/854998249/">*dans</a>

Getting Started

First off, you will need to get an API key. Get one here and hold onto it for later.

Next, we need to build the form that our visitors can input the URL into. This should be pretty basic stuff for most of us.

The HTML Form

<form method="post" id="form" action="flickr_api_example.php" >
	<table>
		<tr>
		<td><label for="photo">Flickr Photo URL:</label></td>
		<td><input type="text" value="" size="50" name="photo" id="photo" /></td>
		</tr>
		<tr>
		<td></td>
		<td><input type="submit" value="Generate Code" name="submitted" /></td>
		</tr>
	</table>
</form>

The PHP if-statement

This form is setup to POST the data back to itself for processing. To handle this, we need to make use of an if-statement to check to see if the form is submitting data back to itself, or if it just needs to show a blank form to a new visitor.

The PHP evaluation isset allows us to determine whether or not a variable is set. In our example, we check to see if the variable 'photo' is set - because that is the name of the input field where the visitor enters the Flickr image's URL.

<?php 
if (isset($_POST['photo'])) { //The form was submitted, process the data

} else { //The form was not submitted

};
?>

If the variable 'photo' is set, the next step is to initialize some variables. The first variable is the image URL that the user submitted into our form, while the second will be the API key we got from Flickr.

<?php 
if (isset($_POST['photo'])) { //The form was submitted, process the data
	$queryString=$_POST['photo']; //The URL submitted
	$flickr_api_key = "352ee7XXXXXXXXXXXXXXXXXXXXXXXXXX"; //Our API Key
	
} else { //The form was not submitted

};
?>

In order to make the URL submitted usable to us, we need to split it up into its relevant sections. I use the PHP function explode to help break the URL up by the character '/'. All we need from this URL is the photo id, and we can see below is the 6th of these so called sections.

PHP FACT: PHP starts it's count with 0.

<?php 
if (isset($_POST['photo'])) { //The form was submitted, process the data
	$queryString=$_POST['photo']; //The URL submitted
	$flickr_api_key = "352ee7XXXXXXXXXXXXXXXXXXXXXXXXXX"; //Our API Key
	
	$url = explode("/", $queryString); //Split the URL up into sections, delimited by the character '/'
	$photo_id = $url[5]; //The Photo ID is the 6th of these sections
	
} else { //The form was not submitted

};
?>

Structuring the Flickr API

After turning the contents of the photo id section into it's own variable, we now have everything we need to start the API call.

After searching the Flickr site a while, I found the flickr.photos.getInfo method - and judging by the example it displays, it looks to be exactly what we want. Notice we already have both of the required variables to make this call: $photo_id and $api_key.

Next, we need to find out what the correct call syntax that Flickr requires in order to get data back from their API. Luckily, they are nice enough to give us an example PHP call here. This test gives us the insight needed as to what an API call should be structured like:

http://www.flickr.com/services/rest/?method=flickr.test.echo&format=php_serial&api_key=eaab5c513e33c01544385641ff9af42f

After we modify their example to use the method flickr.photos.getInfo, we also need insert a new argument for the photo_id. Our newly structured API call now looks like this: (changes are in red)

http://www.flickr.com/services/rest/?method=flickr.photos.getInfo&format=php_serial&photo_id=$photo_id&api_key=$flickr_api_key

You can test the validity of our newly structured call by pasting it into any web browser's address bar. You will get back real data if it works, or errors when it fails.

Using the Data from the Flickr API

Once we get a working API call, we need to have our application read in the data that is returned. To import this data into our web app, we use the function file_get_contents, then re-format it using the unserialize function.

<?php 
if (isset($_POST['photo'])) { //The form was submitted, process the data
	$queryString=$_POST['photo']; //The URL submitted
	$flickr_api_key = "352ee7XXXXXXXXXXXXXXXXXXXXXXXXXX"; //Our API Key
	
	$url = explode("/", $queryString); //Split the URL up into sections, delimited by the character/
	$photo_id = $url[5]; //The Photo ID is the 6th of these sections
	
	$flickrrawoutput =  file_get_contents("http://flickr.com/services/rest/?method=flickr.photos.getInfo&photo_id=$photo_id&api_key=$flickr_api_key&format=php_serial");
	$flickroutput = unserialize($flickrrawoutput);
	
} else { //The form was not submitted

};
?>

Since all good coders do error checking, we also need to run a quick check to see if the API call returned no data (an error). We can do so with this simple line:

$status = $flickroutput['stat']; //Extracts the 'stat' value from the data returned

Now, with a second if-statement, we check to see the variable $status's value, and if it doesn't contain the word 'fail' then we know we made a successful call. Putting it all together, it looks like this:

<?php 
if (isset($_POST['photo'])) { //The form was submitted, process the data
	$queryString=$_POST['photo']; //The URL submitted
	$flickr_api_key = "352ee7XXXXXXXXXXXXXXXXXXXXXXXXXX"; //Our API Key
	
	$url = explode("/", $queryString); //Split the URL up into sections, delimited by the character/
	$photo_id = $url[5]; //The Photo ID is the 6th of these sections
	
	//Get the data from Flickr
	$flickrrawoutput =  file_get_contents("http://flickr.com/services/rest/?method=flickr.photos.getInfo&photo_id=$photo_id&api_key=$flickr_api_key&format=php_serial");
	$flickroutput = unserialize($flickrrawoutput); 
	
	$status = $flickroutput['stat']; //Extracts the 'stat' value from the data returned
	
	if ($status != 'fail') { //fetch from Flickr returned stats for photo
		
	} else { 
		echo "The supplied photo URL is wrong. Please <a href=\"#form\">try again</a>."; //A bad URL was entered into the form
	};
	
	
} else { //The form was not submitted

};
?>

Once we know we've made a successful API call, we need to extract the 'username' of the photo's owner. We do this with this line:

$flickr_user  = $flickroutput['photo']['owner']['username'];

… but this is sometimes not an easy thing to figure out. I have found the best way to find out what to extract is by analyzing the unserialized data we get back from Flickr. PHP allows us to look at the data in an easier to read format by using print_r.

print_r ($flickroutput)

This is probably the hardest part of using the API. If you insert the print_r command into your PHP document right after we unserialize the Flickr data, we can easily see the different levels of the data structure.

Hint: You can view the output of our print_r command here. The different tiers are highlighted in red.

The way our data extract works is 'photo' is the first level within the $flickroutput data. The next tier down is 'owner', which houses the last level called 'username' which holds the data we need. That's how we get $flickroutput['photo']['owner']['username'] — each [] is referencing it's own tier.

Output the Data to the Visitor

Once we have the $flickr_user variable set with this extract, we are ready to output our finished code. We will output it twice: One as an example "live" link, and the other will be the raw HTML code that the visitor can input into his or her site.

<?php 
if (isset($_POST['photo'])) { //The form was submitted, process the data
	$queryString=$_POST['photo']; //The URL submitted
	$flickr_api_key = "352ee7XXXXXXXXXXXXXXXXXXXXXXXXXX"; //Our API Key
	
	$url = explode("/", $queryString); //Split the URL up into sections, delimited by the character/
	$photo_id = $url[5]; //The Photo ID is the 6th of these sections
	
	//Get the data from Flickr
	$flickrrawoutput =  file_get_contents("http://flickr.com/services/rest/?method=flickr.photos.getInfo&photo_id=$photo_id&api_key=$flickr_api_key&format=php_serial");
	$flickroutput = unserialize($flickrrawoutput); 
	
	$status = $flickroutput['stat']; //Extracts the 'stat' value from the data returned
	
	if ($status != 'fail') { //fetch from Flickr returned stats for photo
		$flickr_user  = $flickroutput['photo']['owner']['username'];
	?>
	
	<p>Preview: </p>
	<cite>Photo Credit: <a href="<?php echo $queryString; ?>" title="Photo Credit: <?php echo $flickr_user; ?>"><?php echo $flickr_user; ?></a></cite></p>
	<p>HTML Code:</p>
	<pre>
		&lt;cite&gt;
			Photo Credit: &lt;a href=&quot;<?php echo $queryString; ?>&quot; title=&quot;Photo Credit: <?php echo $flickr_user; ?>&quot;&gt;<?php echo $flickr_user; ?>&lt;/a&gt;
		&lt;/cite&gt;
	</pre>
	
	<?php
	} else { 
		echo "The supplied photo URL is wrong. Please <a href=\"#form\">try again</a>."; //A bad URL was entered into the form
	};
	
	
} else { //The form was not submitted

};
?>

Putting it all Together

Now that we have the form and the PHP sections completed, we need to put it all together into an application page. You can download the example page here, or you can take a look at the working example I've put up.

Post a Comment (rss)





Pittsburgh Web Design - Cagintranet Web Design