Using Instagram’s API to Create an Image Gallery


I’ve been taking a lot of Instagram photos lately, and it occurred to me that maybe I want to display a gallery of these images outside of the app. I realize that Instagram is accessible from desktop computers, but I want people to be able to see my images on my site, without being authenticated through Instagram.

So, to solve this problem, I dived into the Instagram API. It seems pretty straight forward, and I came up with a pretty cool example. I came up with an example that displays all my Instagram thumbnails and when you click on them, displays the large, original image in a jQuery lightbox.

Instagram Gallery Example

View Demo

Let’s dive into some code to see how I accomplished this.


First, let’s look at the PHP needed to make the API call and return the image paths. In order to accomplish this for yourself, you’ll need to retrieve your Instagram User ID and generate an Access Token. Directions can be found on Instagram’s Developer page on Authentication.

$userid = "USER-ID-GOES-HERE";
$accessToken = "ACCES-TOKEN-GOES-HERE";
$url = "{$userid}/media/recent/?access_token={$accessToken}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
$result = json_decode($result);

Essentially, all we’re doing is building our API call and using PHP’s CURL library to make our requests. The $resultvariable will store a JSON string with all the data we need.

HTML + PHP Variables

Now let’s build our page. Go ahead and style the page however you’d like, and choose a suitable jQuery (or otherwise) gallery/slider plugin.

<?php foreach ($result->data as $post): ?>
	<a class="fancybox" href="<?php echo $post->images->standard_resolution->url ?>" data-fancybox-group="gallery" title="<?php echo $post->caption->text ?>"><img src="<?php echo $post->images->thumbnail->url ?>" alt="<?php echo $post->caption->text ?>" /></a>
<?php endforeach ?>

That’s really all there is to it – not a lot going on. All we’re really doing here is looping through each object and pulling out the thumbnail URL, the large image URL, and the caption.

The images that are shown on the page will always be the most up-to-date images you have posted to your Instagram account. You could choose to cache the page, rather than making the API call every time the page loads – Instagram rate limits the number of API calls you can make to 5000/hour, so if you have a site that gets a lot of traffic caching may be a requirement.