Adding Affordances to Our API

Learn how to add affordances to an API.

Augmenting hypermedia with affordances

We’ve created hypermedia and registered some relevant links. Is something missing?

So far, the main JSON format shown has been either plain old JSON or the link-loaded hypermedia format of HAL. It’s one of the most widely adopted formats for hypermedia, probably due to its simplicity. It’s also the default format that Spring HATEOAS renders.

There’s an issue, though.

If we provide both a GET and a PUT operation at the same URI, a HAL document renders that as one link. Our users will have no idea that there are actually two different things available.

Even if we attempt to force a solution by registering different operations using different link relations, it still won’t show what attributes the PUT operation needs in order to effect change.

Leaving it up to the consumer to stumble around doesn’t sound very effective. This is where Spring HATEOAS steps in. Namely, by providing an API to augment our hypermedia with affordances.

A classic example of this is when viewing a single Item resource, we’re afforded the means to update that resource.

Spring HATEOAS provides the means to connect related methods. In this case, the link to the GET operation can be connected to the PUT operation.

How does this help? It’s true that, rendered as HAL, we still see a single link. Another hypermedia format like HAL-FORMS, however, can take advantage of this connection to render additional information. Any affordance-friendly media type can leverage this extra metadata.

To compare plain hypermedia with affordance hypermedia, the usage of Spring HATEOAS’ Affordances API is done in a separate AffordancesItemController, which is a RestController.

Defining Put

Before creating this connection between GET and PUT, we must first define the PUT method in the AffordancesItemController class:

Get hands-on with 1200+ tech skills courses.