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 documentation is pluggable, developers can choose to store the documentation in whatever form is convenient, including attributes, stand-alone files, database tables, resources, or whatever best suits the application build process.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset