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:

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. protected void Page_Load(object sender, EventArgs e)
  3. {
  4. if (!String.IsNullOrEmpty(Request["code"]) && !Page.IsPostBack)
  5. {
  6. code = Request["code"].ToString();
  7. GetDataInstagramToken();
  8. }
  9. }
  10. //Function used to get instagram user id and access token
  11. public void GetDataInstagramToken()
  12. {
  13. var json = "";
  14. try
  15. {
  16. NameValueCollection parameters = new NameValueCollection();
  17. parameters.Add("client_id", ConfigurationManager.AppSettings["instagram.clientid"].ToString());
  18. parameters.Add("client_secret", ConfigurationManager.AppSettings["instagram.clientsecret"].ToString());
  19. parameters.Add("grant_type", "authorization_code");
  20. parameters.Add("redirect_uri", ConfigurationManager.AppSettings["instagram.redirecturi"].ToString());
  21. parameters.Add("code", code);
  22. WebClient client = new WebClient();
  23. var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
  24. var response = System.Text.Encoding.Default.GetString(result);
  25. // deserializing nested JSON string to object
  26. var jsResult = (JObject)JsonConvert.DeserializeObject(response);
  27. string accessToken = (string)jsResult["access_token"];
  28. int id = (int)jsResult["user"]["id"];
  29. //This code register id and access token to get on client side
  30. Page.ClientScript.RegisterStartupScript(this.GetType(), "GetToken", "<script>var instagramaccessid=\"" + @"" + id + "" + "\"; var instagramaccesstoken=\"" + @"" + accessToken + "" + "\";</script>");
  31. }
  32. catch (Exception ex)
  33. {
  34. throw;
  35. }
  36. }
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. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
  25. $(document).ready (function () {
  26. GetUserDetails();
  27. });
  28. //Get user details
  29. function GetUserDetails() {
  30. $.ajax({
  31. type: "GET",
  32. async: true,
  33. contentType: "application/json; charset=utf-8",
  34. url: 'https://api.instagram.com/v1/users/' + instagramaccessid + '?access_token=' + instagramaccesstoken,
  35. dataType: "jsonp",
  36. cache: false,
  37. beforeSend: function () {
  38. $("#loading").show();
  39. },
  40. success: function (data) {
  41. $('#usernameLabel').text(data.data.username);
  42. $('#nameLabel').text(data.data.full_name);
  43. $('#bioLabel').text(data.data.bio);
  44. document.getElementById("imgProfilePic").src = data.data.profile_picture;
  45. }
  46. });
  47. }
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. //Get photos
  11. function GetInstagramPhotos() {
  12. $("#PhotosUL").html("");
  13. $.ajax({
  14. type: "GET",
  15. async: true,
  16. contentType: "application/json; charset=utf-8",
  17. //Recent user photos
  18. url: 'https://api.instagram.com/v1/users/' + instagramaccessid + '/media/recent?access_token=' + instagramaccesstoken,
  19. //Most popular photos
  20. //url: "https://api.instagram.com/v1/media/popular?access_token=" + instagramaccesstoken,
  21. //For most recent pictures from a specific location:
  22. //url: "https://api.instagram.com/v1/media/search?lat=[LAT]&lng=[LNG]&distance=[DST]?client_id=[ClientID]&access_token=[CODE]",
  23. //For min and max images
  24. //url: "https://api.instagram.com/v1/users/"+ userId+ "/media/recent/"+ "?access_token="+ token+ "&count=" + mediaCount+ "&max_id=" + mOldestId",
  25. //By Tags
  26. //url: "https://api.instagram.com/v1/tags/coffee/media/recent?client_id=[]&access_token=[]",
  27. //To get a user’s detail
  28. //url: "https://api.instagram.com/v1/users/usert_id/?access_token=youraccesstoken",
  29. dataType: "jsonp",
  30. cache: false,
  31. beforeSend: function () {
  32. $("#loading").show();
  33. },
  34. success: function (data) {
  35. $("#loading").hide();
  36. if (data == "") {
  37. $("#PhotosDiv").hide();
  38. } else {
  39. $("#PhotosDiv").show();
  40. for (var i = 0; i < data["data"].length; i++) {
  41. $("#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>");
  42. }
  43. }
  44. }
  45. });
  46. }
  47. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
  48. <script type="text/javascript">
  49. $(document).ready(function () {
  50. GetInstagramPhotos();
  51. });
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. //Get popular pictures
  10. function GetPopularPhotos() {
  11. $("#photosUL1").html("");
  12. $.ajax({
  13. type: "GET",
  14. async: true,
  15. contentType: "application/json; charset=utf-8",
  16. //Most popular photos
  17. url: "https://api.instagram.com/v1/media/popular?access_token=" + instagramaccesstoken,
  18. dataType: "jsonp",
  19. cache: false,
  20. beforeSend: function () {
  21. $("#loading").show();
  22. },
  23. success: function (data) {
  24. $("#loading").hide();
  25. if (data == "") {
  26. $("#PopularPhotosDiv").hide();
  27. } else {
  28. $("#PopularPhotosDiv").show();
  29. for (var i = 0; i < data["data"].length; i++) {
  30. $("#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>");
  31. }
  32. }
  33. }
  34. });
  35. }
  36. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
  37. <script type="text/javascript">
  38. $(document).ready(function () {
  39. GetPopularPhotos();
  40. });
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.