Tuesday, April 17, 2012

Trying out the SocialCast REST API

Lately, I’ve been integrating an EPiServer site with SocialCast, a social network for businesses. I thought I’d share some code on how I chose to do this.

SocialCast has quite an extensive REST API which allows the developer to retrieve pretty much all the information needed. In this blog post I’ll show you how to retrieve the most recent status updates and how to post a new message to SocialCast.

IMPORTANT!
1)
The data from SocialCast can either be retrieved as JSON or XML, I’ve chosen JSON for these examples. 
2) I’ve used https://demo.socialcast.com/ in these examples. In order to click on the links I’ve supplied further down you need to be logged into the demo site (username and password is supplied next to login box).

First, let’s create a class called WebRequester which I’ve made internal as I only want it to be accessible from within the same assembly. This class contains two methods, the first being GetRequestInJson which creates a WebRequest towards SocialCast and returns the response. The second method is a generic method called DeserializeResponse which uses a JavaScriptSerializer to deserialize the HttpWebResponse to an object.

1: internal static class WebRequester

2: {

3:    public static HttpWebResponse GetRequestinJson(string url, string username, string password, string method)

4:    {

5:       try

6:       {

7:          var webRequest = WebRequest.Create(url) as HttpWebRequest;

8:          if (webRequest != null)

9:          {

10:            webRequest.Credentials = new NetworkCredential(username, password);

11:            webRequest.Method = method;

12:            webRequest.ServicePoint.Expect100Continue = false;

13:            webRequest.Timeout = 20000;

14:            webRequest.ContentType = "application/json";

15:            return (HttpWebResponse)webRequest.GetResponse();

16:         }

17:      }

18:      catch (Exception e)

19:      {

20:          // Implement your own error handling (logging etc.)

21:      }

22:      return null;

23:    }

24:  

25:    public static T DeserealizeResponse<T>(HttpWebResponse httpWebResponse) where T : new()

26:    {

27:       try

28:       {

29:          Stream responseStream = httpWebResponse.GetResponseStream();

30:          if (responseStream != null)

31:          {

32:             string responseBody;

33:             using (StreamReader sr = new StreamReader(responseStream))

34:             {

35:                responseBody = sr.ReadToEnd();

36:             }

37:             JavaScriptSerializer jsSerializer = new JavaScriptSerializer();

38:             return jsSerializer.Deserialize<T>(responseBody);

39:          }

40:       }

41:       catch (Exception e)

42:       {

43:          // Implement your own error handling (logging etc.)

44:       }

45:       return new T();

46:    }

47: }

Creating the SocialCast class

Next we’ll create a class called SocialCast which will contain one method called GetMostRecentStatusUpdates and another one called PostMessage. Both these methods use the WebRequester class we created above in order to execute the web requests and deserialize the web response.

1: public static class SocialCast

2: {

3:    public static MessageCollection GetMostRecentStatusUpdates()

4:    {

5:       HttpWebResponse httpWebResponse = WebRequester.GetRequestinJson("https://demo.socialcast.com/api/messages.json?page=1&per_page=3&content_filter=status_message&comments_limit=0",

6: "emily@socialcast.com", "demo", "GET");

7:       if (httpWebResponse != null)

8:          return WebRequester.DeserealizeResponse<MessageCollection>(httpWebResponse);

9:       return new MessageCollection();

10:    }

11:  

12:    public static bool PostMessage(string message)

13:    {

14:        string postUrl = string.Format("https://demo.socialcast.com/api/messages.json?message[body]={0}", message);

15:       HttpWebResponse httpWebResponse = WebRequester.GetRequestinJson(postUrl,

16: "emily@socialcast.com", "demo", "POST");

17:       if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.Created)

18:          return true;

19:       return false;

20:    }

21: }

Yes, I am aware of the fact that the code above contains the username and password to the demo site, but I don’t consider that a problem as SocialCast themselves have made it public on https://demo.socialcast.com/

So let’s go through the GetMostRecentStatusUpdates method. The URL and the querystring parameters supplied to the WebRequester is explained here: http://developers.socialcast.com/api-documentation/api/messages/index/. After the WebRequest is executed and the response is returned, the response is deserialized to a MessageCollection object. The MessageCollection class contains the information we need from SocialCast and it has to match the structure of the JSON response. So the MessageCollection class could for example look like this:

1: public class MessageCollection

2: {

3:     public Message[] messages { get; set; }

4: }

5:  

6: public class Message

7: {

8:     public User user { get; set; }

9:     public string body { get; set; }

10:    public string created_at { get; set; }

11:    public string likes_count { get; set; }

12:    public string url { get; set; }

13: }

14:  

15: public class User

16: {

17:    public string name { get; set; }

18:    public string url { get; set; }

19: }

As you can see the MessageCollection simply contains an array of Message objects, and this structure matches the structure of the JSON response seen here: https://demo.socialcast.com/api/messages.json.

Using the SocialCast class

1: MessageCollection messagesCollection = SocialCast.GetMostRecentStatusUpdates();

2:  

3: bool success = SocialCast.PostMessage("This is a test message which I'm posting to SocialCast");

That’s it :)

No comments:

Post a Comment