How to Authenticate and Get Data Using Instagram API

This article explains how to authenticate an Instagram API and how to get user photos, user details and popular photos using the Instagram API.

Instagram

Instagram is an online mobile photo-sharing, video-sharing and social networking service that enables its users to take pictures and videos and share them in a variety of social networking platforms, such as Facebook, Twitter, Tumblr and Flickr. http://en.wikipedia.org/wiki/Instagram.

Authentication

First of all you need to register as a developer at http://instagram.com/developer/. Click on the Register Your Application button.

register your application

Now enter your application name, description, website, OAuth redirect URL and captha code and click the Register button.

register button

the next screen looks like this that has client id, client secret, website URL and redirect URI.

Keep these credentials in the web.config file.

  1. <appSettings>  
  2.     <add key="instagram.clientid" value="8be6127ff21b4f389cb859aadadbf0b4"/>  
  3.     <add key="instagram.clientsecret" value="90a78bf8e87b48568fce4c2606ff4542"/>  
  4.     <add key="instagram.redirecturi" value="http://localhost:36960/InstagramPhotosASPNETSample/AuthenticateInstagram.aspx"/>  
  5.   </appSettings>  
Now add a new web form and drag and drop a button control.
  1. <h1> Instagram Authentication Sample</h1>  

  2. <div>  
  3.    <asp:Button ID="btnAuthenticate" runat="server" Text="Authenticate Instagram" OnClick="btnAuthenticate_Click" />  
  4. </div>  
Fire the button event and write the following code.
  1. Protected void btnAuthenticate_Click(object sender, EventArgs e)  
  2. {  
  3.     var client_id = ConfigurationManager.AppSettings["instagram.clientid"].ToString();  
  4.     var redirect_uri = ConfigurationManager.AppSettings["instagram.redirecturi"].ToString();  
  5.     Response.Redirect("https://api.instagram.com/oauth/authorize/?                           client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=code");  
  6. }  
In the given code you can see that the client_id and redirect_uri are coming from the web.config file.

That will do the following two things: 
  • That will open an Instagram login page if not logged into Instagram.
  • If already logged into Instgram then that will redirect you to a given redirect page with a code in a query string.

authenticate Instagram

If not logged in:

login page

If the user is logged in:

Instagram API

Now let's get the data from Instagram, like recent photos, popular photos and user details.

To get the data using the API then we need an access token first, so let's get the access token.

Get Access Token

The Instagram Access Token is a long number that grants other applications access to your Instagram feed. This allows us to display your awesome Instagram photos on your blog. You can grab your access token by clicking here and authorizing Instagram access. Tumblr General.

For the most part, Instagram's API only requires the use of a client_id. A client_id simply associates your server, script or program with a specific application. However, some requests require authentication, specifically requests made on behalf of a user. Authenticated requests require an access_token. These tokens are unique to a user and should be stored securely. Access tokens may expire at any time in the future.

Note that in many situations, you may not need to authenticate users at all. For instance, you may request popular photos without authentication (in other words you do not need to provide an access_token; just use your client ID with your request). We only require authentication in cases where your application is making requests on behalf of a user (commenting, liking, browsing a user's feed, and so on).

http://instagram.com/developer/authentication/

Get access-token programmatically:

  1. static string code = string.Empty;  
  2.   
  3. protected void Page_Load(object sender, EventArgs e)  
  4. {  
  5.     if (!String.IsNullOrEmpty(Request["code"]) && !Page.IsPostBack)  
  6.     {  
  7.         code = Request["code"].ToString();  
  8.         GetDataInstagramToken();  
  9.   
  10.     }  
  11.   
  12. }  
  13.   
  14. //Function used to get instagram user id and access token  
  15. public void GetDataInstagramToken()  
  16. {  
  17.     var json = "";  
  18.     try  
  19.     {  
  20.         NameValueCollection parameters = new NameValueCollection();  
  21.         parameters.Add("client_id", ConfigurationManager.AppSettings["instagram.clientid"].ToString());  
  22.         parameters.Add("client_secret", ConfigurationManager.AppSettings["instagram.clientsecret"].ToString());  
  23.         parameters.Add("grant_type""authorization_code");  
  24.         parameters.Add("redirect_uri", ConfigurationManager.AppSettings["instagram.redirecturi"].ToString());  
  25.         parameters.Add("code", code);  
  26.   
  27.         WebClient client = new WebClient();  
  28.         var result = client.UploadValues("https://api.instagram.com/oauth/access_token""POST", parameters);  
  29.         var response = System.Text.Encoding.Default.GetString(result);  
  30.   
  31.         // deserializing nested JSON string to object  
  32.         var jsResult = (JObject)JsonConvert.DeserializeObject(response);  
  33.         string accessToken = (string)jsResult["access_token"];  
  34.         int id = (int)jsResult["user"]["id"];  
  35.   
  36.         //This code register id and access token to get on client side  
  37.         Page.ClientScript.RegisterStartupScript(this.GetType(), "GetToken""<script>var instagramaccessid=\"" + @"" + id + "" + "\"; var instagramaccesstoken=\"" + @"" + accessToken + "" + "\";</script>");  
  38.   
  39.     }  
  40.     catch (Exception ex)  
  41.     {  
  42.         throw;  
  43.   
  44.     }   
  45. }  
In the code above, you can see we pass the parameters to Instagram and based on those parameters Instagram returns JSON format data that has id and access-token. You can store access_token and id wherever you want.
  1. // deserializing nested JSON string to object  
  2.   var jsResult = (JObject)JsonConvert.DeserializeObject(response);  
  3.   string accessToken = (string)jsResult["access_token"];  
  4.   int id = (int)jsResult["user"]["id"];  
Or
  1. // deserializing nested JSON string to object  
  2. AuthToken user = JsonConvert.DeserializeObject<AuthToken>(response);  
  3. accessToken = user.AccessToken;  
  4. id = user.User.ID;  
Now let's fetch user details from Instagram like name, username, bio, profile picture using access_token.

Get Basic Details
  1. <div>  
  2.             <h1>  
  3.                 About Me</h1>  
  4.             <div style="font-size: medium;">  
  5.                 User Name:  
  6.                 <label id="usernameLabel">  
  7.                 </label>  
  8.             </div>  
  9.             <div style="font-size: medium;">  
  10.                 Full Name:  
  11.                 <label id="nameLabel">  
  12.                 </label>  
  13.             </div>  
  14.             <div style="font-size: medium;">  
  15.                 Profile Pic:  
  16.                 <img id="imgProfilePic" />  
  17.             </div>  
  18.             <div style="font-size: medium;">  
  19.                 Bio:  
  20.                 <label id="bioLabel">  
  21.                 </label>  
  22.             </div>  
  23. </div>  
  24.   
  25. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  26.   $(document).ready (function () {          
  27.     GetUserDetails();  
  28.   });  
  29.   
  30. //Get user details  
  31.         function GetUserDetails() {  
  32.             $.ajax({  
  33.                 type: "GET",  
  34.                 async: true,  
  35.                 contentType: "application/json; charset=utf-8",  
  36.                 url: 'https://api.instagram.com/v1/users/' + instagramaccessid + '?access_token=' + instagramaccesstoken,  
  37.                 dataType: "jsonp",  
  38.                 cache: false,  
  39.                 beforeSend: function () {  
  40.                     $("#loading").show();  
  41.                 },  
  42.                 success: function (data) {  
  43.                     $('#usernameLabel').text(data.data.username);  
  44.                     $('#nameLabel').text(data.data.full_name);  
  45.                     $('#bioLabel').text(data.data.bio);  
  46.                     document.getElementById("imgProfilePic").src = data.data.profile_picture;  
  47.                 }  
  48.             });  
  49.         }  
Run the application.

user in Instagram photos

Get Recent Photos
  1. <div>  
  2.             <h1>  
  3.                 Recent Photos</h1>  
  4.             <div id="PhotosDiv">  
  5.                 <ul id="PhotosUL">  
  6.                 </ul>  
  7.             </div>  
  8.         </div>  
  9.         <div style="clear:both;"></div>  
  10.   
  11.   
  12. //Get photos  
  13.         function GetInstagramPhotos() {  
  14.             $("#PhotosUL").html("");  
  15.             $.ajax({  
  16.                 type: "GET",  
  17.                 async: true,  
  18.                 contentType: "application/json; charset=utf-8",  
  19.                 //Recent user photos  
  20.                 url: 'https://api.instagram.com/v1/users/' + instagramaccessid + '/media/recent?access_token=' + instagramaccesstoken,  
  21.                 //Most popular photos  
  22.                 //url: "https://api.instagram.com/v1/media/popular?access_token=" + instagramaccesstoken,  
  23.                 //For most recent pictures from a specific location:  
  24.                 //url:  "https://api.instagram.com/v1/media/search?lat=[LAT]&lng=[LNG]&distance=[DST]?client_id=[ClientID]&access_token=[CODE]",  
  25.                 //For min and max images  
  26.                 //url: "https://api.instagram.com/v1/users/"+ userId+ "/media/recent/"+ "?access_token="+ token+ "&count=" + mediaCount+ "&max_id=" + mOldestId",  
  27.                 //By Tags  
  28.                 //url: "https://api.instagram.com/v1/tags/coffee/media/recent?client_id=[]&access_token=[]",  
  29.                 //To get a user’s detail  
  30.                 //url: "https://api.instagram.com/v1/users/usert_id/?access_token=youraccesstoken",  
  31.                 dataType: "jsonp",  
  32.                 cache: false,  
  33.                 beforeSend: function () {  
  34.                     $("#loading").show();  
  35.                 },  
  36.                 success: function (data) {  
  37.                     $("#loading").hide();  
  38.                     if (data == "") {  
  39.                         $("#PhotosDiv").hide();  
  40.                     } else {  
  41.   
  42.                         $("#PhotosDiv").show();  
  43.                         for (var i = 0; i < data["data"].length; i++) {  
  44.                             $("#PhotosUL").append("<li style='float:left;list-style:none;'><a target='_blank' href='" + data.data[i].link + "'><img src='" + data.data[i].images.thumbnail.url + "'></img></a></li>");  
  45.                         }  
  46.   
  47.                     }  
  48.                 }  
  49.   
  50.             });  
  51.         }  
  52.   
  53. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  54.     <script type="text/javascript">  
  55.         $(document).ready(function () {  
  56.             GetInstagramPhotos();              
  57.         });  
Output

recent photo

Get Popular Photos
  1. <div>  
  2.             <h1>  
  3.                 Popular Pictures</h1>  
  4.             <div id="PopularPhotosDiv">  
  5.                 <ul id="photosUL1">  
  6.                 </ul>  
  7.             </div>  
  8.         </div>  
  9.   
  10.   
  11. //Get popular pictures  
  12.         function GetPopularPhotos() {  
  13.             $("#photosUL1").html("");  
  14.             $.ajax({  
  15.                 type: "GET",  
  16.                 async: true,  
  17.                 contentType: "application/json; charset=utf-8",  
  18.                 //Most popular photos  
  19.                 url: "https://api.instagram.com/v1/media/popular?access_token=" + instagramaccesstoken,  
  20.                 dataType: "jsonp",  
  21.                 cache: false,  
  22.                 beforeSend: function () {  
  23.                     $("#loading").show();  
  24.                 },  
  25.                 success: function (data) {  
  26.                     $("#loading").hide();  
  27.                     if (data == "") {  
  28.                         $("#PopularPhotosDiv").hide();  
  29.                     } else {  
  30.                         $("#PopularPhotosDiv").show();  
  31.                         for (var i = 0; i < data["data"].length; i++) {  
  32.                             $("#photosUL1").append("<li style='float:left;list-style:none;'><a target='_blank' href='" + data.data[i].link + "'><img src='" + data.data[i].images.thumbnail.url + "'></img></a></li>");  
  33.                         }  
  34.   
  35.                     }  
  36.                 }  
  37.   
  38.             });  
  39.         }  
  40.   
  41.   
  42. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  43.     <script type="text/javascript">  
  44.         $(document).ready(function () {  
  45.              GetPopularPhotos();  
  46.         });  
Output

Get Popular Photos

Conclusion

This article explained a few things, like Instagram authentication, getting recent photos, getting popular photos and user details. For more details please download the attached sample Zip file. If you have any question or comments, please post a comment in the C# Corner comments section. 


Similar Articles