Getting Twitter Profile Image Via C# With 1.1 API

May 1 2013

If you know someone's Twitter handle and would like to display their twitter avatar on your website, here's some code to get the URL of their avatar.  First, you'll need to register at http://dev.twitter.com and acquire a ConsumerKey, ConsumerSecret, Token and TokenSecret -- now that Twitter supports application only authentication, there isn't any handshaking involved; you just need to craft up the right OAuthCredentials for a ProtectedResource, which the Hammock library does for you. Love that library: you can get it here: https://github.com/danielcrenna/hammock or grab it as a NuGet package: http://nuget.org/packages/Hammock

Here’s the code; nothing too fancy:

using System;
using Hammock;
using Hammock.Authentication.OAuth;
using Hammock.Web;
using Newtonsoft.Json.Linq;

namespace ExternalServices
{
    public class TwitterAvatarLookup : ITwitterAvatarLookup
    {
        const string ConsumerKey = "";
        const string ConsumerSecret = "";
        const string Token = "";
        const string TokenSecret = "";

        public string GetTwitterAvatarUrl(string twitterHandle)
        {
            string avatarUrl = string.Empty;
            var request = new RestRequest
            {
                Credentials = new OAuthCredentials
                {
                    Type = OAuthType.ProtectedResource,
                    SignatureMethod = OAuthSignatureMethod.HmacSha1,
                    ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                    ConsumerKey = ConsumerKey,
                    ConsumerSecret = ConsumerSecret,
                    Token = Token,
                    TokenSecret = TokenSecret,
                }
            };
            request.Path =
                string.Format(
                    "https://api.twitter.com/1.1/users/lookup.json?screen_name={0}&include_entities=0&include_rts=0",
                    twitterHandle);

            request.Method = WebMethod.Get;
            RestClient client = new RestClient();
            try
            {
                RestResponse response = client.Request(request);
                JArray jArray = JArray.Parse(response.Content);
                avatarUrl = (string)jArray[0]["profile_image_url_https"];

            }
            catch (Exception)
            {
                return "default.png";
            }
            return avatarUrl;
        }

    }
}

If you know more than one handle whose avatar you need to get, the API supports passing multiple user handles; see https://dev.twitter.com/docs/api/1.1/get/users/lookup