Thursday, June 2, 2016

Web Services made easy with HttpClient & JSON.NET

I have intended to write this for a while. As a Sales Engineer for Xamarin, and now Microsoft, I go through a lot of the same scenarios when working with companies to get up and running with Xamarin and mobile development. As one example, there is almost a 99% guarantee that the first apps these companies plan to build will communicate with an external data source in some way, almost always using web services.

Now, there is a high likelihood this is not a new topic to those who read this blog, but as a believer in the "Lucky 10,000" from xkcd, I figure this information is still worth sharing. To those of you who were unaware of today's content, congrats as you are one of the lucky 10,000 today! What I have to share should make your mobile journey all the easier.

Now it should be noted that I recognize web services are a broad topic, lots of solutions out there. One quick hop over to the Xamarin documentation alone lists a few:

The main three built into the Xamarin tooling are on consuming RESTful, SOAP and WCF services. For the remainder of this post I will focus on REST as I find it to be the most straightforward to consume.

Consuming REST services really falls down to two main parts. Consumption of the service itself, and then consumption of the data received. As you likely have guessed, there are two tools available to help make this process much more straightforward. For the service, Microsoft's HTTP Client libraries and for the data, JSON.NET. When combined, it can be as simple as three lines of code to communicate with an external service and acquire data. Below is a sample of what that code would look like:

var httpClient = new HttpClient ();
var json = await httpClient.GetStringAsync ($"");
var result = JsonConvert.DeserializeObject (json);

What you see above is both parts. Line one creates the HttpClient followed by actually making a REST call to grab you data. The third line is part two, parsing the resulting json into something more C# readable. If you have not used JSON.NET before, it really is something of magic under the hood. Basically, all you need to do is provide it a valid json file, and then pass a constructed C# object for it to parse into. In the above example, it will try to parse your json into the class "MY_DATA_OBJECT". 

To use a more "practical" example, I am a big fan of Blizzard games and recently wrote an app to play with some of the community API's available, found here The main goal was to just do a bit of poking and write a simple Warcraft character display app. Nothing complex, make some calls to load character data, item sets, etc. In  order to grab the basic character profile in my app, I have the following code:

var httpClient = new HttpClient (new NativeMessageHandler ());
var json = await httpClient.GetStringAsync ($"{
Constants.APIKEY}" );

var res = JsonConvert.DeserializeObject (json); 

In this case, I am pulling the data for my Paladin, Deaus, from the Muradin server. The resulting JSON looked like this:

     "lastModified": 1426370270000,
     "name": "Deaus",
     "realm": "Muradin",
     "battlegroup": "Vengeance",
     "class": 2,
     "race": 3,
     "gender": 0,
     "level": 100,
     "achievementPoints": 7620,
     "thumbnail": "muradin/10/119640842-avatar.jpg",
     "calcClass": "b",
     "faction": 0,
     "totalHonorableKills": 1961

On the C# side, I would create a class called CharData which would look something like this:

public class CharData
    public long lastModified { get; set; }
    public string name { get; set; }
    public string realm { get; set; }
    public string battlegroup { get; set; }
    public int class { get; set; }
    public int race { get; set; }
    public int gender { get; set; }
    public int level { get; set; }
    public int achievementPoints { get; set; }
    public string thumbnail { get; set; }
    public string calcClass { get; set; }
    public int faction { get; set; }
    public int totalHonorableKills { get; set; }

JSON.NET does the rest of the work, taking advantage of the json tags and matching them to the appropriate C# properties, and instantiates/populates my data for me. The best part of all of this? All of this is PCL compliant so it is located 100% inside my shared code!

One useful tool to expedite the process even more is the website This website will take json data and auto generate the resulting C# class for you, at least at a base level.

As a note, not all REST end points are so easily configured, but HttpClient is actually quite flexible. I was also recently poking around a community made Hearthstone API,, and their .NET API's are powered through unirest ( To get this to work I had to add a couple of DefaultRequestHeader paramters to match the documentation there. Still, rather straight forward to communicate with.

That is about it. While this does put some requirement to set up good REST endpoints for your mobile applications, it tends to be worth the effort. Even if you have legacy WCF systems or complicated back ends, I have found that companies that have made exposed REST front ends to facilitate the communication can help streamline the entire process and, as you see above, can really make consumption on the mobile side quite easy. Until next time!

1 comment: