Share your API calls across Windows 8 Store and Windows Phone 8 Apps

In my previous post I discussed the functional behavior of my Starter Kit, I mentioned API invocation as one of the functionalities that can be abstracted out so you can shared them across platforms using a single library (leveraging the Portable Class Library project template). In this blog post, I will discuss the networking implementation (API Invocation) of my Starter Kit.

Keeping this design goal in mind, I realized that while in a Windows 8 App, a call to the REST API typically uses the HttpClient, in Windows Phone the class is not available -Windows Phone Apps typically use the WebClient for this purpose.  So one option I considered was using the HttpWebRequest/HttpWebResponse classes, however I opted instead for a simpler approach: the portable HttpClient that the .Net Framework team released as a NuGet package.

Nowadays, it is quite safe to assume that a REST API will respond in a JSON format. The Json.Net library is supported in PCL projects and widely used, so definitely a plausible option.

Finally, putting all these ideas together, the following snipped of code, shows a simple static methods that fulfilled the design goals I just discussed.


public static async Task<T> InvokeAsync<T>(Uri apiEndPointUri)

         if (apiEndPointUri == null)
             throw new ArgumentNullException();

         using (var httpClient = new HttpClient())
             var responseBody = await httpClient.GetStringAsync(apiEndPointUri);

             return JsonConvert.DeserializeObject<T>(responseBody);


As you can see from the implementation, the method is expecting as a parameter the URI of the API endpoint, to help facilitate the creation of the URI when you need to use parameters in your request, I use the following method.


public static Uri ApiEndPointUriBuilder(string apiEndPoint, params KeyValuePair<string, string>[] parameters)

            if (string.IsNullOrEmpty(apiEndPoint))
                throw new ArgumentException("Invalid argument. The apiEndPoint, can't be null or empty", "apiEndPoint");

            var blrd = new UriBuilder(apiEndPoint);

            if (parameters != null)
                blrd.Query = string.Join("&", parameters.Select<KeyValuePair<string, string>, string>(p => p.Key == null ? p.Value : p.Key + "=" + p.Value).ToArray<string>());

            return blrd.Uri;




In my next post, I will discuss how I approached the deserialization process in more detail. 

No Comments

Post Reply