Consume RESTful Web Services in C#

The acronym REST stands for Representational State Transfer, this basically means that each unique URL is a representation of some object. It embraces a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URLs. It’s different from the more traditional SOAP. Not gonna go into the details of the differences between the two as it will be endless. This link from AjaxPatterns has a pretty in-depth explanation of RESTful services.

http://ajaxpatterns.org/RESTful_Service

There are many ways to consume a RESTful service in C#. Since all it needs is the URL we can create an Http Web Request and then process the response. Another way is to use the more advanced WCF, which I’ve came across this link here:

http://blogs.msdn.com/b/pedram/archive/2008/04/21/how-to-consume-rest-services-with-wcf.aspx

It’s very good as it uses WCF to do the serialization and it eliminates the need to do manual transformation. But as always, you don’t get nothing for free. In this case it’s the same as all other situations when you let the framework do your dirty laundry – you lost flexibility. In addition, it might be hard for someone viewing your code to fully understand what’s going on right away because some stuff is in the web.config, some in code, and some in attributes.

A lot of the publicly available RESTful web services, such as Google Map API, Flicker’s API, Bing platform’s services, support both JSON and XML format. In the JavaScript world I prefer JSON, but when it comes to C# I still find XML much easier to work with for the simple fact that LINQ to XML is right at your fingertip.

Therefore, I find that using LINQ to XML and XPath transformation is pretty easy to consume a RESTful services and extract the information that you need. I am using Google Map API as an example here:

   1: XElement root = XElement.Load("http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=Toronto");

   2: if (decimal.TryParse(root.XPathSelectElement("//result//geometry//location//lat").Value, out latitude) &&

   3:     decimal.TryParse(root.XPathSelectElement("//result//geometry//location//lat").Value, out longitude))

   4: {

   5:     result.Add(new BusinessObjects.Location

   6:     {

   7:         Coordinate = new BusinessObjects.LatLng { Latitude = latitude, Longitude = longitude },

   8:         FormattedAddress = root.XPathSelectElement("//result//geometry//location//lat").Value,

   9:     });

  10: }

As you can see, only a few lines of code. I am calling Google Map’s geocoding service and looking for Toronto. As soon as I have loaded the response XML into XElement I used XPath to get the latitude and longitude, as well as the formatted address in order to construct my own Location object, which might then contain other business logics and validation requirements specific to my application.

Well, that’s it. Here’s the XML response of the link above:

<?xml version="1.0" encoding="utf-8" ?>
<GeocodeResponse>
    <status>OK</status>
    <result>
        <type>locality</type>
        <type>political</type>
        <formatted_address>Toronto, ON, Canada</formatted_address>
        <address_component>
            <long_name>Toronto</long_name>
            <short_name>Toronto</short_name>
            <type>locality</type>
            <type>political</type>
        </address_component>
        <address_component>
            <long_name>Toronto Division</long_name>
            <short_name>Toronto Division</short_name>
            <type>administrative_area_level_2</type>
            <type>political</type>
        </address_component>
        <address_component>
            <long_name>Ontario</long_name>
            <short_name>ON</short_name>
            <type>administrative_area_level_1</type>
            <type>political</type>
        </address_component>
        <address_component>
            <long_name>Canada</long_name>
            <short_name>CA</short_name>
            <type>country</type>
            <type>political</type>
        </address_component>
        <geometry>
            <location>
                <lat>43.6525000</lat>
                <lng>-79.3816667</lng>
            </location>
            <location_type>APPROXIMATE</location_type>
            <viewport>
                <southwest>
                    <lat>43.5231891</lat>
                    <lng>-79.6377855</lng>
                </southwest>
                <northeast>
                    <lat>43.7815330</lat>
                    <lng>-79.1255479</lng>
                </northeast>
            </viewport>
            <bounds>
                <southwest>
                    <lat>43.4582970</lat>
                    <lng>-79.6392190</lng>
                </southwest>
                <northeast>
                    <lat>43.8554580</lat>
                    <lng>-79.0024810</lng>
                </northeast>
            </bounds>
        </geometry>
    </result>
</GeocodeResponse>

By Bryan Xu

Tagged with: ,
Posted in .NET, C# Programming
One comment on “Consume RESTful Web Services in C#
  1. Alan says:

    “you don’t get nothing for free” is a double negative and means you get everything for free. I think you mean “you don’t get anything for free” or “you get nothing for free”

Leave a Reply