Heather McLean

Thoughts on agile methodologies and leadership.

REST in .NET

without comments

After a discussion of the merits of various web service technologies with a colleague of mine, I decided to do a little programming exercise. I felt I hadn’t really gotten to do any seriously complex programming in a while, so it was nice to exercise my brain a bit and learn some new things. I basically implemented a REST web service stack in .NET. It has both a server and client model. For the client, it’s as simple as decorating an interface:

[RestWebClient(Url = "http://local.yahooapis.com/MapsService/V1")]
public interface IYahooTrafficService : IRestWebService
{
    [RestNoun("trafficData", Method = RestHttpMethod.GET)]
    [return: RestReturnType(RestReturnType.Xml)]
    XmlDocument GetTrafficData(string appid, string street, string city, string state);
}

The example here uses the Yahoo Traffic Data API. Once the interface is created, I can get a concrete instance through the RestWebClient factory:

IYahooTrafficService svc = RestWebClient.Create<IYahooTrafficService>();
XmlDocument xdoc = svc.GetTrafficData("YdnDemo", "1771 LBJ Fwy", "Dallas", "TX");

And voila! Traffic data:

Example of output from the Yahoo! Traffic Data API.

Example of output from the Yahoo! Traffic Data API.

Pretty simple, and it works with a variety of REST interfaces. It can also handle complex types through XML and binary serialization as well as straight binary streams, such as image files. The server piece works similar to the client; decorate a class with attributes to describe the service contract, and an HttpHandler does the rest.

This was particularly challenging on the client piece because I had to learn the System.Reflection.Emit namespace, which I had never used before, and it requires an in-depth knowledge of MSIL. So that was difficult at first, frustrating most of the time, and rewarding in the end.

At some point I would like to clean up the code and release it as open source. Some other folks might actually find it useful. It definitely needs some heavy refactoring first, though.

Written by Heather

September 2nd, 2009 at 10:52 am

Leave a Reply