Get Photos from Instagram using JavaScript API

The ready to use examples of getting Instagram media by user ID, by username, by one or multiple tags. Works perfect with new API changes.

October 19, 2015 / #APIs, #Instagram

This is the first post in post series about Instagram. There would be posts about working with Instagram API (via PHP and JavaScript) without difficult classes or another similar things. Just ready to use code.

For those who are looking for the complete decision, I have the one. It is WordPress plugin which allows you to insert Instagram widget with photos of a certain user or (and) by a hashtag(s).

Download the plugin

Now let’s come back to this post — it consists of three parts and different examples. As you could understand from its heading it is only about getting photos. Another API methods will be described in the next posts.

All the examples work with jQuery.

Small introducion to Instagram API changes. Access token. #


Generate your Access Token in 4 easy steps #

First of all we need a small preparation — for all examples you should specify your Access Token. It is very easy to get it in four steps:

  1. Log in to Instagram and open this page https://instagram.com/developer/clients/manage
  2. Click on the button «Register a New Client».
  3. Fill all the required fields, in Valid Redirect URIs specify https://rudrastyh.com/tools/access-token and click «Register». Then click «Manage» button to obtain both Client ID and Client Secret of your just registered app.
    Instagram Client ID and Client Secret
  4. Use the Client ID and Client Secret to generate access token with this tool. You can find more info there as well.

A few facts about Sandbox Mode #

  • All newly created apps start in Sandbox Mode
  • Apps in Sandbox mode have access only to 20 latest media of an access token owner (and sandbox users invited to your app).
  • To avoid these restrictions you should send your app to approval.

1. By User ID #

In fact, it is the only example in this post that works properly in Sandbox Mode. For Sandbox mode change userid to the access token owner ID or just to self.

var token = 'your access token', // learn how to obtain it below
    userid = 1362124742, // User ID - get it in source HTML of your Instagram profile or look at the next example :)
    num_photos = 4; // how much photos do you want to get
 
$.ajax({
	url: 'https://api.instagram.com/v1/users/' + userid + '/media/recent', // or /users/self/media/recent for Sandbox
	dataType: 'jsonp',
	type: 'GET',
	data: {access_token: token, count: num_photos},
	success: function(data){
 		console.log(data);
		for( x in data.data ){
			$('ul').append('<li><img src="'+data.data[x].images.low_resolution.url+'"></li>'); // data.data[x].images.low_resolution.url - URL of image, 306х306
			// data.data[x].images.thumbnail.url - URL of image 150х150
			// data.data[x].images.standard_resolution.url - URL of image 612х612
			// data.data[x].link - Instagram post URL 
		}
	},
	error: function(data){
		console.log(data); // send the error notifications to console
	}
});

See the Pen EyPbBr by Misha (@rudrastyh) on CodePen.light

2. By a Username #

Of course you can look for user ID in Instagram HTML code each time.

But do not you think that it would be better to get user ID in the code automatically? Especially for your own plugin or application. It is much simplier for every single user of your app to specify a username, not a user ID.

This example isn’t supported by apps in Sandbox Mode.

var token = 'your access token',
    username = 'rudrastyh', // rudrastyh - my username :)
    num_photos = 4;
 
$.ajax({ // the first ajax request returns the ID of user rudrastyh
	url: 'https://api.instagram.com/v1/users/search',
	dataType: 'jsonp',
	type: 'GET',
	data: {access_token: token, q: username}, // actually it is just the search by username
	success: function(data){
		console.log(data);
		$.ajax({
			url: 'https://api.instagram.com/v1/users/' + data.data[0].id + '/media/recent', // specify the ID of the first found user
			dataType: 'jsonp',
			type: 'GET',
			data: {access_token: token, count: num_photos},
			success: function(data2){
				console.log(data2);
				for(x in data2.data){
					$('ul').append('<li><img src="'+data2.data[x].images.thumbnail.url+'"></li>');  
				}
    			},
			error: function(data2){
				console.log(data2);
			}
		});
	},
	error: function(data){
		console.log(data);
	}
});

Can I get Photos of a Certain User Filtered by a Tag(s)? #

Get Instagram photos of a certain user filtered by a tag.

Yes you can. I do not want to overload this post with difficult code, so, I recommend you to download my Instagram plugin for WP — and it doesn’t require access token or application approval! If you won’t use WordPress, you can inspect the plugin code anyway.

3. By a Tag #

This functionality is also very popular. Very easy to implement.

But if your Instagram app is in Sandbox Mode you can only get your own tagged media. And rememeber that your app has access only to 20 recent media. If you want to avoid these restrictions so much you could try to use my WordPress plugin.

var token = 'your access token',
    hashtag='wordcamprussia2015', // hashtag without # symbol
    num_photos = 4;
 
$.ajax({
	url: 'https://api.instagram.com/v1/tags/' + hashtag + '/media/recent',
	dataType: 'jsonp',
	type: 'GET',
	data: {access_token: token, count: num_photos},
	success: function(data){
		console.log(data);
		for(x in data.data){
			$('ul').append('<li><img src="'+data.data[x].images.standard_resolution.url+'"></li>');  
		}
	},
	error: function(data){
		console.log(data);
	}
});

Can I get photos by Multiple Tags? #

Get Instagram photos by multiple tags.

Of course you can, but you should learn more about JavaScript arrays in that case — this requires to make an ajax request for every hashtag and then just rearrange the result data.

If you don’t want to dig into it — download the plugin and look how this is implemented in the code (or just use the plugin — that’s all).

If you have a question, please, leave it in comments — I will answer for everyone.

Only the best of WordPress

once a week, no spam

Comments 43

  • This is the simplest script I’ve found to get photos via the Instagram API, and your instructions were the clearest. Thank you!!

  • if i have a scenario like this : i have an instagram account, ex : @jonsnow. i want to create a web app using php, which can reply a comment with my account (@jonsnow) it is possible? my algorithm is first, i search a photo with a tag. than i want to get the photo caption, then i want to give/reply a comment with my account.

  • I notice you say “If you won’t use WordPress, you can inspect the plugin code anyway”. I do not have a WP site but I want to mess with some of this plugin’s code in a personal product. 2 questions:
    1. Can I definitely see the source code if I buy the plugin to copy and alter for my own app?
    2. Will I still be restricted by the sandbox return results?

    • MishaAuthorJune 16, 2016 at 03:06

      Hi Joe,

      1. Yes, you can do it, but in the latest version of the plugin it is not so simple as before ( you will need good knowledge of PHP and PHP/JS beautifier ).
      2. No you won’t be restricted.

  • Awesome post, the better one I have found that explain and help to get the Access token and without the need of other libraries.

    Do you know if Is it necessary to submit the instagram app for review if you are only using it to grab the most recent photos from the instagram account to show them in the company website?

  • Hi

    It’s possible to send a Image and hashtag to the user timeline?

    thanks

  • This is not Javascript. This is JQuery. If we wanted JQuery, we would’ve come looking for “JQuery.” The title is misleading.

  • That’s amazing article as I have know. Thank you so much.

  • This still work ?

  • firebuggirlAugust 8, 2016 at 02:08

    Hi,

    When I follow the instructions and attempt to get an access token I receive this error:

    “code”: 400,
    “error_type”: “OAuthException”,
    “error_message”: “Invalid Client ID

    Why is this happening?

    Thanks!

  • Is there a way to fetch my account’s liked photos/videos?

    Thanks!

    • MishaAuthorAugust 15, 2016 at 10:08

      Hi Marcelo,
      yes, you can just add the IF statement:

      for(x in data2.data){
      	if( data2.data[x].likes.count > 0 ) {
      		$('ul').append('<li><img src="'+data2.data[x].images.thumbnail.url+'"></li>');
      	}
      }
  • Great tutorial. I really enjoyed it. :)

    I was wondering if you had the ability for a search function to populate images via hashtag?

  • *For the user to input themselves that is (Sorry for not clarifying before). Thanks.

    • MishaAuthorAugust 18, 2016 at 10:08

      Hi Valerie,

      My plugin can get images by hashtags, currently it can not filter user images by a specific tag (well, it can, but this functions doesn’t work as expected), but I’m working on it now :)

  • hi developer, thank for your job.

    3 questions for you

    1) I did understand why in Valid Redirect URIs I need to specify this url https://rudrastyh.com/tools/access-token ? I can’t put my website url http://www.exemple.com ?

    2) I would like to view pictures about other public account?i s it possible ? Or just own account ?
    3) at the end, is it possible found results by hashtag from all profile. I would like to create an aggregator by instangram hashtag

    thank you Rud

    • Hi,
      1) Try to put your website there and look what happens :) It is required to specify url to the tool, after receiving Access Token you can change it if you want I suppose.

      2) Other accounts are possible in two cases: a) approved access token b) using my plugin.

      3) Profile pictures filtered by a hashtag currenly is not supported.

  • does it possible nowadays for me to show timeline photos based on hashtags, example #helloworld ?
    because even snapwidget(instagram timeline viewer for website) remove their ability to showing all photos based on hashtags

  • Arrogant AmbassadorOctober 29, 2016 at 11:10

    This is a fantastic little tool. Thanks for creating it.

  • Hello Misha,

    Do you know how to search for tags with Ruby?

  • is any option to move my image with some rotation with change position.

  • Hey Misha, thanks a lot for this tutorial.

    I have a problem tho, I get the acces token with my personal account, but when I want to retrieve a feed by hashtag, I get an empty array.

    The same happens when i search for a random user, even when their accounts are public.

    I have copied and pasted the code exactly as you show here, replacing only the token

    • MishaAuthorJanuary 4, 2017 at 22:01

      Hi Leo,

      since June 2016 Instagram made some changes in their API, if your application is not approved, you can get ONLY 20 latest photos of your account (the owner of the access token).

      But you can consider using this plugin – it allows to get photos by tags and from any public account without an access token.

    • When you create an application to get a token on instagram, it is created on sandbox mode. When on sandbox mode, you can only query your own content, and you’ll only get 20 results.

      You cannot submit the application for approval, I mean you can but it’s worthless, as any useful scenario won’t be approved. For instance, searching for hashtags and displaying content on your website.

      So, if you create your token and query the instagram api for pictures tagged with #somehashtag

      https://api.instagram.com/v1/tags/somehashtag/media/recent?access_token=[token]

      it will only return images tagged that were published using your account. If you don;t have any, you’ll get an empty array.

  • sorry, when i get myself’s user detail, i get results, but when i want to get other’s user detail, it return error with 404.l

  • Hello Misha, thanks a lot for this tutorial!
    Please help me understand what I’m doing wrong!
    This script works in Chrome and Safari, but in Opera 12.15 is not working (I need it to check the layout of website). This is strange because your example on this page in Opera 12.15 displays the result. I thought that the problem with jquery, I tried several versions, but to no avail. Please help!

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
    	<meta name="description" content="">
    	<meta name="keywords" content="">
     
    	<!-- JQUERY -->
    		<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
    	<!-- END JQUERY -->
     
    	<style type="text/css">
    		#rudr_instafeed{
    			list-style:none  
    		}
    		#rudr_instafeed li{
    			float:left;
    			width:20%;
    			height:20%;
    			margin:5px
    		}
    		#rudr_instafeed li img{
    			max-width:100%;
    			max-height:100%;
    		}
    	</style>
     
    	<script type="text/javascript">
    		var token = '3592151521.ac3c225.e401af617bab4bc497ec860caea88cd7',
    		num_photos = 10;
     
    		$.ajax({
    			url: 'https://api.instagram.com/v1/users/self/media/recent/',
    			dataType: 'jsonp',
    			type: 'GET',
    			data: {access_token: token, count: num_photos},
    			success: function(data){
    				console.log(data);
    				for( x in data.data ){
    					$('ul').append('<li><img src="'+data.data[x].images.low_resolution.url+'"></li>');
    				}
    			},
    			error: function(data){
    				console.log(data);
    			}
    		});
     
     
     
    	</script>
     
    </head>
    <body>
    	f<br><ul id="rudr_instafeed"></ul><br>f
    </body>
    </html>
    • The issue decided. It turned out everything is simple. For older browsers it is important that Ajax was wrapped in $(document).ready

      	<script type="text/javascript">
      		$(document).ready(function() {
      			var token = '-----------------------------------',
      			num_photos = 10;
       
      			$.ajax({
      				url:		'https://api.instagram.com/v1/users/self/media/recent/',
      				dataType:	'jsonp',
      				type:		'GET',
      				data:		{access_token: token, count: num_photos},
      				success: function(data){
      					console.log(data);
      					for( x in data.data ){
      						$('ul').append('<li><img src="' + data.data[x].images.thumbnail.url + '" /></li>');
      					}
      				},
      				error: function(data){
      					console.log(data);
      				}
      			});
      		});
      	</script>

      If we write so that all works!

Leave your question or feedback

phpjsHTMLCSSSQLCode
Please, enter a comment
Please, enter a name
Incorrect email