Friday, November 21, 2014

API documentation using GetApiExplorer() function.

We know documentation and help file is very much needed for any application. It‘s more essential if the application expose any API where program from outer world will communicate. There are many solutions to implement documentation. We can use Sandcastle where we can get complete book like documentation of entire application.

Web API has built in class and functions where we can expose documentation page by using same technology.


In this example we will see to expose documentation using GetApiExplorer() function. So, take one Web API application and Add below action to some Controller class.

public ActionResult Index()
 {
var ApiDescription = GlobalConfiguration.Configuration.Services.GetApiExplorer();
         return View("ApiDesc", ApiDescription);
 }   

We know GlobalConfiguration static class is responsible for configuration in project level and we can access GetApiExplorer() with the help of couple of properties of GlobalConfiguration class.

Now, let’s add View (ApiDesc) where we will show the documentation of API functions. Here is example of sample view.


@Model System.Web.Http.Description.IApiExplorer
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ApiDesc</title>
</head>
<body>
    <div>
    @foreach (var api in Model.ApiDescriptions)
    {
       <h5>@api.HttpMethod @api.RelativePath</h5>
       <p>@api.Documentation</p>
      
       if(api.ParameterDescriptions.Count > 0)
       {
           <h6>Parameters</h6>
           <ul>
           @foreach (var parameter in api.ParameterDescriptions)
           {
               <li>@parameter.Name: @parameter.Documentation (@parameter.Source)</li>
           }
           </ul>
       }
   }
    </div>
</body>
</html>

Before hitting run button please make sure that the ValuesController is present in application, which creates by default in default MVC template. The spatiality of ValuesController is that, this is Api Controller, not MVC controller (Hm, wait, in future we will not see them separately)  or make sure that some api controller is present in applications by containing some actions.

Now, let us run the application and we will see below screen.

As discussed, we are seeing the detail documentation of Web API actions. 

1 comment: