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.
Now enter your application name, description, website, OAuth redirect URL and captha code and click the 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.
- <appSettings>
- <add key="instagram.clientid" value="8be6127ff21b4f389cb859aadadbf0b4"/>
- <add key="instagram.clientsecret" value="90a78bf8e87b48568fce4c2606ff4542"/>
- <add key="instagram.redirecturi" value="http://localhost:36960/InstagramPhotosASPNETSample/AuthenticateInstagram.aspx"/>
- </appSettings>
Now add a new web form and drag and drop a button control.
- <h1> Instagram Authentication Sample</h1>
- <div>
- <asp:Button ID="btnAuthenticate" runat="server" Text="Authenticate Instagram" OnClick="btnAuthenticate_Click" />
- </div>
Fire the button event and write the following code.
- Protected void btnAuthenticate_Click(object sender, EventArgs e)
- {
- var client_id = ConfigurationManager.AppSettings["instagram.clientid"].ToString();
- var redirect_uri = ConfigurationManager.AppSettings["instagram.redirecturi"].ToString();
- Response.Redirect("https://api.instagram.com/oauth/authorize/? client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=code");
- }
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.
If not logged in:
If the user is logged in:
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:
- static string code = string.Empty;
-
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!String.IsNullOrEmpty(Request["code"]) && !Page.IsPostBack)
- {
- code = Request["code"].ToString();
- GetDataInstagramToken();
-
- }
-
- }
-
-
- public void GetDataInstagramToken()
- {
- var json = "";
- try
- {
- NameValueCollection parameters = new NameValueCollection();
- parameters.Add("client_id", ConfigurationManager.AppSettings["instagram.clientid"].ToString());
- parameters.Add("client_secret", ConfigurationManager.AppSettings["instagram.clientsecret"].ToString());
- parameters.Add("grant_type", "authorization_code");
- parameters.Add("redirect_uri", ConfigurationManager.AppSettings["instagram.redirecturi"].ToString());
- parameters.Add("code", code);
-
- WebClient client = new WebClient();
- var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
- var response = System.Text.Encoding.Default.GetString(result);
-
-
- var jsResult = (JObject)JsonConvert.DeserializeObject(response);
- string accessToken = (string)jsResult["access_token"];
- int id = (int)jsResult["user"]["id"];
-
-
- Page.ClientScript.RegisterStartupScript(this.GetType(), "GetToken", "<script>var instagramaccessid=\"" + @"" + id + "" + "\"; var instagramaccesstoken=\"" + @"" + accessToken + "" + "\";</script>");
-
- }
- catch (Exception ex)
- {
- throw;
-
- }
- }
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.
-
- var jsResult = (JObject)JsonConvert.DeserializeObject(response);
- string accessToken = (string)jsResult["access_token"];
- int id = (int)jsResult["user"]["id"];
Or
-
- AuthToken user = JsonConvert.DeserializeObject<AuthToken>(response);
- accessToken = user.AccessToken;
- id = user.User.ID;
Now let's fetch user details from Instagram like name, username, bio, profile picture using access_token.
Get Basic Details
- <div>
- <h1>
- About Me</h1>
- <div style="font-size: medium;">
- User Name:
- <label id="usernameLabel">
- </label>
- </div>
- <div style="font-size: medium;">
- Full Name:
- <label id="nameLabel">
- </label>
- </div>
- <div style="font-size: medium;">
- Profile Pic:
- <img id="imgProfilePic" />
- </div>
- <div style="font-size: medium;">
- Bio:
- <label id="bioLabel">
- </label>
- </div>
- </div>
-
- <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
- $(document).ready (function () {
- GetUserDetails();
- });
-
-
- function GetUserDetails() {
- $.ajax({
- type: "GET",
- async: true,
- contentType: "application/json; charset=utf-8",
- url: 'https://api.instagram.com/v1/users/' + instagramaccessid + '?access_token=' + instagramaccesstoken,
- dataType: "jsonp",
- cache: false,
- beforeSend: function () {
- $("#loading").show();
- },
- success: function (data) {
- $('#usernameLabel').text(data.data.username);
- $('#nameLabel').text(data.data.full_name);
- $('#bioLabel').text(data.data.bio);
- document.getElementById("imgProfilePic").src = data.data.profile_picture;
- }
- });
- }
Run the application.
Get Recent Photos
- <div>
- <h1>
- Recent Photos</h1>
- <div id="PhotosDiv">
- <ul id="PhotosUL">
- </ul>
- </div>
- </div>
- <div style="clear:both;"></div>
-
-
-
- function GetInstagramPhotos() {
- $("#PhotosUL").html("");
- $.ajax({
- type: "GET",
- async: true,
- contentType: "application/json; charset=utf-8",
-
- url: 'https://api.instagram.com/v1/users/' + instagramaccessid + '/media/recent?access_token=' + instagramaccesstoken,
-
-
-
-
-
-
-
-
-
-
- dataType: "jsonp",
- cache: false,
- beforeSend: function () {
- $("#loading").show();
- },
- success: function (data) {
- $("#loading").hide();
- if (data == "") {
- $("#PhotosDiv").hide();
- } else {
-
- $("#PhotosDiv").show();
- for (var i = 0; i < data["data"].length; i++) {
- $("#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>");
- }
-
- }
- }
-
- });
- }
-
- <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- GetInstagramPhotos();
- });
OutputGet Popular Photos
- <div>
- <h1>
- Popular Pictures</h1>
- <div id="PopularPhotosDiv">
- <ul id="photosUL1">
- </ul>
- </div>
- </div>
-
-
-
- function GetPopularPhotos() {
- $("#photosUL1").html("");
- $.ajax({
- type: "GET",
- async: true,
- contentType: "application/json; charset=utf-8",
-
- url: "https://api.instagram.com/v1/media/popular?access_token=" + instagramaccesstoken,
- dataType: "jsonp",
- cache: false,
- beforeSend: function () {
- $("#loading").show();
- },
- success: function (data) {
- $("#loading").hide();
- if (data == "") {
- $("#PopularPhotosDiv").hide();
- } else {
- $("#PopularPhotosDiv").show();
- for (var i = 0; i < data["data"].length; i++) {
- $("#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>");
- }
-
- }
- }
-
- });
- }
-
-
- <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- GetPopularPhotos();
- });
OutputConclusion
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.