CakePHP: Fetch your Instagram media

Instagram is a very popular photo sharing application. People can capture/upload images and share them easily. It provides an API platform to build non-automated, authentic, high-quality apps and services.

In this article, we will learn how to fetch media from an authenticated Instagram account in our CakePHP 3 application.

To interact with Instagram API Platform, we will use Instagram Plugin for CakePHP.

Let’s start!

Setup app and configure plugin

To start with, create a blank CakePHP project using Composer. Please refer to documentation for details on installation. Once it is installed, we are good to go!

Let’s assume our new application is accessible at http://localhost/instacake.

Now, install the plugin using composer.

Load the plugin into our application,

Basic things are now ready.

This plugin provides a Utility class to connect with Instagram APIs. Instagram API uses the OAuth 2.0 protocol and requires access_token for all authenticated requests.

We simply need to create an instance of this class and perform API calls. Here, we need client id and client secret of our Instagram application. If you have not created it, please create it first from here and get client id and secret.

First of all, let’s create a configuration variable with client id, secret and redirect url and write it with name Instagram.config.

You can write above configuration in your bootstrap.php or in your AppController.

Now, you can use the Utility class wherever neeeded as below.

Authorize User

Instagram API requires access_token in request to make authorized API calls. To get an this access token, you need to redirect user to Instagram authentication URL. This plugin provides a Helper to generate authentication URL for your user. Load the Instagram helper in your application and use it’s getAuthUrl() method to generate URL.

In your AppView,

In your template,

This will build an authentication URL, and user will be redirected to this for authorization. On successful authorization by user, Instagram will redirect back to your specified redirect uri with code. Using that code, we need to get our access token.

So, in our controller’s action (which is used to handle redirect url), we can get access token using getAccessToken() method of utility class. See example,

You can store this token into your database for future use and make authenticated API calls.

Once you get the token, you can set it into Instagram client class using accessToken() method and make calls.

Fetch media

So, we have access token of authorized user and we can now make API calls to fetch media from Instagram. It provides a method getMedia() to fetch media. See example,

This will return last 20 media from particular user’s Instagram account.

That is it.


This plugin provides some other API methods as well. Please refer to its repository for more details here –

You may also like...