Wednesday, March 27, 2013

Annotation-based Documentation Provider for APIExplorer

The APIExplorer is a nice way to automatically build a docs page for your WebAPI RESTful services. The documentation is created using reflection and then the IDocumentationProvider tries to find the textual information about your methods and method parameters.

The problem is that the reference implementation shows how the docs could be retrieved from the XML documentation generated during the compilation of a service. If this is not an option for you, you could use this simple provider which uses System.ComponentModel.DataAnnotations.Display attributes for method decoration:

public class AttributeDocumentationProvider : IDocumentationProvider
 {
     #region IDocumentationProvider Members
 
     public string GetDocumentation( HttpParameterDescriptor parameterDescriptor )
     {
         ReflectedHttpParameterDescriptor reflectedParameterDescriptor = 
             parameterDescriptor as ReflectedHttpParameterDescriptor;
         if ( reflectedParameterDescriptor != null )
         {
             var display = reflectedParameterDescriptor.ParameterInfo
                 .GetCustomAttributes( typeof( DisplayAttribute ), false )
                 .OfType<DisplayAttribute>().FirstOrDefault();
             if ( display != null )
                 return display.Description;
             else
                 return reflectedParameterDescriptor.ParameterInfo.Name;
         }
 
         return string.Empty;
     }
 
     public string GetDocumentation( HttpActionDescriptor actionDescriptor )
     {
         ReflectedHttpActionDescriptor reflectedActionDescriptor = 
             actionDescriptor as ReflectedHttpActionDescriptor;
         if ( reflectedActionDescriptor != null )
         {
             var display = reflectedActionDescriptor.MethodInfo
                 .GetCustomAttributes( typeof( DisplayAttribute ), false )
                 .OfType<DisplayAttribute>().FirstOrDefault();
             if ( display != null )
                 return display.Description;
             else
                 return reflectedActionDescriptor.MethodInfo.Name;
         }
 
         return string.Empty;
     }
 
     #endregion
 }

This way the WebAPI controller could be documented as follows:

public class MyWebAPIController : ApiController
{
    /// <summary>
    /// POST/Create a new Foo
    /// </summary>
    [Display( Description="Create a new instance of Foo")]
    public HttpResponseMessage PostFoo( 
        [Display( Description="Name of the newly created Foo")]
        string fooName 
        )
    {
       ...

An advantage of this approach is that the docs are part of the assembly metadata and there is no need for external XML documentation files.

No comments: