Documenting Link Relations with Web API

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:

<resource rel="self" href="http://localhost:1700/dinners/1">
  <link rel="http://localhost:1700/rels/rsvps" href="http://localhost:1700/dinners/1/rsvps" />
  <link rel="http://localhost:1700/rels/update-dinner" href="http://localhost:1700/dinners/1" />
  <link rel="http://localhost:1700/rels/delete-dinner" href="http://localhost:1700/dinners/1" />
  <DinnerId>1</DinnerId>
  <Title>MVC Dinner</Title>
  <Description>This dinner will be for MVC developers.</Description>
  <Address>123 Main Street</Address>
  <Country>USA</Country>
  <EventDate>7/1/2011 12:00:00 AM</EventDate>
</resource>

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):

linkRelDocPage

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

using System;
using System.Collections.Generic;
 
namespace NerdDinnerWebApi.ResourceModel
{
    public class LinkRelationMetadata
    {
        public LinkRelationMetadata()
        {
            this.HypermediaItems = new List<HypermediaMetadata>();
        }
 
        public string Rel { get; set; }
 
        public string Description { get; set; }
 
        public string HttpMethod { get; set; }
 
        public string Schema { get; set; }
 
        public string Example { get; set; }
 
        public string MediaType { get; set; }
 
        public List<HypermediaMetadata> HypermediaItems { get; set; }
    }
}

This will allow me to "write my documentation" like this:

linkRelations.AddItem(LinkRelationNames.Dinner, HttpMethod.Get, "Get a dinner resource for Nerd Dinner.", typeof(Dinner),
    new HypermediaMetadata { Rel = LinkRelationNames.UpdateDinner, ConditionsDescription = "Always present as a resource." },
    new HypermediaMetadata { Rel = LinkRelationNames.DeleteDinner, ConditionsDescription = "Always present as a resource." },
    new HypermediaMetadata { Rel = LinkRelationNames.Rsvps, ConditionsDescription = "Always present as a resource." });

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.

private static void AddItem(this Dictionary<string, LinkRelationMetadata> dict, string rel, HttpMethod httpMethod, string description, Type responseMessageType, params HypermediaMetadata[] hypermedia)
{
    var instance = PopulateInstance(responseMessageType);
    var xml = ToHalRepresentation(instance);

    dict.Add(rel.Replace("http://localhost:1700/rels/", string.Empty), new LinkRelationMetadata { Rel = rel, HttpMethod = httpMethod.ToString(), MediaType = "application/vnd.nerddinner.hal+xml", Description = description, Example = xml, HypermediaItems = hypermedia.ToList() });
}
 
private static object PopulateInstance(Type type)
{
    var instance = Activator.CreateInstance(type) as HalResource;
    if (instance == null)
    {
        return null;
    }
 
    // First populate HAL-specific properties
    instance.Rel = "self";
    instance.HRef = "http://example.com/foo";
 
    instance.Links = new List<Link>
    {
        new Link { Rel = "abc", HRef = "http://example.com/abc" },
        new Link { Rel = "xyz", HRef = "http://example.com/xyz" }
    };
 
    foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty))
    {
        if (property.IsValueTypeOrString())
        {
            SetDummyValue(instance, property);
        }
    }
 
    return instance;
}
 
private static string ToHalRepresentation(object instance)
{
    var formatter = new HalMediaTypeFormatter();
    var stream = new MemoryStream();
    formatter.WriteToStream(instance.GetType(), instance, stream, null, null);
    stream.Position = 0;
    var xml = new StreamReader(stream).ReadToEnd();
    return xml;
}
 
private static void SetDummyValue(object instance, PropertyInfo property)
{
    if (property.PropertyType == typeof(int))
    {
        instance.SetValue(property, 123);
    }
    else if (property.PropertyType == typeof(string))
    {
        instance.SetValue(property, "abc");
    }
    else if (property.PropertyType == typeof(DateTime))
    {
        instance.SetValue(property, DateTime.Now);
    }
    else
    {
        throw new InvalidOperationException("Unsupported type for setting a dummy value.");
    }
}

At this point I'm just populating the dictionary that will be used for the service call which looks like this:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.ServiceModel;
using System.ServiceModel.Web;
using Microsoft.ApplicationServer.Http;
using Microsoft.ApplicationServer.Http.Dispatcher;
using NerdDinnerWebApi.ResourceModel;
 
namespace NerdDinnerWebApi.Services.Services
{
    [ServiceContract]
    public class LinkRelationService
    {
        static readonly Dictionary<string, LinkRelationMetadata> linkRelations = LinkRelationInitializer.Create();
 
        [WebGet(UriTemplate = "{rel}")]
        public HttpResponseMessage<LinkRelationMetadata> Get(string rel)
        {
            LinkRelationMetadata linkRelation = null;
            if (!linkRelations.TryGetValue(rel, out linkRelation))
            {
                var notFoundResponse = new HttpResponseMessage();
                notFoundResponse.StatusCode = HttpStatusCode.NotFound;
                notFoundResponse.Content = new StringContent("Link Relation '" + rel + "' not found");
                throw new HttpResponseException(notFoundResponse);
            }
            return new HttpResponseMessage<LinkRelationMetadata>(linkRelation);
        }
    }
}

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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Link relation - @Model.Rel</title>
    <style>{copied from WCF help page but omitted here for brevity}</style>
  </head>
  <body>
    <div id="content">
      <p class="heading1">Link relation - @Model.Rel</p>
      <p><b>Description: @Model.Description</b></p>
      <table>
        <tr>
          <th>Item</th>
          <th>Description</th>
        </tr>
        <tr>
            <td>HTTP Method</td>
            <td>@Model.HttpMethod</td>
        </tr>
        <tr>
            <td>Media Type</td>
            <td>@Model.MediaType</td>
        </tr>
        <tr>
            <td>Potential Hypermedia</td>
            <td>
                <table>
                    @foreach (var item in @Model.HypermediaItems)
                    {
                        <tr>
                            <td><a href="@item.Rel">@item.Rel</a></td>
                            <td>@item.ConditionsDescription</td>
                        </tr>
                    }
                </table>
            </td>
        </tr>
      </table>
 
      <p>
        The following is an example response:
        <pre class="response-xml">@FormatXmlForHtml(Model.Example)</pre>
      </p>
 
      <p>
        The following is the response Schema (XSD):
        <pre class="response-xml">@FormatXmlForHtml(Model.Schema)</pre>
      </p>
    </div>
  </body>
</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:

linkRelDocPageXml

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.

The complete code sample for this can be downloaded here.

Tweet Post Share Update Email RSS