In a previous post, I talked about how to build your own custom Media Type Formatter with the WCF Web API. In this post, I used HAL as the media type to expose an API for Nerd Dinner. There are a core set of guiding principles to building RESTful services and one of those principles is that documentation efforts for a service should be focused on defining the media type(s) and link relations that the service uses. While it’s important to have a consistent pattern for URI design, it’s really not that important in comparison to defining the link relations because clients should just “follow the links” and not have tight coupling to URI’s (i.e., clients shouldn’t have knowledge of what the URI’s look like).

Let’s take the example HAL response that returned a dinner resource in my last post:

The hypermedia shown on lines 2-4 have link relations in URI format (ignore the ugly “localhost:1700” and imagine this was something like “http://nerddinner.com/rels/rsvps”). Since the rel attributes are already in URI format, a common convention is to actually provide the documentation for that link relation at that URI if someone hits that in a browser. This documentation page can contain information such as a human readable description of the purpose of the link relation, what media type should be used in the Accept header, which HTTP verb to use, the format of the resource messages, etc.

How can we produce this documentation when using the WCF Web API? The /help page that comes out of the box in WCF 4 won’t help us much here because that is much more in an RPC style with application/xml and application/json formats that are too generic to match our application’s media type. By leveraging the HAL media type formatter that I’ve previously built, I can use this to help document my link relations to produce a help page that looks like this (this page looks like the WCF /help page simply because I copied their CSS):

There were several steps that went in to producing this page. First I defined a metadata object that I used for documentation purposes.

The AddItem() method above is the key. Specifically, its job is the instantiate an instance of the type and populate it with dummy values (e.g., “abc” for strings, 123 for integers, etc. This implementation is fairly rudimentary right now) – it does this on line #3 below. Then on line #4 it calls the ToHalRepresentation() method which internally leverages the HalMediaTypeFormatter (line #42) to create the example XML representation that will be shown on the screen.

I would like to provide this data in an HTML format when a user agent such as a browser is requesting with an Accept header of “text/html”. To accomplish this, I’ll use my RazorHtmlMediaTypeFormatter which I blogged about here which utilizes Razor *outside* of MVC and *within* the WCF Web API to render this HTML resource:

5: <style>{copied from WCF help page but omitted here for brevity}</style>

6: </head>

7: <body>

8: <divid="content">

9: <pclass="heading1">Link relation - @Model.Rel</p>

10: <p><b>Description: @Model.Description</b></p>

11: <table>

12: <tr>

13: <th>Item</th>

14: <th>Description</th>

15: </tr>

16: <tr>

17: <td>HTTP Method</td>

18: <td>@Model.HttpMethod</td>

19: </tr>

20: <tr>

21: <td>Media Type</td>

22: <td>@Model.MediaType</td>

23: </tr>

24: <tr>

25: <td>Potential Hypermedia</td>

26: <td>

27: <table>

28: @foreach (var item in @Model.HypermediaItems)

29: {

30: <tr>

31: <td><ahref="@item.Rel">@item.Rel</a></td>

32: <td>@item.ConditionsDescription</td>

33: </tr>

34: }

35: </table>

36: </td>

37: </tr>

38: </table>

39:

40: <p>

41: The following is an example response:

42: <preclass="response-xml">@FormatXmlForHtml(Model.Example)</pre>

43: </p>

44:

45: <p>

46: The following is the response Schema (XSD):

47: <preclass="response-xml">@FormatXmlForHtml(Model.Schema)</pre>

48: </p>

49: </div>

50: </body>

51: </html>

This gives me the HTML that is shown in the browser screen shot above. There might also be consumers who want to generate client side types based on the XML and XSD shown in the link relations doc. Screen scraping HTML is not the most user friendly thing for this. Therefore, if someone requests with an Accept header of “application/xml” we can also provide this same data in XML format just using built-in Web API functionality:

This is just a prototype of early thinking. I am very curious to hear what other people think about this approach and how it could potentially be evolved.

Media Type Formatters in the WCF Web API provide a way for the consumer of your service to not only specify the format they want for their response, but also specify the format they are using on their request. Typically the desired response format is specified in the “Accept” request header and the request body format is specified in the “Content-Type” request header. Media types are central to building any RESTful service. Two of the most common media types are “application/xml” and “application/json”. However, to build a truly RESTful service that is hypermedia driven, these media types should not be used. Instead, a media type that indicates the specifics of your application domain and has rich semantics for hypermedia is preferred.

REST is an architectural style that is governed by a guiding set of principles. While adhering to these principles, there is no one right way to do things. Recently, Darrel Miller turned me on the HAL (Hypermedia Application Language) which was created by Mike Kelly. I really like the well-structured style that HAL has – making it easy and flexible to embed hypermedia in your resources. Although HAL is an XML-based media type, it is not just “application/xml” because of the specific rules that govern its format. We *could* accomplish this format with some well placed attributes that control XML serialization but instead let’s create our own custom Media Type Formatter to create the format. Media Type Formatters expose OnWritetoStream() and OnReadFromStream() methods to allow serialization/deserialization. Quite often people think of media type formatters as only being used on the server. However, they can be used on the client side as well to control serialization/deserialization of the requests. The following diagram shows the process of an HTTP request/response and the role that the Media Type Formatter plays:

For my example, I’m going to use the Nerd Dinner domain since it’s something most people are familiar with. I could just use “application/hal” for my media type but instead I’m going to use “application/vnd.nerddinner.hal+xml” to more clearly indicate the specifics of my application’s domain (“vnd” indicates a vendor specific domain). One of the core tenets of REST services is loose coupling between the client and server which allows evolvability. Clients need to know about the bookmark URI (i.e., the “home page” so to speak) but should not have knowledge of any other URIs. Instead clients must understand the link relations (i.e., “rel” attributes of the <link> elements) and just “follow the links.”

If I request my well-known “bookmark URI”, to get a specific dinner, it would look like this:

Notice I passed an Accept header of “application/vnd.nerddinner.hal+xml”. Also notice the three <link> elements that came back in my response – this is my hypermedia. The Link Relations are in URI format and the client must have knowledge of what these mean.

My Dinner class just looks like this:

1: publicclass Dinner : HalResource

2: {

3: publicint DinnerId { get; set; }

4: publicstring Title { get; set; }

5: publicstring Description { get; set; }

6: publicstring Address { get; set; }

7: publicstring ContactPhone { get; set; }

8: publicstring Country { get; set; }

9: public DateTime EventDate { get; set; }

10: publicstring HostedBy { get; set; }

11: }

The HalResource base class just defines the standard HAL attributes:

1: publicabstractclass HalResource

2: {

3: public HalResource()

4: {

5: this.Links = new List<Link>();

6: }

7:

8: publicstring Rel { get; set; }

9: publicstring HRef { get; set; }

10: publicstring LinkName { get; set; }

11: public List<Link> Links { get; set; }

12: }

The code snippet below shows what my custom HalMediaTypeFormatter currently looks like. Notice line #18 in the constructor shows the media types that the formatter is intended to support.

The code is not yet Production ready because it only handles a few primitives types and it is still incomplete with respect to the way HAL handles child collections but it gives a good flavor of *both* serialization/deserialization directions for a custom media type formatter. To tell the Web API to use this formatter, you can just add this configuration to your start up code (e.g., Global.asax or a PreApplicationStartMethod). The key is on line #20 below:

35: dinnerResource.Description.Should().Be("This dinner will be for MVC developers.");

36: dinnerResource.Address.Should().Be("123 Main Street");

37: dinnerResource.EventDate.Should().Be(new DateTime(2011, 7, 1));

38: dinnerResource.Country.Should().Be("USA");

39: dinnerResource.Links.Count.Should().Be(3);

40: }

41: }

42: }

There are a couple of very important things to note in the code above. First, on line #23 I am setting the Accept header of the request (the variable was defined on line #15). Second, when I deserialize the xml to a .NET object on line #27, I pass the formatters in (which is just my HalMediaTypeFormatter) so that it knows how to deal with this request. If I don’t do this correctly, I’ll get an InvalidOperationException: No 'MediaTypeFormatter' is available to read an object of type <Type Name> with the media type <Media Type of Response>.

As you can see from the example above, I’m using the *same* custom Media Type Formatter on both the server *and* the client.

As I mentioned earlier in this post, the coupling between the client and server should be focused on defining the link relations for your media types. Stay tuned for my next post where I’ll show a mechanism for leveraging a media type formatter (like the one shown in this post) to generate documentation for consumers of your service so that consumers can fully understand all hypermedia link relations.