DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. REST API Discoverability and HATEOAS

REST API Discoverability and HATEOAS

Eugen Paraschiv user avatar by
Eugen Paraschiv
·
Nov. 14, 11 · Interview
Like (3)
Save
Tweet
Share
15.53K Views

Join the DZone community and get the full member experience.

Join For Free

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:

  • Part 1 – Bootstrapping a web application with Spring 3.1 and Java based Configuration
  • Part 2 – Building a RESTful Web Service with Spring 3.1 and Java based Configuration
  • Part 3 – Securing a RESTful Web Service with Spring Security 3.1
  • Part 5 – REST Service Discoverability with Spring
  • Part 6 – Basic and Digest authentication for a RESTful Service with Spring Security 3.1
  • Part 7 – REST Pagination in Spring
  • Part 8 – Authentication against a RESTful Service with Spring Security
  • Part 9 – ETags for REST with Spring

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.

REST Web Protocols API Discoverability Web Service Spring Security Spring Framework Uniform Resource Identifier Links

Published at DZone with permission of Eugen Paraschiv, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Test Design Guidelines for Your CI/CD Pipeline
  • Debezium vs DBConvert Streams: Which Offers Superior Performance in Data Streaming?
  • Tracking Software Architecture Decisions
  • Public Key and Private Key Pairs: Know the Technical Difference

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: