How to Use Instagram Basic Display API: A Comprehensive Guide

The Instagram Basic Display API enables developers to integrate Instagram content into applications, allowing access to user profiles and media. This guide details setting up the API, managing access tokens, and making requests, providing essential knowledge for effective Instagram integration before its deprecation.

Table of Content

Instagram has become a powerhouse for businesses and individuals alike. The Instagram Basic Display API opens up new possibilities for developers to integrate Instagram content into their applications. This powerful tool allows access to user profiles, media, and basic account information, enabling the creation of innovative and engaging experiences for users.

The Instagram Basic Display API has a significant impact on how developers interact with Instagram's platform. This guide will walk you through the process of setting up the API, obtaining access tokens, and making API requests. We'll also explore how to implement the API in your application, providing you with the knowledge to leverage Instagram's features effectively. By the end of this guide, you'll be well-equipped to use the Instagram Basic Display API and enhance your projects with Instagram integration.

Setting Up Your Instagram Basic Display API

To begin using the Instagram Basic Display API, you need to set up your environment correctly. This process involves creating a Facebook app, configuring the Instagram Basic Display settings, and adding an Instagram test user. Let's break down these steps to get you started.

Creating a Facebook App

The first step is to create a Facebook app, which is necessary to access Instagram's features. Here's how to do it:

  1. Go to developers.facebook.com and click on "My Apps."
  2. Click the "Create App" button.
  3. Choose "Consumer" as the app type and click "Next."
  4. Give your app a name, such as "Instagram Basic Display App."
  5. Enter your contact email and select a business manager account if you have one.
  6. Click "Create App" to finalize the process.

After creating your app, you'll need to configure some basic settings:

  1. Navigate to "Settings" > "Basic" in the left sidebar.
  2. Scroll down and click "Add Platform."
  3. Choose "Website" and enter your website's URL.
  4. Select a category for your app (e.g., Education).
  5. Add an app icon to personalize your application.
  6. Save your changes.

Configuring Instagram Basic Display

Now that you have a Facebook app, it's time to add the Instagram Basic Display product:

  1. In the left navigation bar, click on "Products."
  2. Find "Instagram Basic Display" and click "Set Up."
  3. Once added, click on "Basic Display" under the Instagram product.
  4. Scroll down and click "Create New App."
  5. Keep the display name as is and click "Create App."

After creating the Instagram app, you'll see important information such as your App ID and App Secret. Keep these secure, as you'll need them later.

Next, configure the necessary URLs:

  1. Scroll down to "Valid OAuth Redirect URIs."
  2. Enter the URL where users will be redirected after authentication.
  3. Fill in the Deauthorize Callback URL and Data Deletion Request URL with your website's address for now.

Adding an Instagram Test User

To test your app's functionality, you need to add yourself as an Instagram test user:

  1. Expand the "Roles" section in the left sidebar and click "Roles."
  2. Scroll down to the "Instagram Testers" section.
  3. Click "Add Instagram Testers."
  4. Enter your Instagram username and submit the invitation.

To accept the invitation:

  1. Log into your Instagram account on www.instagram.com.
  2. Go to your profile and click "Edit Profile."
  3. Navigate to "Apps and Websites" > "Tester Invites."
  4. Find your app's invitation and click "Accept."

After accepting, your Instagram account becomes eligible for testing your app while it's in Development Mode.

Remember, the Instagram Basic Display API is set to be deprecated on December 4, 2024. It's recommended to plan for migrating to the newer Instagram API to ensure your services continue without disruption.

By following these steps, you've successfully set up your Instagram Basic Display API environment. You now have a Facebook app with Instagram Basic Display configured and a test user added. This setup allows you to start developing and testing your application's integration with Instagram's features.

In the next sections, we'll explore how to obtain access tokens and make API requests using this setup. These steps will enable you to retrieve user profiles, media, and other basic account information, opening up possibilities for creating engaging Instagram-integrated experiences in your applications.

Obtaining Access Tokens

Access tokens are crucial for authenticating requests to the Instagram Basic Display API. These tokens allow your application to interact with Instagram's platform on behalf of a user. There are two types of access tokens: short-lived and long-lived. Let's explore how to obtain and manage these tokens effectively.

Generating a Short-Lived Token

To begin, you'll need to generate a short-lived access token. This token is valid for one hour and serves as the starting point for accessing Instagram's features. Here's how to obtain a short-lived token:

  1. Navigate to the Basic Display section of your Facebook app dashboard.
  2. Scroll down to the User Token Generator section and click the "Generate Token" button.
  3. You may need to log in to your Instagram account again to grant specific permissions.
  4. Once generated, a pop-up window will display your access token. Copy this token for immediate use.

The short-lived token is obtained through an authorization process. Your app redirects the user to Instagram's authorization window:

https://api.instagram.com/oauth/authorize
?client_id={instagram-app-id}
&redirect_uri={redirect-uri}
&scope={scope}
&response_type=code

After the user grants permission, Instagram redirects them back to your specified redirect URI with an authorization code. This code is valid for one hour and can only be used once.

To exchange the authorization code for a short-lived token, send a POST request to:

POST https://api.instagram.com/oauth/access_token

Include the following parameters in your request body:

  • client_id
  • client_secret
  • granttype (set to "authorizationcode")
  • redirect_uri
  • code (the authorization code you received)

If successful, the API will respond with a JSON payload containing the short-lived access token and user ID:

{
 "access_token": "IGQVJ...",
 "user_id": 17841405793187218
}

Exchanging for a Long-Lived Token

While short-lived tokens are useful, they expire quickly. For more extended access, you'll want to exchange your short-lived token for a long-lived token. Long-lived tokens are valid for 60 days and can be refreshed before they expire.

To exchange your short-lived token for a long-lived one, send a GET request to:

https://graph.instagram.com/access_token
?grant_type=ig_exchange_token
&client_secret={instagram-app-secret}
&access_token={short-lived-access-token}

Replace {instagram-app-secret} with your app's secret and {short-lived-access-token} with the token you just obtained.

If successful, the API will respond with a JSON payload containing the long-lived access token:

{
 "access_token": "{long-lived-user-access-token}",
 "token_type": "bearer",
 "expires_in": 5183944
}

The "expires_in" field indicates the number of seconds until the token expires (approximately 60 days).

It's important to note that this request must be made server-side to protect your app secret. Once you have the long-lived token, you can use it in server-side requests or send it to the client for use there.

To keep your long-lived token valid, you should refresh it before it expires. You can refresh a long-lived token as long as it's at least 24 hours old but hasn't expired. To refresh the token, send a GET request to:

https://graph.instagram.com/refresh_access_token
?grant_type=ig_refresh_token
&access_token={long-lived-access-token}

Refreshing the token resets its expiration to 60 days from the refresh date. Remember that tokens not refreshed within 60 days will expire and can no longer be refreshed.

By following these steps, you'll be able to obtain and manage access tokens for the Instagram Basic Display API effectively. These tokens are essential for making authenticated requests and accessing user data through the API. In the next section, we'll explore how to use these tokens to make API requests and retrieve Instagram content for your application.

Making API Requests

Now that you have obtained the necessary access tokens, it's time to start making API requests to retrieve data from Instagram. The Instagram Basic Display API allows you to access user profiles and media content. Let's explore how to use the API endpoints effectively.

User Profile Endpoint

To get an Instagram user's profile information, you can use the User Profile endpoint. This endpoint provides basic details about the user's account. Here's how to make a request:

  1. Send a GET request to the following URL: https://graph.instagram.com/me?fields=id,username&access_token={access-token}
  2. Replace {access-token} with your long-lived access token.
  3. The API will respond with a JSON payload containing the user's ID and username:

  {
    "id": "17841405793187218",
    "username": "example_user"
  }

You can customize the fields parameter to request additional information such as account type and media count. For example: fields=id,username,account_type,media_count

User Media Endpoint

To retrieve a user's media content, including images, videos, and albums, you can use the User Media endpoint. This endpoint allows you to access the user's posts and related information. Here's how to make a request:

  1. Send a GET request to the following URL: https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,permalink,thumbnail_url,timestamp&access_token={access-token}
  2. Replace {access-token} with your long-lived access token.
  3. The API will respond with a JSON payload containing a list of media items:

  {
    "data": [
      {
        "id": "17895695668004550",
        "caption": "Beautiful sunset!",
        "media_type": "IMAGE",
        "media_url": "https://scontent.cdninstagram.com/v/t51.29350-15/123456789_123456789_n.jpg",
        "permalink": "https://www.instagram.com/p/ABC123/",
        "timestamp": "2023-05-01T18:30:00+0000"
      },
      // More media items...
    ],
    "paging": {
      "cursors": {
        "before": "QVFIUjNfZADJoZD",
        "after": "QVFIUmFfZADJoZD"
      },
      "next": "https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,permalink,thumbnail_url,timestamp&access_token={access-token}&after=QVFIUmFfZADJoZD"
    }
  }

The response includes various details about each media item, such as its ID, caption, media type, URL, and timestamp.

Pagination

When dealing with large amounts of data, the Instagram Basic Display API uses cursor-based pagination to manage the results. This allows you to retrieve data in smaller, more manageable chunks. Here's how pagination works:

  1. In the initial API response, you'll receive a paging object containing cursors and a next URL.
  2. To get the next page of results, use the next URL provided in the response. This URL includes the necessary cursor information.
  3. Continue making requests using the next URL until you reach the end of the data set, indicated by the absence of a next URL in the response.
  4. To navigate to previous pages, use the before cursor provided in the cursors object.

Example of using pagination:

  1. Make the initial request to retrieve media items.
  2. Check if there's a next URL in the paging object of the response.
  3. If a next URL exists, make another request using that URL to get the next page of results.
  4. Repeat steps 2-3 until there's no next URL, indicating you've reached the end of the data set.

By using pagination, you can efficiently retrieve large amounts of data without overwhelming your application or hitting API rate limits. Remember to handle pagination properly in your code to ensure you retrieve all the desired data.

Implementing the API in Your Application

Now that you have a solid understanding of how to set up the Instagram Basic Display API and obtain access tokens, it's time to implement the API in your application. This section will guide you through the process of integrating the API into your project, providing sample code, best practices, and error handling techniques.

Sample Code

To get started with implementing the Instagram Basic Display API in your application, you'll need to make HTTP requests to the API endpoints. Here's a basic example using Python and the requests library:

import requests

access_token = 'YOUR_ACCESS_TOKEN'
user_id = 'YOUR_USER_ID'

# Fetch user profile information
profile_url = f'https://graph.instagram.com/{user_id}?fields=id,username&access_token={access_token}'
profile_response = requests.get(profile_url)
profile_data = profile_response.json()

print(f"Username: {profile_data['username']}")

# Fetch user's media
media_url = f'https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,permalink,thumbnail_url,timestamp&access_token={access_token}'
media_response = requests.get(media_url)
media_data = media_response.json()

for item in media_data['data']:
   print(f"Media ID: {item['id']}")
   print(f"Caption: {item.get('caption', 'No caption')}")
   print(f"Media Type: {item['media_type']}")
   print(f"Media URL: {item['media_url']}")
   print("---")

This sample code demonstrates how to fetch a user's profile information and recent media items using the Instagram Basic Display API. You can expand on this code to build more complex features in your application.

Best Practices

When implementing the Instagram Basic Display API in your application, it's important to follow these best practices:

  1. Token Management: Store access tokens securely and implement a mechanism to refresh long-lived tokens before they expire. This ensures uninterrupted access to the API.
  2. Rate Limiting: Be mindful of the API's rate limits. Implement proper error handling and backoff strategies to avoid exceeding these limits and getting your application blocked.
  3. Caching: To reduce API calls and improve performance, cache API responses when appropriate. This is particularly useful for data that doesn't change frequently, such as user profiles.
  4. Pagination: When fetching large amounts of data, use the pagination features provided by the API. This allows you to retrieve data in smaller, more manageable chunks.
  5. Error Logging: Implement comprehensive error logging to track and diagnose issues with API requests. This will help you identify and resolve problems quickly.
  6. User Consent: Always obtain proper user consent before accessing their Instagram data. Clearly communicate what data you'll be accessing and how it will be used.
  7. Keep Up with Changes: Stay informed about updates to the Instagram Basic Display API. Meta frequently updates its APIs, and it's crucial to adapt your application accordingly.

Error Handling

Proper error handling is crucial when working with external APIs. The Instagram Basic Display API may return various error responses, and your application should be prepared to handle them gracefully. Here's an example of how to implement basic error handling:

import requests

def make_api_request(url):
   try:
       response = requests.get(url)
       response.raise_for_status()  # Raises an HTTPError for bad responses
       return response.json()
   except requests.exceptions.HTTPError as http_err:
       print(f"HTTP error occurred: {http_err}")
       # Handle specific HTTP errors (e.g., 404, 500)
   except requests.exceptions.ConnectionError as conn_err:
       print(f"Error connecting: {conn_err}")
       # Handle connection errors
   except requests.exceptions.Timeout as timeout_err:
       print(f"Timeout error: {timeout_err}")
       # Handle timeout errors
   except requests.exceptions.RequestException as req_err:
       print(f"An error occurred: {req_err}")
       # Handle any other requests-related errors
   return None

# Usage
access_token = 'YOUR_ACCESS_TOKEN'
user_id = 'YOUR_USER_ID'
profile_url = f'https://graph.instagram.com/{user_id}?fields=id,username&access_token={access_token}'

profile_data = make_api_request(profile_url)
if profile_data:
   print(f"Username: {profile_data['username']}")
else:
   print("Failed to fetch profile data")

This error handling approach allows you to gracefully manage different types of errors that may occur when making API requests. You can expand on this to include more specific error handling based on the API's error responses.

Remember that the Instagram Basic Display API is set to be deprecated on December 4, 2024. It's crucial to plan for migrating your application to the newer Instagram API to ensure continuity of service. Keep an eye on Meta's developer documentation for updates and migration guides.

By following these implementation guidelines, best practices, and error handling techniques, you'll be well-equipped to integrate the Instagram Basic Display API into your application effectively. This will allow you to create engaging experiences for your users while maintaining a robust and reliable integration with Instagram's platform.

Phyllo: Unlocking Instagram Data

At Phyllo, we understand the importance of harnessing social media insights to drive effective marketing strategies. Our platform provides seamless access to creator data, enabling businesses to leverage Instagram content for their campaigns. With Phyllo, you can easily integrate Instagram data, analyze performance metrics, and connect with influencers.

Our tools are designed to empower brands and marketers to make data-driven decisions and optimize their influencer partnerships. Explore how Phyllo can elevate your Instagram marketing strategy today!

Schedule a demo

Download our detailed guide on how to leverage Instagram Stories for influencer marketing

Download Now
Shubham Tiwari

Be the first to get insights and updates from Phyllo. Subscribe to our blog.

Ready to get started?

Sign up to get API keys or request us for a demo

/*