It doesn't matter if we are using REST, SOAP, or even if we are using web services at all, but one of the main points of creating an API is to allow other developers to use our services. And this means that it becomes even more important to document the API.
In ASP.NET Web API, we can do this by using XML comments, plus an additional tool which can be added to our project using NuGet.
XML comments should be added to:
- Controllers
- Controller methods
- Model classes passed in or returned from controller methods (both the classes themselves and their properties)
Example of such comments:
/// <summary>
/// MyController represents resources belonging to the currently logged in user.
/// </summary>
[Route("api/v1/my")]
public class MyController : Controller
{
/// <summary>
/// This method returns the final grades in all completed courses for the given student.
/// </summary>
[Route("grades")]
public List<GradeDTO> Grades()
{
....
}
/// <summary>
/// (etc., the documentation should explain in detail what this method does!
/// Provide examples if necessary, and make it as detailed as possible.)
/// </summary>
/// <returns>A list of Event</returns>
/// <params name=id>The id of the schedule</params>
[Route("schedule/{id:int}")]
public List<Event> Schedule(int id)
{
....
}
}
// In another file:
/// <summary>
/// This class represents a given final grade in a given course.
/// </summary>
public class GradeDTO
{
/// <summary>
/// The final grade. Note that the type is string, because the grade could
/// be a string value such as "Failed", "Evaluated" etc.
/// </summary>
public string Grade { get; set; }
/// <summary>
/// The ID of the course in which the grade was given.
/// </summary>
public int CourseInstanceID { get; set; }
}
The process to extract these comments and ensure they show up in a special documentation page is described here, the section "Adding Help Pages to an Existing Project" is more general. Do note that this tutorial is from 2013 and could be slightly out of date.
It is worth mentioning that the documentation tool assumes that all types (i.e. all controllers and model classes) are located in the same assembly, i.e. in the Web API project itself. In a real project, it is highly likely that we will move classes to different projects/assemblies, and this will require some modification to the documentation tool which is being used.
A number of similar tools exist, this blogpost lists a few of them.
SOAP services can be described using WSDL (Web Services Description Language), which returns what a web service is capable of doing in machine-readable format. This allows us to create tools which can generate wrappers for SOAP services, such that they can be called from C# code as if they were regular classes.
Apparently, there is no similar universally-accepted standard for REST services. WADL seems to have a similar role as WSDL, but is not used much. It is even not entirely certain that such standard is indeed needed.