Connecting with API Data from Instagr.am using PHP




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.

https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URL&response_type=code

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.

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',
     );

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!

/**
 * 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();

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.

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
     );

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.

$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);

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:

<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>

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 DemoDownload 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.





About the author:

Jake is a creative designer, illustrator, and web developer. He frequently writes articles involving new-age design concepts and freelance management skills. You can find him in Google or follow his tweets @jakerocheleau

Comments:

Scroll back to the top