Posts
202
Comments
1112
Trackbacks
51
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:

   1:  <resource rel="self" href="http://localhost:1700/dinners/1">
   2:    <link rel="http://localhost:1700/rels/rsvps" href="http://localhost:1700/dinners/1/rsvps" />
   3:    <link rel="http://localhost:1700/rels/update-dinner" href="http://localhost:1700/dinners/1" />
   4:    <link rel="http://localhost:1700/rels/delete-dinner" href="http://localhost:1700/dinners/1" />
   5:    <DinnerId>1</DinnerId>
   6:    <Title>MVC Dinner</Title>
   7:    <Description>This dinner will be for MVC developers.</Description>
   8:    <Address>123 Main Street</Address>
   9:    <Country>USA</Country>
  10:    <EventDate>7/1/2011 12:00:00 AM</EventDate>
  11:  </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.

   1:  using System;
   2:  using System.Collections.Generic;
   3:   
   4:  namespace NerdDinnerWebApi.ResourceModel
   5:  {
   6:      public class LinkRelationMetadata
   7:      {
   8:          public LinkRelationMetadata()
   9:          {
  10:              this.HypermediaItems = new List<HypermediaMetadata>();
  11:          }
  12:   
  13:          public string Rel { get; set; }
  14:   
  15:          public string Description { get; set; }
  16:   
  17:          public string HttpMethod { get; set; }
  18:   
  19:          public string Schema { get; set; }
  20:   
  21:          public string Example { get; set; }
  22:   
  23:          public string MediaType { get; set; }
  24:   
  25:          public List<HypermediaMetadata> HypermediaItems { get; set; }
  26:      }
  27:  }

This will allow me to “write my documentation” like this:

   1:  linkRelations.AddItem(LinkRelationNames.Dinner, HttpMethod.Get, "Get a dinner resource for Nerd Dinner.", typeof(Dinner),
   2:      new HypermediaMetadata { Rel = LinkRelationNames.UpdateDinner, ConditionsDescription = "Always present as a resource." },
   3:      new HypermediaMetadata { Rel = LinkRelationNames.DeleteDinner, ConditionsDescription = "Always present as a resource." },
   4:      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.

 

   1:  private static void AddItem(this Dictionary<string, LinkRelationMetadata> dict, string rel, HttpMethod httpMethod, string description, Type responseMessageType, params HypermediaMetadata[] hypermedia)
   2:  {
   3:      var instance = PopulateInstance(responseMessageType);
   4:      var xml = ToHalRepresentation(instance);
   5:           
   6:      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() });
   7:  }
   8:   
   9:  private static object PopulateInstance(Type type)
  10:  {
  11:      var instance = Activator.CreateInstance(type) as HalResource;
  12:      if (instance == null)
  13:      {
  14:          return null;
  15:      }
  16:   
  17:      // First populate HAL-specific properties
  18:      instance.Rel = "self";
  19:      instance.HRef = "http://example.com/foo";
  20:   
  21:      instance.Links = new List<Link>
  22:      {
  23:          new Link { Rel = "abc", HRef = "http://example.com/abc" },
  24:          new Link { Rel = "xyz", HRef = "http://example.com/xyz" }
  25:      };
  26:   
  27:      foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty))
  28:      {
  29:          if (property.IsValueTypeOrString())
  30:          {
  31:              SetDummyValue(instance, property);
  32:          }
  33:      }
  34:   
  35:      return instance;
  36:  }
  37:   
  38:  private static string ToHalRepresentation(object instance)
  39:  {
  40:      var formatter = new HalMediaTypeFormatter();
  41:      var stream = new MemoryStream();
  42:      formatter.WriteToStream(instance.GetType(), instance, stream, null, null);
  43:      stream.Position = 0;
  44:      var xml = new StreamReader(stream).ReadToEnd();
  45:      return xml;
  46:  }
  47:   
  48:  private static void SetDummyValue(object instance, PropertyInfo property)
  49:  {
  50:      if (property.PropertyType == typeof(int))
  51:      {
  52:          instance.SetValue(property, 123);
  53:      }
  54:      else if (property.PropertyType == typeof(string))
  55:      {
  56:          instance.SetValue(property, "abc");
  57:      }
  58:      else if (property.PropertyType == typeof(DateTime))
  59:      {
  60:          instance.SetValue(property, DateTime.Now);
  61:      }
  62:      else
  63:      {
  64:          throw new InvalidOperationException("Unsupported type for setting a dummy value.");
  65:      }
  66:  }

 

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

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Net;
   4:  using System.Net.Http;
   5:  using System.ServiceModel;
   6:  using System.ServiceModel.Web;
   7:  using Microsoft.ApplicationServer.Http;
   8:  using Microsoft.ApplicationServer.Http.Dispatcher;
   9:  using NerdDinnerWebApi.ResourceModel;
  10:   
  11:  namespace NerdDinnerWebApi.Services.Services
  12:  {
  13:      [ServiceContract]
  14:      public class LinkRelationService
  15:      {
  16:          static readonly Dictionary<string, LinkRelationMetadata> linkRelations = LinkRelationInitializer.Create();
  17:   
  18:          [WebGet(UriTemplate = "{rel}")]
  19:          public HttpResponseMessage<LinkRelationMetadata> Get(string rel)
  20:          {
  21:              LinkRelationMetadata linkRelation = null;
  22:              if (!linkRelations.TryGetValue(rel, out linkRelation))
  23:              {
  24:                  var notFoundResponse = new HttpResponseMessage();
  25:                  notFoundResponse.StatusCode = HttpStatusCode.NotFound;
  26:                  notFoundResponse.Content = new StringContent("Link Relation '" + rel + "' not found");
  27:                  throw new HttpResponseException(notFoundResponse);
  28:              }
  29:              return new HttpResponseMessage<LinkRelationMetadata>(linkRelation);
  30:          }
  31:      }
  32:  }

 

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:

   1:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   2:  <html xmlns="http://www.w3.org/1999/xhtml">
   3:    <head>
   4:      <title>Link relation - @Model.Rel</title>
   5:      <style>{copied from WCF help page but omitted here for brevity}</style>
   6:    </head>
   7:    <body>
   8:      <div id="content">
   9:        <p class="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><a href="@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:          <pre class="response-xml">@FormatXmlForHtml(Model.Example)</pre>
  43:        </p>
  44:   
  45:        <p>
  46:          The following is the response Schema (XSD):
  47:          <pre class="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:

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.

posted on Monday, June 6, 2011 8:32 PM Print
Comments
Gravatar
# re: Documenting Link Relations with Web API
Jakob Strauch
9/2/2011 1:18 PM
I think, the example implies somehow an operation centric style. Why use update-dinner and delete-dinner relationtypes on the same uri? it´s a resource with an uniform interface, thus supporting GET,PUT,POST,DELETE.

If it´s not allowed to use one of the methods, the server will return a MethodNotAllowed error (i think 403).

(by the way: what means rsvps?)
Gravatar
# re: Documenting Link Relations with Web API
Steve
9/2/2011 1:23 PM
@Jakob - I don't disagree - the "REST Police" would probably be able to make a case against me for that. :) The more typical way is what you describe. However, the way I showed above was more an option for being able to use hypermedia to express to a consumer *in advance* whether or not the execution is allowed rather than them finding that out *after* the fact by receiving a 405.

Post Comment

Title *
Name *
Email
Comment *  
 

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud