I’m a software engineer with a passion for REST, TDD and clean code, Web Security and Data Mining. Baeldung is about all of these and more. Eugen is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

REST API Discoverability and HATEOAS

11.14.2011
| 7247 views |
  • submit to reddit

This is the forth of a series of articles about setting up a secure RESTful Web Service using Spring 3.1 and Spring Security 3.1 with Java based configuration. The article will focus on Discoverability of the REST API, HATEOAS and practical scenarios driven by tests.

The REST with Spring Series:

Introducing REST Discoverability

Discoverability of an API is a topic that doesn’t get enough well deserved attention, and as a consequence very few APIs get it right. It is also something that, if done right, can make the API not only RESTful and usable but also elegant.

To understand discoverability, one needs to understand that constraint that is Hypermedia As The Engine Of Application State (HATEOAS); this constraint of a RESTful API is about full discoverability of actions/transitions on a Resource from Hypermedia (Hypertext really), as the only driver of application state. If interaction is to be driven by the API through the conversation itself, concretely via Hypertext, then there can be no documentation, as that would coerce the client to make assumptions that are in fact outside of the context of the API.

Also, continuing this logical train of thought, the only way an API can indeed be considered RESTful is if it is fully discoverable from the root and with no prior knowledge – meaning the client should be able to navigate the API by doing a GET on the root. Moving forward, all state changes are driven by the client using the available and discoverable transitions that the REST API provides in representations (hence Representational State Transfer).

In conclusion, the server should be descriptive enough to instruct the client how to use the API via Hypertext only, which, in the case of a HTTP conversation, may be the Link header.

Concrete Discoverability Scenarios (Driven by tests)

So what does it mean for a REST service to be discoverable? Throughout this section, we will test individual traits of discoverability using Junit, rest-assured and Hamcrest. Since the REST Service has been secured in part 3 of the series, each tests need to first authenticate before consuming the API. Some utilities for parsing the Link header of the response are also necessary.

Discover the valid HTTP methods

When a RESTful Web Service is consumed with an invalid HTTP method, the response should be a 405 METHOD NOT ALLOWED; in addition, it should also help the client discover the valid HTTP methods that are allowed for that particular Resource, using the Allow HTTP Header in the response:

@Test
public void
 whenInvalidPOSTIsSentToValidURIOfResource_thenAllowHeaderListsTheAllowedActions(){
   // Given
   final String uriOfExistingResource = this.restTemplate.createResource();
   
   // When
   Response res = this.givenAuthenticated().post( uriOfExistingResource );
   
   // Then
   String allowHeader = res.getHeader( HttpHeaders.ALLOW );
   assertThat( allowHeader, AnyOf.<String> anyOf(
    containsString("GET"), containsString("PUT"), containsString("DELETE") ) );
}
Discover the URI of newly created Resource

The operation of creating a new Resource should always include the URI of the newly created resource in the response, using the Location HTTP Header. If the client does a GET on that URI, the resource should be available:

@Test
public void whenResourceIsCreated_thenURIOfTheNewlyCreatedResourceIsDiscoverable(){
   // When
   Foo unpersistedResource = new Foo( randomAlphabetic( 6 ) );
   Response createResponse = this.givenAuthenticated().contentType( MIME_JSON )
    .body( unpersistedResource ).post( this.paths.getFooURL() );
   final String uriOfNewlyCreatedResource = createResp
    .getHeader( HttpHeaders.LOCATION );
   
   // Then
   Response response = this.givenAuthenticated()
    .header( HttpHeaders.ACCEPT, MIME_JSON ).get( uriOfNewlyCreatedResource );
   
   Foo resourceFromServer = response.body().as( Foo.class );
   assertThat( unpersistedResource, equalTo( resourceFromServer ) );
}

The test follows a simple scenario: a new Foo resource is created and the HTTP response is used to discover the URI where the Resource is now accessible. The tests then goes one step further and does a GET on that URI to retrieve the resource and compares it to the original, to make sure that it has been correctly persisted.

Discover the URI to GET All Resources of that type

When we GET a particular Foo instance, we should be able to discover what we can do next: we can list all the available Foo resources. Thus, the operation of retrieving an resource should always include in its response the URI where to get all the resources of that type, again making use of the Link header:

@Test
public void whenResourceIsRetrieved_thenURIToGetAllResourcesIsDiscoverable(){
   // Given
   String uriOfExistingResource = this.restTemplate.createResource();
   
   // When
   Response getResponse = this.givenAuthenticated().get( uriOfExistingResource );
   
   // Then
   String uriToAllResources = HTTPLinkHeaderUtils.extractURIByRel
    ( getResponse.getHeader( "Link" ), "collection" );
   
   Response getAllResponse = this.givenAuthenticated().get( uriToAllResources );
   assertThat( getAllResponse.getStatusCode(), is( 200 ) );
}

The test tackles a thorny subject of Link Relations in REST: the URI to retrieve all resources uses the rel=”collection” semantics. This type of link relation has not yet been standardized, but is already in use by several microformats and proposed for standardization. Usage of non-standard link relations opens up the discussion about microformats and richer semantics in RESTful web services.

Other potential discoverable URIs and microformats

Other URIs could potentially be discovered via the Link header, but there is only so much the existing types of link relations allow without moving to a richer semantic markup such as defining custom link relations, the Atom Publishing Protocol or microformats, which will be the topic of another article.

For example it would be good if the client could discover the URI to create new resources when doing a GET on a specific resource; unfortunately there is no link relation to model create semantics. Luckily it is standard practice that the URI for creation is the same as the URI to GET all resources of that type, with the only difference being the POST HTTP method.

Conclusion

This article covered the some of the traits of discoverability in the context of a RESTful web service, discussing HTTP method discovery, the relation between create and get, discovery of the URI to get all resources, etc. In the next articles I will focus on discovering the API starting with the root, pagination, custom link relations, the Atom Publishing Protocol and the actual implementation of Discoverability in the REST service with Spring. In the meantime, check out the github project.

If you read this far, you should follow me on twitter here.

Original at RESTful Web Service Discoverability from the REST with Spring series.

Published at DZone with permission of Eugen Paraschiv, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)