Professional ASP.NET MVC 4
by Jon Galloway, Phil Haack, Brad Wilson, K. Scott Allen, Scott Hanselman
Exploring APIs Programmatically
An MVC application's controllers and actions are usually a fairly ad-hoc affair, designed solely to suit the display of HTML in the application. Web APIs, on the other hand, tend to be more ordered and planned. Offering the ability to discover APIs at run time enables developers to provide key functionality along with their Web API applications, including things like automatically generated help pages and test client UI.
Developers can acquire the IApiExplorer service from HttpConfiguration.Services and use it to programmatically explore the APIs exposed by the service. For example, an MVC controller could return the IApiExplorer instance from Web API to this snippet of Razor code to list all the available API endpoints. (The output of this code is shown in Figure 11.4.)
@model System.Web.Http.Description.IApiExplorer
@foreach (var api in Model.ApiDescriptions) {
<h1>@api.HttpMethod @api.RelativePath</h1>
if (api.ParameterDescriptions.Any()) {
<h2>Parameters</h2>
<ul>
@foreach (var param in api.ParameterDescriptions) {
<li>@param.Name (@param.Source)</li>
}
</ul>
}
}
In addition to the automatically discoverable information, developers can implement the IDocumentationProvider interface to supplement the API descriptions with documentation text, which could be used to offer richer documentation and test client functionality. Since the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access