You're in good company
RapidAPI has a strong developer community with over a million developers and a growing list of enterprise customers.






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
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 hello.py and run this on my machine I see this:
>python hello.py 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.
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.
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”:
There are actually several Instagram APIs you can choose from. I chose this one for two reasons:
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!
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("instagramdimashirokovv1.p.rapidapi.com") headers = { 'x-rapidapi-host': "InstagramdimashirokovV1.p.rapidapi.com", 'x-rapidapi-key': "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } conn.request("GET", "/tag/virtualstarsgymnastics/optional", headers=headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8"))
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 """ File: populateInstagramFeed.py Description: 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 debug=0 #This is the hashtag we will search for in the Instagram API hashtag = "virtualstarsgymnastics" #Connect to the Instagram API conn = http.client.HTTPSConnection("instagramdimashirokovv1.p.rapidapi.com") headers = { 'x-rapidapi-host': "InstagramdimashirokovV1.p.rapidapi.com", 'x-rapidapi-key': "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } conn.request("GET", "/tag/"+hashtag+"/optional", headers=headers) res = conn.getresponse() data = res.read() # 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> .instagram-wrapper{ display:grid; grid-template-columns: 200px 200px 200px; } .post-wrapper{padding:10px;} .post-wrapper img {max-width:180px;} .post-likes{font-weight:bold;} </style> </head><body> <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> </div>' # Finally close out the HTML elements outputHTML+='</div></body></html>' #Now populate the HTML file with open(outputFile, "w", encoding="utf-8") as f: f.write(outputHTML)
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:
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.
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:
<iframe id="instagramFeedFrame" title="Instagram Feed" width="300" height="200" loading="lazy" src="https://mydomain/path/to/instagramFeed.html"> </iframe>
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:
<div class="instagram-feed"><?php echo file_get_contents("/path/to/instagramFeed.html"); ?></div>
$.ajax({ url: "/path/to/instagramFeed.html", context: document.body, success: function(response) { $("#instagramFeedDiv").html(response); } });
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
Navigate to https://rapidapi.com/collection/instagram-apis and choose your preferred Instagram API. Test the endpoints to make sure the API works. Click the code snippet dropdown and select Python. 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. 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.How to start with the Instagram API in python?
What is the Instagram API?
What can you do with the Instagram API?