Creating API documentation
We’ve recently been working on our API and came across the problem of writing documentation for the API.
Having looked at a number of solutions I came up with a simple solution using XML comments within C# and the XML generated by the project during compilation. Here are the steps:
- For any exposed API methods you write, make sure you fully comment the method, including adding your own tags. For example, I also used an <response> comment and <url> comment.
- Go the the projects build properties (right-click Project > Properties > Build). Make sure the XML Documentation check box is checked. During compilation, this will output an XML file into the output directory.
/// <name>get.workspaces.for.user</name>
/// <description>Gets the workspaces for a user.</description>
/// <url>https://api.huddle.net/v1/json/workspaces</url>
/// <method>GET</method>
/// <authentication>User authentication required</authentication>
///
/// <response><!--[CDATA[
/// {"Data":[
/// {"Id":342758,"Title":"My Workspace"},
/// {"Id":343001,"Title":"Team Workspace"}]--></response>
///
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "workspaces",
BodyStyle = WebMessageBodyStyle.Bare)]
ResponseWrapper GetWorkspacesForUser();
Now you need to copy the XML file to your website. There are two ways you can do this:
- Post-build event within a project file.
- NAnt using the “copy” task.
Once copied to the website, you can simply create an aspx page that reads the information and renders it. There are a few ways you can do this, Deserialization, LINQ For XML, or simply using XPath.
I took the opportunity to use LINQ, which provided a solution with very few lines, although it wasn’t quite as readable as I would have liked. LINQ, for me, is very powerful, but doesn’t quite fit with the typical C# syntax.
var xml = XDocument.Load(Server.MapPath("~/API/xml/Huddle.Services.API.xml"));
var items = from item in xml.Descendants("doc").Descendants("members").Descendants("member")
where item.Element("name") != null
orderby item.Element("name").Value
select new RestItem
{
Name = item.Element("name").Value
};
apiUrls.DataSource = items;
apiUrls.DataBind();Anyway, here’s our page (it’s actually two pages, one that shows the methods, and one that shows the details for a method):
For any new methods we add, as long as they are commented correctly, the documentation will be generated during the build. This reduces our workload allowing us to focus on other things.


