THERE are certainly lots of articles around that explain how to create your own WCF REST service. However, I couldn’t find many that explained how to consume a REST service. So this is what I’ll concentrate on in this article… so read on..

Background Info

The reason I’m writing this article is because I recently designed an solution that utilises a RESTful API Service. This solution communicates with the RESTful service to GET and POST data using their given API. Here is a quick link to the wiki if you want to learn more about the REST architecture.

REST API

REST APIs are pretty cool when you think about it. There are already lots of sites out there provide an API for developers to communicate with to access their services. Below is a quick list to some well known sites and their API documentation:

With APIs you can integrate any data service exposed over the web and have it seemlessly integrated into your very own application!

REST API – Requests

Accessing the API is pretty easy. Especially if you just want to grab data from the RESTful service. Communication with a REST API is done using basic HTTP GET, POST, PUT and DELETE requests. And for this reason, a REST API can be access via your web browser for all GET requests.

:: Here’s a Twitter example – http://search.twitter.com/search.json?q=clouds
Navigating to the above URL, you are basically executing a Twitter search on the word ‘clouds’. Twitter then provides you a response to your HTTP GET request in the form of JSON text. JSON and XML are two most common REST response types.

::Here’s a Google Maps example – http://maps.googleapis.com/maps/api/directions/xml?origin=sydney city&destination=melbourne&sensor=false
Navigating to the above URL, you are querying the Google Map directions API for directions to Melbourne from Sydney! Here the response is provided as XML

Steps to consume a REST service

Here is a the list of topics that will be covered, and by the end of this article, hopefully you have enough information to integrate this solution into your own applications!

  1. Setting up the WCF REST Starter Kit for Visual Studio
  2. Building your HttpClient
  3. Initiate HTTP GET requests
  4. Generate .Net classes from the REST Response (XML)
  5. Transform the response into your .Net classes
  6. Sample POST
  7. Sample PUT
  8. Sample DELETE

1. Setting up the WCF REST Starter Kit for Visual Studio

First up you will need some Microsoft libraries… Goto the Microsoft WCF REST website and download the latest WCF REST Starter Kit. Install the kit.  Once done, you will have 2 libraries that you will need to reference, these DLLs are located in the folder C:\Program Files\Microsoft WCF REST\WCF REST Starter Kit Preview 2\Assemblies\

These are:

  • Microsoft.Http and
  • Microsoft.Http.Extensions

Add these as library references to your project.

2. Building your HttpClient

Next up, lets create a static method to return a httpClient. You will be using the httpClient object to create and process all your API calls to the REST Service. Create a class called HttpClientManager and add the following ‘using’ statement for the two libraries you just referenced.


using Microsoft.Http;
using System.Xml.Serialization;

This class will have one static method that returns a HttpClient object all set up and ready to go. There are 3 main parts to this function, and depending on your environment and infrastructure you can choose to include or skip certain sections. The 3 sections are:

  1. Setting the base url for the httpClient
  2. Setting the Proxy configurations
  3. Setting the Authentication headers for the REST service

1. Setting the base url for the httpClient

Each API library will have a standard base url for which all other API calls are ‘nested’ under this url. For example, our Google Map directions API has a base URL of:  http://maps.googleapis.com/maps/api/

2. Setting the Proxy configurations

If your corporate network contains a firewall/proxy. You may need to configure your httpClient to use the correct Proxy Credentials.  You can optionally skip this step if no proxy is required.

3. Setting the Authentication headers for the REST service

Most API services out there will require some sort of authentication. This will most likely be a token or some sort, which may or may not include MD5 hashes, other encryption, salts and/or other secure data transfers in order for the remote service to recognise who you really are. You can optionally skip this step if no authentication is required by the API service.

Below is the snippet that covers point one and two above.

public class HttpClientManager
{

    public static Microsoft.Http.HttpClient GetHttpClient()
    {
        string clientURL = "http://maps.googleapis.com/maps/api/";
        Microsoft.Http.HttpClient httpClient = new Microsoft.Http.HttpClient(clientURL);
        httpClient.DefaultHeaders.ContentType = "application/xml";

        // PROXY - If required
        System.Net.WebProxy p = new System.Net.WebProxy(proxy, int.Parse(proxyPort));
        p.Credentials = new System.Net.NetworkCredential(userName, password, domain);
        httpClient.TransportSettings.Proxy = p;

        return httpClient;
    }
}

If Authentication is required, you will need to determine what data to pass with the HTTP Request; and how. In the following code, we add the ‘authentication string’ as part of the HTTP Request Header called ‘Authorization’.

        // PROXY - If required
        // .....

        // AUTHENTICATION
        string authString = "xxxxxxxx";
        httpClient.DefaultHeaders["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(authString));

        return httpClient;

Keep in mind, the API service you use will outline what data needs to be passed; the format they expect, and any additional processing that is required from the authentication string.

That’s it.  Now you have a re-usable static method to call whenever you need a new HttpClient object.

Next up, you will be using the method above to grab a HttpClient object, and then writing a few additional lines of code to perform the various API calls for GET, POST, PUT and DELETE requests!

3. Initiate HTTP GET requests

Lets jump right into the GET request.  Your first API GET request will programmatically call Google Maps’ Directions API and perform a search. The structure of your method will be of the following:

  • Grab a new HttpClient
  • Determine the URL of the API call – and add this to the HttpClient’s Base URL address
  • Determine any Query String Parameters that need to be passed through – add this to the API path
  • Perform the API GET request
  • Read the Response

Below is the simplest GET request you can have. It adds to the Base URL – the API location ‘directions/xml’. And then appends the search parameters as query strings.  The Base URL + the API location + the Parameter string makes up the full URL to Google’s Direction Search API.

To initiate the request, we invoke the Get() method on the httpClient object.
This returns a HttpResponseMessage object for us to interpret, and handle the response data as necessary. Here we are just storing the returned XML response into a local string variable.

    public static class GoogleDirectionsManager
    {

        public static void GetDirections(string origin, string destination)
        {
            HttpClient httpClient = HttpClientManager.GetHttpClient();

            // I'm sure you can think of a better way of managing these parameters!
            string url = "directions/xml";
            string param = "?origin=" + origin + "&destination=" + destination + "&sensor=false";

            HttpResponseMessage resp = httpClient.Get(url + param);
            string respString = resp.Content.ReadAsString();
        }
    }

To finish off our GetDirections() method, we are missing one elegant part… the Entity (or POCO) transformation.

The above method returns the response as XML. If your application wants to manipulate the XML directly, then thats all you require. However going one step further I will show how you can easily transfrom the XML into .Net Entity Classes. Not only does this provide extra readability, you can pass these entity objects to other layers of your application in a nice and clean manner.

3. Generate .Net classes from the REST Response (XML)

  • First up: Run your application, and grab the XML response as a string. Copy this into Notepad.  And save the file. Lets call it “Direction.xml”.
  • Open up Visual Studio’s command prompt (this is not the stand windows cmd promt). You will find the shortcut in your Start Menu -> Microsoft Visual Studio -> Visual Studio Tools -> Visual Studio Command Prompt menu
  • Goto the directory that you saved the “Direction.xml” file into
  • Run the following two commands in order, one after the other:
    • xsd Direction.xml
    • xsd Direction.xsd /c
  • The first command creates a XSD file from the XML file
  • The second command creates a CS class file from the XSD file

Once you have done that, you will find a “Directions.CS” file – Copy/Paste the contents of the CS file into your application.  That’s it!!  You have generated a ‘Direction’ C# class from your XML response!

5. Transform the response into your .Net classes

To do this, instead of reading the HttpResponseMessage as a string, we need to use the ReadAsXmlSerializable() method, and then define the type of object we want to transform the response text into. To achieve this, replace the above ReadAsString() method with a call to ReadAsXmlSerializable() as shown below.  Declare the Class type we generated in step.4 — and thats it.

The ReadAsXMLSerializable() method will do all the work, and at the end, you will have a fully functional Direction Object with all properties and nested classes in one!!

    public static class GoogleDirectionsManager
    {
        public static void GetDirections(string origin, string destination)
        {
            HttpClient httpClient = HttpClientManager.GetHttpClient();

            // I'm sure you can think of a better way of managing these parameters!
            string url = "directions/xml";
            string param = "?origin=" + origin + "&destination=" + destination + "&sensor=false";

            HttpResponseMessage resp = httpClient.Get(url + param);

            Entities.Direction d = resp.Content.ReadAsXmlSerializable<Entities.Direction>();
        }
    }

6. Sample POST

That’s all the hard part done!  The other Http Request methods are pretty straight foward, all you need to do is invoke the corresponding httpClient method of either Post(), Put() or Delete().

A Http POST request is all about ‘creating’ new data via the REST Service. Where a Http PUT request is all about ‘updating’ existing data. And of course Http DELETE removes existing data.

Http POST  and PUT will require ONE additional step. And that is to include the data you want to create or update with the API call. In the examples below, I will refer to a generic Ticketing system instead of Google Map.  POST will allow our system to POST a Ticket via XML to the API – in order to create a new ticket in their system.  Likewise a PUT will allow our system to UPDATE a Ticket (also via XML) to the API – in order to update an existing record.

Sending data via a POST/PUT command requires the data to be included in the Http Request as part of its Http Content. Also known as the Http Body.  Just like sending an email, there is a subject section and a body section!

Below is an example of how you will POST a new Ticket with 2 simple properties (Email and Comment) to the API located in the sub-path (tickets.xml). :

note: The structure of the content is purely dependant on the REST Service. You will need to consult the API to know what structure and data to pass through.

        public static void CreateTicket(Entities.Ticket ticket)
        {
            HttpClient httpClient = HttpClientManager.GetHttpClient();

            // I'm sure you can think of a better way of generating the XML! :-)
            HttpContent content = Microsoft.Http.HttpContent.Create("<ticket><email>test@test.com</email><comment>my comments are here!</comment></ticket>"
                                                            , "application/xml");

            string url = "tickets.xml";
            HttpResponseMessage resp = httpClient.Post(url, content);

            string respString = resp.Content.ReadAsString();
        }

7. Sample PUT

Http PUT is similar to a Http POST.  The differences would be the API path to navigate to, and the XML data that you send across the wire. Below we update a Ticket, sending over the email and comment we wish to update the record with.  Everything else… remains the same as above!

        public static void UpdateTicket(Entities.Ticket ticket)
        {
            HttpClient httpClient = HttpClientManager.GetHttpClient();

            // I'm sure you can think of a better way of generating the XML! :-)
            HttpContent content = Microsoft.Http.HttpContent.Create("<ticket><email>test@test.com</email><comment>UPDATED comments!</comment></ticket>"
                                                            , "application/xml");

            string url = "tickets/" + ticket.ID + ".xml";
            HttpResponseMessage resp = httpClient.Put(url, content);

            string respString = resp.Content.ReadAsString();
        }

8. Sample DELETE
A Http DELETE is alot simpler than a Http POST and PUT.  All we need to do is grab the API path to navigate to (which coincidentally will most likely contain the record ID) and execute the httpClient DELETE method.

Below is a snippet that shows you how this is done.

        public static void DeleteTicket(Entities.Ticket ticket)
        {
            HttpClient httpClient = HttpClientManager.GetHttpClient();

            string url = "tickets/" + ticket.ID + ".xml";
            HttpResponseMessage resp = httpClient.Delete(url);

            string respString = resp.Content.ReadAsString();
        }

Conclusion

Well there you have it!!  You now have all the knowledge you need to create you own apps and integrate them with 3rd party APIs out there. It may be alot of information to consume, but once you complete the GET request, you will see how everything clicks in!  Then its smooth sailing from there onwards :-)

Hope this article helped! Have fun!