Building a Self-Documenting REST API
Article
Building rest endpoints with Drupal 8 is a snap. With the Rest UI module, fieldable entities, and the range of field-types in core, a site-builder can readily toss together a HAL+JSON REST server. Lists can be created with views using the REST export display type.
But any API is only as good as its documentation. Wouldn't it be great if Drupal could build out this documentation for us – and keep it current as we make changes?
REST API Documentation in the PHP World
Looking to our open source PHP cousins in Symfony, the NelmioApiDoc bundle generates documentation by parsing doc-blocks on each controller method.
But in Drupal, the REST endpoints are fully-dynamic methods in the REST module's controller. The REST and Serialization modules integrate with the Entity Field API to dynamically introspect the properties of each entity type and bundle. In theory, we should be able to do the same to build out our documentation by leveraging the information APIs in the Entity-Field and Routing APIs.
Providing Business Rules
We can use Drupal to introspect the available routes and the required fields for each end-point, but we can't capture business rules for each field. First we need to specify those rules for each field. Luckily, if we're doing things right, we've already accomplished this by adding help text when we created the field – so we’ll re-use that to build our documentation.