Instagram API with Python

You're in good company

RapidAPI has a strong developer community with over a million developers and a growing list of enterprise customers.

Extremely fast and simple API

One simple endpoint to extract media from a URL

Extract Media

Extract and download media from Instagram and Facebook

images & videos

Grab photos or videos from a Facebook or IG page

Simple & Cheap

Completely free to use

Choose the perfect plan

RapidAPI partners directly with API providers to give you no-fuss, transparent pricing. Find a plan that best matches the scale you need for your application.



Per month

For individuals who just want the essentials to get started quickly



Per month

For professionals who require more volume for their application

Instagram API

Using the API with Python

The Instagram API is available to consume in the following Python SDK code snippets:

  • http.client
  • Requests
  • Unirest

Simply pick your preferred Python Code Snippet from the dropdown, install the SDK, and add the code snippet to your website or application.

Instagram Facebook Media Downloader API

API Stats

0 /10
Popularity Score
1 ms
0 %
Success Rate

One dashboard to track them all

Call volume and billing

Monitor call volumes and corresponding billing charges for all APIs in one dashboard.

Errors and Latency

Ensure your app’s uptime by keeping track of API errors and trends in latency.

Logs for your API calls

Debug faster by searching and viewing logs for your API calls.

Table of Contents

Instagram is a great way to share images and short videos with your friends.  But it is designed for use on a phone.  How can we capture Instagram feeds and put them on our website?  If Python is not your preference you can read about how to use the Instagram API using PHP and Node.js.  But if Python is your jam, follow along and you can learn about using Instagram API with Python.

I recently helped create a site for running virtual gymnastics competitions. I thought it would be fun to see what people had posted on Instagram about their experience.  We instructed people to use a specific tag for their YouTube video entries. We gave no direction about Instagram.  In this article, we go through a process that allows us to pull a list of Instagram posts. The resulting posts use a specific hashtag.  This list then populates an HTML file that shows in an iframe or widget on another site.

The following list is a summary of the process we will follow:

View the Best Instagram APIs List

A Five-Step Process

  1. Make sure you have python installed on your server
  2. Get an API Key
  3. Subscribe to the Instagram API
  4. Create an output template in Python
  5. Use it in different contexts

Step 1. Make sure you have python installed

For this article, we will be using a computer running Windows to run the Python code.  I installed Python version 3 from the Python installation instructions for Windows.

But to be sure, we will put up this sample code and try running it:

#!/usr/bin/env python
import sys
sys.stdout.write("hello from Python %sn" % (sys.version,))

When I save the code as and run this on my machine I see this:

hello from Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)]

Python version 3.x is required to use the http.client library in the sample Python code for the Instagram API.

Step 2. Get an API Key

Once we know Python is available, we need to get an API Key.  The Instagram API we will be using is hosted on the RapidAPI platform.  Getting a key is a simple process that is free.  Go to the RapidAPI home page and use an email address or social media account to connect.

Step 3. Subscribe to the Instagram API

Once you are registered on the RapidAPI platform, the next step is to subscribe to the Instagram API.  You can do that by clicking on the blue button on the endpoints page which says “Subscribe to Test”:

Subscribe to Instagram API

There are actually several Instagram APIs you can choose from.  I chose this one for two reasons:

  1. It is advertised as “Simple”.  I want to spend my time working with API results, not figuring out how to get them!
  2. There are several available endpoints for this API. Some allow me to pull from more than one Instagram account at once.  I’m interested in the Tag endpoint, so I can pull posts by hashtag.

After subscribing, I used the online test interface to view the outputs. I wanted to make sure the outputs contained the information I expected.  I started with the Search endpoint. The first hashtag I searched for only looked for users and places with that name.  Then I added # at the beginning (#virtualstarsgymnastics for example). I got a result but it was not what I expected.  I was hoping to get Instagram posts with that hashtag but I got the hashtag itself returned. Yet, when I used the Tag endpoint I got what I was after – actual Instagram posts!

Step 4. Use the Instagram API with Python

Now that we have made sure Python is available and picked an API, it’s time to use it.  First we will start with the sample code on the Endpoints page for Python http.client.  This uses built in Python libraries (when you have Python version 3+ installed).

import http.client

conn = http.client.HTTPSConnection("")

headers = {
    'x-rapidapi-host': "",
    'x-rapidapi-key': "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

conn.request("GET", "/tag/virtualstarsgymnastics/optional", headers=headers)

res = conn.getresponse()
data =


You’ll need to replace the rapidapi-key Xs with your actual key.  You will see this on the endpoints page when you are logged in.

This sample code pulls posts in JSON format.  Next we will use the JSON to create an HTML file showing the results:

#! python
  This script pulls a list of Instagram posts which use a specific hashtag.
    Then it populates an html file that can be used to populate a widget or
    an iframe on another site.

#import libraries used below
import http.client
import json

# Set to 1 to show details along the way for debugging purposes

#This is the hashtag we will search for in the Instagram API
hashtag = "virtualstarsgymnastics"

#Connect to the Instagram API
conn = http.client.HTTPSConnection("")

headers = {
    'x-rapidapi-host': "",
    'x-rapidapi-key': "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

conn.request("GET", "/tag/"+hashtag+"/optional", headers=headers)

res = conn.getresponse()
data =

# Load API response into a Python dictionary object, encoded as utf-8 string
json_dictionary = json.loads(data.decode("utf-8"))

# Prepare output HTMl - use meta charset to display emojis properly.
#   If you are populating the contents of an element on a webpage then 
#   remove the html, head, meta, and body tags below.  But make sure 
#   the parent page has that meta tag in the header.  This will ensure 
#   that emojis, slanted quotes, and other non ASCII characters are displayed.
outputHTML = "<html><head><meta charset='utf-8'><style>
    grid-template-columns: 200px 200px 200px;
  .post-wrapper img {max-width:180px;}
<div class='instagram-wrapper'>"

# This is where the generated html will be saved (in the local directory)
outputFile = "instagramFeed.html"

# Loop through dictionary keys to access each Instagram Post
for item in json_dictionary['edges']:
    # Pull the caption, image, and number of likes for this Instagram Post into variables.
    #   Make sure newlines appear as such in the resulting webpage using line breaks.
    thisCaption = item['node']['edge_media_to_caption']['edges'][0]['node']['text'].replace('n','<br />n')
    if debug>0:
        print("CAPTION:", thisCaption)
    thisURL = item['node']['display_url']
    if debug>0:
        print("image url", ":", thisURL)
    numLikes = item['node']['edge_liked_by']['count']
    if debug>0:
        print("likes", ":", numLikes)

    # Add a section of HTML for this Instagram Post
    outputHTML+='<div class="post-wrapper">
                <img src="'+str(thisURL)+'" />
                <div class="post-caption">'+thisCaption+'</div>
                <div class="post-likes">'+str(numLikes)+' likes</div>

# Finally close out the HTML elements

#Now populate the HTML file
with open(outputFile, "w", encoding="utf-8") as f:

Again, to use the code above you’ll need to replace the Xs with your RapidAPI Key.  What the code will do is to pull a list of Instagram Posts which have a given hashtag in the caption.  Then it captures the image, caption, and number of likes for each post.  Finally it creates an HTML file that shows the posts in a 3 column grid.  You can change the styles used for the template as needed in the Python script.

The hashtag used in this example has only 4 Instagram posts using it so far.  But if you search for something more common the results will be paginated.  You can see the structure for paginated results on the Endpoints page for the Instagram API.  It looks like pagination kicks in after 100 posts:

Paginated Instagram API Results


Step 5. Use it in different contexts

At this point, you may be wondering how to use this information.  Why would I want to generate a static HTML page for dynamic information like Instagram posts?  I will explain two appropriate scenarios for this approach.

Populate an iframe on another site

Let’s say you have an Instagram feed you want to host on your server but provide to other sites as a service?  In this case you could follow these steps:

  1. Set up a cron job or scheduled task on your server to run the python script and generate the html file.
  2. Save the HTML file as part of step 1 to a publicly accessible location with an URL.
  3. Use the public URL to populate an iframe which you share with other sites.  The inline frame (iframe) tag has several available attributes.  Here are a few you might want in this context:
    <iframe id="instagramFeedFrame"
        title="Instagram Feed"

Populate an element on a local site

Let’s say you have an existing site with a lot of moving parts.  Maybe it’s built by someone else so you’re not familiar with the code.  You just have a div picked out on the site where you can put the Instagram feed.  In this situation you could follow these steps:

  1. Same as above, automate the process of updating the HTML file.  But this time leave out the html, head, meta, and body tags.
  2. Make sure the meta tag is in the HEAD of the parent page
  3. Populate the div either on the server or in the client:


In this article, we have walked through an example of using the Instagram API with Python.  We started by getting set up with the API and then used Python to create an HTML file with the results.  Then we discussed possible uses for the output.  Where you take it from here is up to you.  Build something awesome!

View the Best Instagram APIs List


How to start with the Instagram API in python?

Navigate to and choose your preferred Instagram API. Test the endpoints to make sure the API works. Click the code snippet dropdown and select Python.

What is the Instagram API?

The Instagram API is essentially a way for apps to talk to and interact with Instagram. Check out how to use the API with Python in this article.

What can you do with the Instagram API?

The possibilities are endless. Some examples include: Search Tags, Incorporate Photos on Websites, View Photos from Specific Locations in Real-Time, View Popular and Trending Photos, Print Photos from Events and Tags Instantly, Make Custom Items, Market Venues, Events and Businesses, and Create Event Live Feeds.

2.8/5 - (5 votes)

Building an Enterprise API Program
Learn More