PHP API Tutorials

How to Use Instagram API with PHP (and Node.js)

EDITED TO ADD: Due to the COVID-19 situation, the original EOL (End of Life) for the “basic” level access to the Instagram API has been delayed to June 2020.

“We understand these are challenging times for our developer community, so we are postponing disabling the Instagram Legacy API Platform by 90 days to June 29, 2020. Remaining endpoints on the Legacy API will no longer be available after this date and your app’s users may lose functionality.”

For more details and updates, keep an eye on the official Instagram Developer‘s website.


What can I do with PHP and APIs?

Let’s say you’re building a PHP application. You’d like to feature some content from Instagram that updates itself in real-time. You heard somewhere that anything real-time would be better suited for Node.js, but they don’t elaborate. Now it’s up to you to sort out the finer details in order to finalize the technical requirements to satisfy the project’s requirements.

End result? After your research, the project is now interested in building a PHP application that features “real-time” Instagram content. This application will use an API (application programming interface) that will communicate with Instagram via HTTP requests.

What would be the best way to achieve this using the Instagram API? The answer echos a common response in software engineering: it depends.

Prerequisites

Due to the particularly strict requirements to use the Instagram API, all development projects must be designed with clear use cases in mind. Examples may include:

  • Install a widget that needs to make API calls to Instagram
  • Display Instagram content on a personal website via API calls
  • One-off Project or POC that will make API calls to Instagram

However, this is somewhat of a trick question. If any of the above are true for you, Instagram considers your use case “invalid.”

Do not panic, however, because their suggestion is to leverage “sandbox mode” to accomplish your goal and leave it at that. It will display the last 20 posts associated with a particular user ID. No further laborious development is required on your side. Let’s be realistic – can you honestly think of a concrete example that the user would need more than the last 20 entries? “Real-time” content is by nature ephemeral. How much of the past do you really need to hold onto for your application?

Sandbox mode has evolved over time to address the reality that most projects fall into the above three buckets. Since security incidents are costly and ruin the integrity of the brand, Instagram understandably is a bit coy with giving developers any access beyond that. Additionally, it’s apropos to remind ourselves that Instagram was acquired by Facebook. The review processes for both have tightened up in direct response to intense public scrutiny that their API was insecure.

However, all Instagram API projects start from the same place: Instagram Sandbox Mode.

How do I Display Instagram Feeds in My PHP Website?

You will need to do a bit of homework in order to understand which snippets of code you will need to put in your website’s code. It’s best to follow their existing tutorial to find these required snippets. It includes pointers on optimizing this feed for both mobile and desktop browsers. It’s possible to leverage more than simply adding an Instagram feed display in your PHP application if you’re creative.

Instagram API Best Practices – Sandbox Mode

A best practice is to develop all applications in Instagram’s Sandbox mode. If this exercise illustrates that your project requires more functionality, you can formally engage with Instagram and be met with a higher chance of success. The time spent working in the sandbox mode will facilitate a focused dialog with their team. Instagram will certainly ask for evidence that the limitations of sandbox mode are not suitable for your project. This “homework” is worth the investment in order to facilitate a productive conversation with Instagram’s team. Since the review process can take upwards of two weeks before getting a response, preparation is critical for success.

In order to qualify to go “live,” your use case must be limited to “help[ing] individuals share their own content with 3rd party apps.” There are no other acceptable use cases.

“While in sandbox, your app has access to all permissions and you can generate access tokens with any scope for testing. To use these scopes in production though, your app needs to go through review and be approved for a given permission. The permissions your app can be approved for relate directly to the use case of your app.”

Assuming your application does meet the use case requirements, all approved applications have “basic” access by default. Any access beyond that would require a deeper review from the Instagram team. In short, there is a rigid review process to prepare for even for basic access. It is wise to fully review all of their documentation around passing the review process, especially in light of the changes to the API in 2020.

Before we jump deeper into that, however, let’s discuss this hypothetical project at a high level.

PHP v. Node.js? Why Not Both?

This discussion is covered in many blog posts throughout the internet. It is a common topic among web developers. Usually, a developer just picks one or the other depending on the project and their comfort level with the associated language.

The integration of both alongside one another is a separate beast entirely. When you integrate PHP with Node.js, you can provide real-time content using “live” data without needing to reload the entire page. Think of a news feed or dashboard that updates itself without any action required from its viewer. Instant messages, user activity streams, newsfeed tickers, games – all of this functionality can be created by integrating both PHP and Node.js so that the result is similar to other familiar platforms like EventMachine (Ruby) or Twisted (Python).

This is quite the departure from traditional PHP website architecture, which is typically running on Apache. A limitation of this back end architecture is that managing resource-intensive tasks in an elegant fashion is difficult. Integration with Node.js allows the developer to leverage an event-driven model that prevents resource-expensive tasks from consuming all available memory. Instead of a process blocking another, the Node approach allows the costly tasks to be run in the background while still servicing other requests. It’s a slick solution for bringing a typical PHP application to the next level of “streaming” content.

When designing this new kind of PHP application, it’s necessary to identify source data. Where can you get some source data that would be useful and consistently updated in “real-time”? Social media content is perfectly suited for this. You can leverage their API in order to push content to your application. In the case of Instagram, it would be a user’s profile, images, videos, and albums.

Quick HTTP Status Code Review

It’s a good idea to brush up on how to handle status codes in PHP. As a quick refresher, here is how HTTP response code requests typically look in PHP

http_response_code ([ int $response_code ] ) : mixed

Or, to elaborate.

<?php

// Get the current response code and set a new one
var_dump(http_response_code(404));

// Get the new response code
var_dump(http_response_code());
?>

And to remind ourselves of common return codes:

Code Number Meaning Description
200 OK Not an error code – success message
401 Error Unauthorized / Access Denied Error code – the user does not have permission to access the requested resource
404 Error Not Found Error code – requested resource not found
503 Error Server Unavailable Error code – the server is unavailable to process the request

Working With API Endpoints

We must also remind ourselves what API Endpoints are. We can identify endpoints in our code by the syntax they keep – URLs. When designing our applications to leverage endpoints, it’s helpful to remind ourselves that typically they are named after the functionality they provide. The best APIs have naming conventions that are self-explanatory by looking at them.

In our upcoming example using Hastagy API, that endpoint looks like the following:

https://hashtagy-generate-hashtags.p.rapidapi.com/v1/insta/tags

Gracefully Handling JSON API Responses with PHP

Oftentimes an endpoint will respond in JSON format. There are available built-in functions to handle JSON with PHP so that you can put values into objects, arrays, etc. If you have not worked with them before, they are named in a fairly straightforward manner:

  • json_encode();
  • json_decode();

There are also some built-in functions for error handling. It would be advisable to review the full documentation for additional examples.

How to Get Started Using Instagram API with PHP and Node.js

Our application, now identified as integration between PHP and Node.js, would like to incorporate Instagram content as part of its source content. Perhaps you have other sources as well, but this sprint of development is focused on Instagram. Let’s get started.

Requirements

  • Instagram User Account (Developer)
  • Sandbox User accounts
  • Access Token

How to get an API Key / Access Token

You must be logged onto Instagram while registering as a developer. A common mistake is to not realize you are logged onto a personal or another undesirable account. Be sure you are logged on using the account that is designated as the primary lead developer account for the application.

  1. Identify an Instagram account to be the developer’s account.
  2. Log onto that Instagram account.
  3. Register with Instagram as a Developer
  4. Obtain an access token.

Once you are registered, you are ready to start requesting data. All endpoints can be reached by the following URL. Be sure to replace ACCESS_TOKEN with the token gained in step 4.

https://api.instagram.com/v1/self/media/recent?access_token=ACCESS_TOKEN

If you need to dive deeper, Facebook has very detailed guides for its business and consumer APIs.

Example Using Instagram API w/ PHP & Node.js

For this example, we’re going to assume our application would like to leverage the Hashtagy API from RapidAPI.

This Instagram API uses the “keyword” parameter in order to pull hashtags associated with that particular keyword. It’s good for situations where the user might not be sure which hashtags would make sense for their particular topic. Imagine that your application has some sort of picker that allows you to then pull known in-use Instagram hashtags.  For the sake of this example, the keyword we want to generate hashtags is “pineapple.”

The URL used to contact endpoints looks as follows with that parameter:

https://hashtagy-generate-hashtags.p.rapidapi.com/v1/custom_1/tags?keyword=pineapple

Depending on your particular project, you can grab either the Node.js code snippet or the PHP one to provide that functionality in the app. Here are some examples provided by Hashtagy using our pineapple keyword.

Node.js

var unirest = require("unirest");

var req = unirest("GET", "https://hashtagy-generate-hashtags.p.rapidapi.com/v1/custom_1/tags");

req.query({
  "keyword": "pineapple"
});

req.headers({
  "x-rapidapi-host": "hashtagy-generate-hashtags.p.rapidapi.com",
  "x-rapidapi-key": "SIGN-UP-FOR-KEY"
});


req.end(function (res) {
  if (res.error) throw new Error(res.error);

  console.log(res.body);
});

PHP (curl)

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://hashtagy-generate-hashtags.p.rapidapi.com/v1/custom_1/tags?keyword=pineapple",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "x-rapidapi-host: hashtagy-generate-hashtags.p.rapidapi.com",
    "x-rapidapi-key: SIGN-UP-FOR-KEY"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

An example 200 response to this literal request returns 45 distinct hashtags it considers related to the keyword pineapple. It’s helpful to use RapidAPI’s built-in tools to fully understand how to best integrate it into your PHP application. This preview allows you to inspect what the returned data looks like. It also allows you to inspect what additional information you can glean for your application when you pull those requests. For example, by looking at this example response, I may decide to add some logic to handle responses that have more than 30 distinct hashtags (such as calculate displaying only the first 10 in the UI unless expanded).

Conclusion

Most use cases for incorporating real-time content from Instagram can be satisfied by using sandbox mode. If your goal is to simply display your Instagram feed on a website, sandbox mode should be sufficient for your needs. Instagram has infamously tight requirements to use its API in an application. All apps developed with their API must undergo a review process. The official Instagram documentation cautions developers that the review process may take upwards of a week. You must register with them as a developer and describe your intent behind its use. Their documentation even specifies that this process must be done while logged onto your mobile Instagram account. You must submit a compelling case of why the sandbox mode is not sufficient for your needs while simultaneously illustrating how it meets the requirements defined by Instagram.

5/5 - (2 votes)

View Comments

  • Very interesting blog about how to use the Instagram API with PHP.
    it is useful & informative blog .Thank You for sharing blog keep it up!

  • Part of the article describes how it's beneficial to combine PHP with Node.js. And then... the topic trails off. Two examples are given, achieving the same end result, in PHP and in Node... so where's the combining going on?

Share
Published by

Recent Posts

Power Up Your Enterprise Hub: New March Release Boosts Admin Capabilities and Streamlines Integrations

We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…

2 weeks ago

Unveiling User Intent: How Search Term Insights Can Empower Your Enterprise API Hub

Are you curious about what your API consumers are searching for? Is your Hub effectively…

2 weeks ago

Rapid Enterprise API Hub Levels Up Custom Branding, Monetization, and Management in February Release

The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…

4 weeks ago

Supercharge Your Enterprise Hub with January’s Release: Search Insights, Login Flexibility, and More!

This January's release brings exciting features and improvements designed to empower you and your developers.…

3 months ago

Enhanced Functionality and Improved User Experience with the Rapid API Enterprise Hub November 2023 Release

Rapid API is committed to providing its users with the best possible experience, and the…

5 months ago

The Power of Supporting Multiple API Gateways in an API Marketplace Platform

In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…

6 months ago