SpyreStudios

Web Design and Development Magazine

  • Design
  • Resources
  • Showcase
  • Inspirational
  • Tutorials
  • CSS
  • Resources
  • Tools
  • UX
  • More
    • Mobile
    • Usability
    • HTML5
    • Business
    • Freebies
    • Giveaway
    • About SpyreStudios
    • Advertise On SpyreStudios
    • Get In Touch With Us

Connecting with API Data from Instagr.am using PHP

January 4, 2012 by Jake Rocheleau

The process of connecting into API data via OAuth is tricky. Some of the more notable social networks which have adopted this technology include Foursquare, Twitter, and Facebook. But Instagram is a very popular mobile app which has grown tremendously fast. Their recent API v1.0 release has some really neat features where you can pull popular photos, recent users, follower lists, and a whole bunch more.

Instagram Homemade Graham Crackers Cookies

I don’t want to overwhelm anyone by offering too much information in a single tutorial. Thus I’ve broken this process into segments where the final script will output some user profile data from your Instagram account via OAuth connection. For an example you can try to login yourself or check out my screenshot at the bottom of this article.

Setting Up the Library

It’s a whole lot easier to work with API data when you have a library set and ready. The Instagram PHP API on Github is fantastic for beginners to start with. It’s the only repo by user macuenca and he’s great with support questions – I also recommend Stack Overflow if you’re having other troubles.

Simply download his code and unzip to reveal the files. We only meed to use 2 specifically named CurlHttpClient.php and Instagram.php. Curl is a code library used to pull JSON data from an HTTP request and is integrated right into PHP. The Instagram.php script is mostly config and custom functions related to the API. If you want to get an idea for how this all ties together check out the included example.php script which displays the most popular recent photos.

Before we jump into PHP we need to setup an application with Instagram’s developer center. Hit this page and signup for an account if you haven’t already. Once logged in as a developer you can manage different applications and find your client ID and Secret keys.

Web API Keys

This concept is a bit difficult to wrap your head around the first time. Basically you need to present 2 distinct keys to Instagram with every authorization request. The ID is generally public and included right within the authorization URL.

[html wraplines=”false”]https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URL&response_type=code

[/html]

Now the Secret key is still needed at some point in your code, but this isn’t openly displayed to your visitors. Just realize that you need both of these codes for Instagram to authorize your application. The final parameter which requires configuration is the callback URL. After Instagram authorizes a user login it will respond with a code for building an access token. This token code is sent to whichever callback URL you input.

Manage Instagram API Clients

Access Tokens are similar to cookies or session variables which hold your user’s current account login. In our example scenario I’m using the script http://spyrestudios.com/demos/instagram-api/instagammy.php as a callback method. Please notice you do need some type of web server to test this out on – even if you’re running through localhost.

Configure the Login Page

There are two scripts we will focus on – the login authorization followed by our instagammy.php callback. For the login page I’ve simply used index.php but you could rename this to anything. I’ll walk through the important sections of this page below.

[php wraplines=”false”]require_once ‘Instagram.php’;

/**
* Configuration params, make sure to write exactly the ones
* instagram provide you at http://instagr.am/developer/
*/
$config = array(
‘client_id’ => ‘f0d225aa955c4bd9ae563f87f831efab’,
‘client_secret’ => ‘377b77afc1274a89bd2df7d77e934689’,
‘grant_type’ => ‘authorization_code’,
‘redirect_uri’ => ‘http://spyrestudios.com/demos/instagram-api/instagammy.php’,
);
[/php]

We first need to include our Instagram.php script which does all the backend API handling for us. Be sure you also have the Curl script I mentioned earlier and place all these files within the same directory. You’ll additionally notice a $config array with 4 values – Client ID, Secret, Grant Type, and Callback URL. Grant type should almost always be set to authorization_code by default, as this is how Instagram will process the login data.

All the other 3 variables you should pull from your Instagram client page. These three values will be very important over the course of your API development. Keep in mind you can create and manage dozens of Instagram API clients – but please be reasonable with the OAuth calls!

[php wraplines=”false”]/**
* This is how a wrong response looks like
* array(1) { ["InstagramOAuthToken"]=> string(89) "{"code": 400, "error_type": "OAuthException", "error_message": "No matching code found."}" }
*/
session_start();
if (isset($_SESSION[‘InstagramAccessToken’]) && !empty($_SESSION[‘InstagramAccessToken’])) {
header(‘Location: /index.php’);
die();
}

// Instantiate the API handler object
$instagram = new Instagram($config);
$instagram->openAuthorizationUrl();
[/php]

In the latter portion of our script we check for an InstagramAccessToken. If any value is found this means we have a user currently authorized and we redirect them to our home page. Otherwise we need to re-direct them to Instagram so the user may login.

Instagram login OAuth page

This is the best part of using a pre-built code library so we don’t need to make every call from scratch. Simply initialize a new Instagram class and use $instagram->openAuthorizationUrl(); to automatically re-direct. The Instagram.php library uses your configuration variables to create a unique authorization URL for each user.

Building the API Output

The output page in our scenario is the same as our callback script. I’ve used the name instagammy.php but you can use anything you’d like. Let’s examine the header to this script before we jump into content.

[php wraplines=”false”]session_start();
require_once ‘Instagram.php’;
/**
* Configuration params, make sure to write exactly the ones
* instagram provide you at http://instagr.am/developer/
*/
$config = array(
‘client_id’ => ‘f0d225aa955c4bd9ae563f87f831efab’, // Your client id
‘client_secret’ => ‘377b77afc1274a89bd2df7d77e934689’, // Your client secret
‘grant_type’ => ‘authorization_code’,
‘redirect_uri’ => ‘http://spyrestudios.com/demos/instagram-api/instagammy.php’, // The redirect URI you provided when signed up for the service
);
[/php]

We need to keep the session alive so our user authorization call isn’t lost. Thus we also need a copy of the configuration details for your specific app. If you feel it’s easier to include this from a separate file you could create something like app-config.php to setup the array. You can then use another include statement directly under Instagram.php.

Now that the user is (hopefully) authorized we are looking to display some of their profile info. We need to give them an Access Token which represents this specific account login. Additionally we can store this into our PHP session to offer as a parameter later on.

[php wraplines=”false”]$instagram = new Instagram($config);
$accessToken = $instagram->getAccessToken();
$_SESSION[‘InstagramAccessToken’] = $accessToken;

$instagram->setAccessToken($_SESSION[‘InstagramAccessToken’]);
$userinfo = $instagram->getUser($_SESSION[‘InstagramAccessToken’]);

// After getting the response, let’s iterate the payload
$ures = json_decode($userinfo, true);
[/php]

The function getUser() can be found inside our Instagram.php library. This takes in a single token and returns a JSON string via HTTP. We then use the PHP function json_decode() converting our return data into an array. This content is stored within the variable $ures which stands for user results.

Dumping Output Data

The Instagram API is fairly well documented compared to other apps. But it can take so long to go through all of their pages looking for a specific answer. When we have the data stored in PHP it’s just easier to use var_dump() to pull out associative array labels.

All the info we need is held inside of a sub-array labeled “data”. So for example, to pull your profile picture URL you need to echo $ures[‘data’][‘profile_picture’]. Similarly $ures[‘data’][‘username’] outputs your username. Check out my code below which is included in the body of instagammy.php:

[php wraplines=”false”]<div class="myuser">
<strong><?= $ures[‘data’][‘username’] ?>(<?= $ures[‘data’][‘full_name’] ?>)</strong> – <img src="<?= $ures[‘data’][‘profile_picture’] ?>" />
<p><a href="<?= $ures[‘data’][‘website’] ?>"><?= $ures[‘data’][‘website’] ?></a></p>
<ul>
<li>Total Photos: <?= $ures[‘data’][‘counts’][‘media’] ?></li>
<li>Following: <?= $ures[‘data’][‘counts’][‘follows’] ?></li>
<li>Followers: <?= $ures[‘data’][‘counts’][‘followed_by’] ?></li>
<li>User ID: <?= $ures[‘data’][‘id’] ?></li>
</ul>
</div>
[/php]

A lot of the variable names should be self-explanatory. Using the var_dump() function you’ll also get a visual representation so you can follow along with my train of thought. One thing to point out is within the counts array we have 3 more values – total number of photos, users you follow, and your followers. These are represented in the unordered list by media, follows, and followed_by. You can see in the associative array we’re going 3 levels deep to pull out this data, which is how Instagram returns the results by default.

Live Demo – Download Source Code

Conclusion

This is just one example of the many things you can do with Instagram’s new API functionality. Inside the Instagram.php file you’ll find a lot of custom functions with well-crafted comments to explain their purpose. Spend a bit of time going through here to see if you can perform any other cool functionality. Also check throughout Google if you get lost as there are dozens of resources available for API development using this exact library.

Filed Under: PHP Tagged With: API, Instagram, OAuth, tutorial

Recent Posts

  • 31 Fresh Design Elements for Spring and Easter
  • 10 Templates for Music Concert Flyers
  • How to Build a Web Scraper Using Node.js
  • Best PHP Books, Courses and Tutorials in 2022
  • How to Get Your First Web Design Client

Archives

  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • July 2019
  • June 2019
  • May 2019
  • April 2019
  • March 2019
  • February 2019
  • January 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • January 2018
  • December 2017
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • July 2017
  • June 2017
  • May 2017
  • April 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • February 2016
  • January 2016
  • December 2015
  • November 2015
  • October 2015
  • September 2015
  • August 2015
  • July 2015
  • June 2015
  • May 2015
  • April 2015
  • March 2015
  • February 2015
  • January 2015
  • December 2014
  • November 2014
  • October 2014
  • September 2014
  • August 2014
  • July 2014
  • June 2014
  • May 2014
  • April 2014
  • March 2014
  • February 2014
  • January 2014
  • December 2013
  • November 2013
  • October 2013
  • September 2013
  • August 2013
  • July 2013
  • June 2013
  • May 2013
  • April 2013
  • March 2013
  • February 2013
  • January 2013
  • December 2012
  • November 2012
  • October 2012
  • September 2012
  • August 2012
  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
  • March 2010
  • February 2010
  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • May 2008
  • April 2008

Categories

  • Accessibility
  • Android
  • Apps
  • Art
  • Article
  • Blogging
  • Books
  • Bootstrap
  • Business
  • CSS
  • Design
  • Development
  • Ecommerce
  • Fireworks
  • Flash
  • Freebies
  • Freelance
  • General
  • Giveaway
  • Graphic Design
  • HTML5
  • Icons
  • Illustrator
  • InDesign
  • Infographics
  • Inspirational
  • Interview
  • Jobs
  • jQuery
  • Learning
  • Logos
  • Matrix
  • Minimalism
  • Mobile
  • Motion Graphics
  • Music
  • News
  • Photoshop
  • PHP
  • Promoted
  • Rails
  • Resources
  • Showcase
  • Tools
  • Tutorial
  • Twitter
  • Typography
  • Uncategorized
  • Usability
  • UX
  • Wallpapers
  • Wireframing
  • WordPress
  • Work

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

SpyreStudios © 2022