Thursday, April 3, 2014

Consuming RESTful Web Services

Here is a quick and easy way to consume and deserialize a RESTful web service.

1:  Uri uri = new Uri(@"https://somewebsite.com/api/completions?token=abcde12345");  
2:      HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);  
3:      webRequest.MaximumResponseHeadersLength = -1;  
4:      WebResponse ws = webRequest.GetResponse();  
5:      JavaScriptSerializer ser = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };  
6:      ResultsCollection res = ser.Deserialize<ResultsCollection>(new StreamReader(ws.GetResponseStream()).ReadToEnd());  

To deal with dynamic responses, I find it quite useful to handle this in the POCO class for example:

1:  public class ResultsCollection  
2:    {  
3:      private string status;  
4:      private List<Result> data;  
5:      public string Status  
6:      {  
7:        get { return status; }  
8:        set { status = value; }  
9:      }  
10:      public List<Result> Data  
11:      {  
12:        get { return data; }  
13:        set { data = value; }  
14:      }  
15:    }  
16:    public class Result  
17:    {  
18:      private string username;  
19:      private string last_name;  
20:      private string first_name;  
21:      private string name;  
22:      private string email;  
23:      private string course_name;  
24:      private string created;  
25:      private int result;  
26:      public string Username  
27:      {  
28:        get { return username; }  
29:        set { username = value; }  
30:      }  
31:      public string Last_name  
32:      {  
33:        get { return last_name; }  
34:        set { last_name = value; }  
35:      }  
36:      public string First_name  
37:      {  
38:        get { return first_name; }  
39:        set { first_name = value; }  
40:      }  
41:      public string Name  
42:      {  
43:        get { return name; }  
44:        set { name = value; }  
45:      }  
46:      public string Email  
47:      {  
48:        get { return email; }  
49:        set { email = value; }  
50:      }  
51:      public string Course_name  
52:      {  
53:        get { return course_name; }  
54:        set { course_name = value; }  
55:      }  
56:      public string Created  
57:      {  
58:        get { return created; }  
59:        set { created = value; }  
60:      }  
61:      public int Score  
62:      {  
63:        get { return result; }  
64:        set { result = value; }  
65:      }  
66:    }