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
- Make sure you have python installed on your server
- Get an API Key
- Subscribe to the Instagram API
- Create an output template in Python
- 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 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.
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”:
There are actually several Instagram APIs you can choose from. I chose this one for two reasons:
- It is advertised as “Simple”. I want to spend my time working with API results, not figuring out how to get them!
- 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("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:
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:
- Set up a cron job or scheduled task on your server to run the python script and generate the html file.
- Save the HTML file as part of step 1 to a publicly accessible location with an URL.
- 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" width="300" height="200" loading="lazy" src="https://mydomain/path/to/instagramFeed.html"> </iframe>
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:
- Same as above, automate the process of updating the HTML file. But this time leave out the html, head, meta, and body tags.
- Make sure the meta tag is in the HEAD of the parent page
- Populate the div either on the server or in the client:
- If your site is written in PHP you could simply populate the div with inline code.
<div class="instagram-feed"><?php echo file_get_contents("/path/to/instagramFeed.html"); ?></div>
- If you have a large feed you want to populate after the page loads you can use jQuery like below. This assumes you are populating a div with an ID of instagramFeedDiv:
$.ajax({ url: "/path/to/instagramFeed.html", context: document.body, success: function(response) { $("#instagramFeedDiv").html(response); } });
- If your site is written in PHP you could simply populate the div with inline code.
Conclusion
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
FAQ
How to start with the Instagram API in python?
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.
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.
Thanks for your help, i connect to this API, i just want to know how to use this data in a pandas dataframe to make some analysis. I mean how to extract the data that i collect in order to be able to make an analysis!
I haven´t found any documentation related to this API
Hi Gabriel,
You might find some help at https://stackoverflow.com/questions/25734079/json-dictionaries-to-pandas-dataframe-in-python to help you read the JSON data directly into a pandas dataframe instead of a dictionary as I did in this example.
Regards,
Robert
Hello,
I was wondering if it’s possible to get any user’s post (if they are public)?
Or can you only use the api on yourself (or if someone gives you permission).
Thanks,
Bill
Yes Bill you can get any user’s public posts. In the example I shared I was not even aware of those posts before I searched for them using the API.
Hey Robert,
Do you work as a freelancer as well? I have an idea to use the instagram api but I’m not familiar with coding.
Cheers, Ismet
Hi Ismet,
Yes I do freelance work, thanks for asking. I’ve sent you an email to follow up.
Regards,
Robert
Hi Robert.
I was thinking if it’s possible to post to Instagram from my website with the Instagram API.
Hi Samson,
The instagram API does not include the option to post to Instagram. The closest thing I found was for “Instagram Professionals” at https://developers.facebook.com/docs/instagram-api/, but even that does not seem to allow posting, only replying to comments. Specifically https://developers.facebook.com/docs/instagram-api/reference/media says the Creating operation is not supported.
Regards,
Robert
Hi,
I read https://developers.facebook.com/docs/instagram-api/guides/hashtag-search – there are limitations for hashtag search up to 30 unique hashtags in 7 days.
Does /tag API have such limitation? If yes – can you please, describe limitations for app/account?
Thanks in advance.
Hi Anna,
I see you’ve already asked the API owner. My suggestion would be to try searching 31 unique hashtags in a day and see what happens. 🙂
Regards,
Robert
Hi. It appears that the GET followers option only returns the first 12 followers for a profile. I suspect I should be doing something the the cursor option because it says pagination, it 12 looks like the visible followers before scrolling. How do I retrieve the full list of followers? or, at least more than 12?
Hello J Scriven,
In the example responses of the Instagram API at https://rapidapi.com/v.sobolev/api/Instagram?endpoint=apiendpoint_53b655cc-dfad-40a1-a024-86cebcad8476 there is a section at the bottom that looks like this:
page_info”:{
“end_cursor”:”QVFCcmxuTWdNY2xVS3NwSlZqcHJuR0VVZ1RvZ3ZfWnpxQzNibGlwMndiLTY1TER3bkpLTzNmdVJlRVdSSlFIOUwwNzlwTUVfS1NFVmlyeEl3M0dmRTJuMA==”
“has_next_page”:true
}
In order to get the next page of results you would take the string contained in the “end_cursor” value and put that into the “cursor” input for your next api call. Does that make sense?
Regards,
Robert
Can’t we use the latest version of python to make use of this api?
Hi Sanjana,
Yes you can use the latest version of python, I just made a point of using at least version 3 because that has http.client built in.
Regards,
Robert
Hello, it’s possible with api receive or disable the two factor Security Code ?
I’m not aware of that capability from the Instagram API.