Getting more properties through Spring HATEOAS

HATEOAS is a standard (though they use the word constraint) on a REST-based architecture. The idea is that the client can find out about everything via hyperlinks in the responses. Spring has a good overview on it and how it works. And, naturally, Spring has some excellent support for it. Make an interface, slap an annotation on it, and you are good to go. With Spring Boot and Spring Data JPA it really is that easy.

But say you want to add a bit more information in your response. Maybe you want to include the ID of the joined entities in the entity you are serving up. By default, it will only have a link to it, which you then have to make a client call to get, and then another call to see the whole thing.

I have set up a simple Spring Boot app that has some quotes in it. By default, by just going to http://localhost:8080/quotes/ I get the following in the response

  {

  {
    "_embedded" : {
      "quotes" : [ {
        "text" : "Join Us Now And Share The Software",
        "_links" : {
          "self" : {
            "href" : "http://localhost:8080/quotes/1"
          },
          "quote" : {
            "href" : "http://localhost:8080/quotes/1"
          },
          "author" : {
            "href" : "http://localhost:8080/quotes/1/author"
          }
        }
      },
  .....
  }

Hey I get all my data in a response with just an annotation! That’s pretty cool. But note that it has just the text field in it. I don’t have any information about the author except where to go to find more information about it. That is HATEOAS.

If I follow http://localhost:8080/quotes/1/author I get the this:

  {
    "firstName" : "Richard",
    "lastName" : "Stallman",
    "_links" : {
      "self" : {
        "href" : "http://localhost:8080/authors/1"
      },
      "author" : {
        "href" : "http://localhost:8080/authors/1"
      }
    }
  }

And there is the author information, including more of where to go for more information, as well the canonical URL (which is what self contains).

This is fine for a single quote but what if you were listing out each quote at http://localhost:8080/quotes ? If you have a 100 quotes in there, you would have to make a 101 requests to the server to get the author information. Isn’t there a way we can get all that information in one request? Yes there is, using Projections.

Projections are documented fairly well in the Spring HATEOAS documentation, but I had to connect the dots to see how this would help me. The implementation is fairly straightforward. Essentially you make an interface with some annotations and one or more getter methods. See the following:

This says: “Make a projection on the class, and combine the author’s first and last names and call it”

  @Projection(name = "AuthorNames", types = {Quote.class})
  public interface QuoteProjection {

      @Value("#{target.author.firstName} #{target.author.lastName}")
      public String getAuthorName();

  }

Now we see the in the JSON

  {
        "authorName" : "Richard Stallman",
        "_links" : {
          "self" : {
            "href" : "http://localhost:8080/quotes/1"
          },
          "quote" : {
            "href" : "http://localhost:8080/quotes/1{?projection}",
            "templated" : true
          },
          "author" : {
            "href" : "http://localhost:8080/quotes/1/author"
          }
        }

But wait!  We are missing the text field from the object itself! Well it seems we have to add it to our Projection interface:

  @Projection(name = "AuthorNames", types = {Quote.class})
  public interface QuoteProjection {

      @Value("#{target.author.firstName} #{target.author.lastName}")
      public String getAuthorName();

      @Value("#{target.text}")
      public String getText();

  }

And now we can see both properties at http://localhost:8080/quotes/

  {
     "text" : "Join Us Now And Share The Software",
     "authorName" : "Richard Stallman",
     "_links" : {
       "self" : {
         "href" : "http://localhost:8080/quotes/1"
       },
       "quote" : {
         "href" : "http://localhost:8080/quotes/1{?projection}",
         "templated" : true
       },
       "author" : {
         "href" : http://localhost:8080/quotes/1/author
       }

     }
   },

So it’s fairly easy to put more properties in your JSON responses when you are using Spring HATEOAS. You can see my little quotes project at https://github.com/squarepegsys/spring-hateoas-quotes .

About the Author

Mike Hostetler profile.

Mike Hostetler

Principal Technologist

Mike has almost 20 years of experience in technology. He started in networking and Unix administration, and grew into technical support and QA testing. But he has always done some development on the side and decided a few years ago to pursue it full-time. His history of working with users gives Mike a unique perspective on writing software.

One thought on “Getting more properties through Spring HATEOAS

  1. Jesse says:

    Very useful thing to know. Thanks for the information!

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Blog Posts
Why we started using JSON Schema in our internal Helm charts
Helm 3 supports validating the provided chart values against a JSON Schema. While it may be quicker to get started in your chart development without a schema, we found it valuable for a number of […]
Rewriting files in Google Cloud Storage
Rewriting Files in GCP Note: even though this code is in Python, this should be the same idea in JavaScript, Go, etc. I wrote the following to copy a file from one Google Cloud Storage […]
Interpreting Spatial Data in the Age of COVID-19
As 2020 has come to an end, many are eager to leave the mess of COVID-19 behind with the new year and gain a fresh start. Unfortunately, new cases are still soaring across the United […]
Building a Better Mousetrap
Recently, my daughter (age 6) was into building “mousetraps” out of shoe boxes. These were more or less comfortable cardboard mouse houses complete with beds, rooms, everything a mouse could want or need and not […]