RESTful Web Service Discoverability, part 4

This is the fourth 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.

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.

Reference: RESTful Web Service Discoverability, part 4 from our JCG partner Eugen Paraschiv at the baeldung blog.

Related Articles :

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


1 + seven =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.