This project provides JSON:API media type support for Spring HATEOAS.

© 2020 The original authors.

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

Fundamentals

For further understanding of this document, please be aware of both

The following documentation assumes that the reader knows above documents.

JSON:API

JSON:API is a widely adapted hypermedia format. You can find a list of implementations and tools here. Answers to a few questions, e.g. related to HAL, you can find here.

Anytime a client supplies an Accept header with application/vnd.api+json, you can expect something like this:

{
  "jsonapi": {
    "version": "1.0"
  },
  "data": {
    "id": "1",
    "type": "movies",
    "attributes": {
      "title": "The Shawshank Redemption",
      "year": 1994,
      "rating": 9.3
    },
    "relationships": {
      "directors": {
        "data": {
          "id": "2",
          "type": "directors"
        }
      }
    },
    "links": {
      "self": "http://localhost:8080/api/movies/1"
    }
  },
  "included": [
    {
      "id": "2",
      "type": "directors",
      "attributes": {
        "name": "Frank Darabont"
      }
    }
  ],
  "links": {
    "self": "http://localhost:8080/api/movies?page[number]=0,page[size]=1",
    "next": "http://localhost:8080/api/movies?page[number]=1&page[size]=1",
    "last": "http://localhost:8080/api/movies?page[number]=249&page[size]=1"
  },
  "meta": {
    "page": {
      "number": 0,
      "size": 1,
      "totalPages": 250,
      "totalElements": 250
    }
  }
}

Integration in your Backends

To enable the JSON:API media type you just need to add this module as a dependency to your project.

Maven:

<dependency>
    <groupId>com.toedter</groupId>
    <artifactId>spring-hateoas-jsonapi</artifactId>
    <version>0.6.0</version>
</dependency>

Gradle:

implementation 'com.toedter:spring-hateoas-jsonapi:0.6.0'

The latest published snapshot version is 0.7.0-SNAPSHOT. If you want to try it out, please make sure to add oss.sonatype.org/content/repositories/snapshots/ as repository to your Maven or Gradle configuration.

Representation Models

All Spring HATEOAS representation models are rendered as JSON:API. Consider a simple Movie Class as base for a Spring HATEOAS entity model:

@Data
@NoArgsConstructor
@AllArgsConstructor
@With
public class Movie {
    private String id;
    private String title;
}

An EntityModel.of(new Movie("1", "Star Wars")) is then rendered as

{
  "data": {
    "id": "1",
    "type": "movies",
    "attributes": {
      "title": "Star Wars"
    }
  }
}

In JSON:API, the id field must be of type String. But in your model you can use any Class and toString() is used for conversion. So, if the id attribute of Movie would be of type long, the rendered JSON:API would be the same. The JSON:API type is automatically generated of the pluralized, lower case, simple class name. This is best practice, since then most likely the type matches the URL (end) of the corresponding REST collection resource.

You can configure if you want to use non-pluralized class names, see Configuration

Annotations

The goal of this implementation is to automate the mapping from/to JSON:API as convenient as possible for the developer.

There are 3 new Annotations provided by this project:

  • @JsonApiId to mark a JSON:API id

  • @JsonApiType to mark a JSON:API type

  • @JsonApiRelationships to mark a JSON:API relationship

The use of these annotations is optional. For the mapping of the id, the following rules apply in order:

  • the annotation @JsonApiId is used on a field

  • the annotation @JsonApiId is used on a method

  • the annotation @Id (javax.persistence.Id) is used on a field

  • the annotation @Id (javax.persistence.Id) is used on a method

  • the entity (base for representation models) provides an attribute id

For the mapping of the type, the following rules apply in order:

  • the annotation @JsonApiType is used on a field

  • if no annotation is present, the pluralized, lower case, simple class name of the entity will be used

You can configure if you want to use non-pluralized class names, see Configuration

As an example, consider the class

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Movie2 {
    @Id
    private String myId;
    private String title;
    @JsonApiType
    private String type;
}

Then, EntityModel.of(new Movie2("1", "Star Wars", "my-movies"))) will be rendered as

{
  "data": {
    "id": "1",
    "type": "my-movies",
    "attributes": {
      "title": "Star Wars"
    }
  }
}

JSON:API Builder

If you want to use JSON:API relationships or included data, you can use the JsonApiModelBuilder. The following example shows how to create a JSON::API representation model using the JsonApiModelBuilder

import static com.toedter.spring.hateoas.jsonapi.JsonApiModelBuilder.jsonApiModel;
Movie movie = new Movie("1", "Star Wars");
final RepresentationModel<?> jsonApiModel = jsonApiModel().model(movie).build();

Consider that you want to express the relationships of movies to their directors. A simple Director class could look like:

@Data
@NoArgsConstructor
@AllArgsConstructor
@With
public class Director {
    private String id;
    private String name;
}

You can build a relationship from a movie to a director like

Movie movie = new Movie("1", "Star Wars");
Director director = new Director("1", "George Lucas");
final RepresentationModel<?> jsonApiModel =
        jsonApiModel().model(movie)
                .relationship("directors", EntityModel.of(director))
                .build();

The representation model will be rendered as

{
  "data": {
    "id": "1",
    "type": "movies",
    "attributes": {
      "title": "Star Wars"
    },
    "relationships": {
      "directors": {
        "data": {
          "id": "1",
          "type": "directors"
        }
      }
    }
  }
}

If you want to include the related resources in the JSON:API output, you can build included director resources like

Movie movie = new Movie("1", "The Matrix");
Movie relatedMovie = new Movie("2", "The Matrix 2");
Director director1 = new Director("1", "Lana Wachowski");
Director director2 = new Director("2", "Lilly Wachowski");

final RepresentationModel<?> jsonApiModel =
        jsonApiModel().model(movie)
                .relationship("directors", director1)
                .relationship("directors", director2)
                .relationship("relatedMovies", EntityModel.of(relatedMovie))
                .included(director1)
                .included(director2)
                .build();

The representation model will be rendered as

{
  "data": {
    "id": "1",
    "type": "movies",
    "attributes": {
      "title": "The Matrix"
    },
    "relationships": {
      "relatedMovies": {
        "data": {
          "id": "2",
          "type": "movies"
        }
      },
      "directors": {
        "data": [
          {
            "id": "1",
            "type": "directors"
          },
          {
            "id": "2",
            "type": "directors"
          }
        ]
      }
    }
  },
  "included": [
    {
      "id": "1",
      "type": "directors",
      "attributes": {
        "name": "Lana Wachowski"
      }
    },
    {
      "id": "2",
      "type": "directors",
      "attributes": {
        "name": "Lilly Wachowski"
      }
    }
  ]
}

The following example shows the creation of a more complex JSON:API specific representation model with a paged model as base. The builder supports adding both pagination metadata and pagination links.

Movie movie = new Movie("1", "The Matrix");
Movie relatedMovie = new Movie("2", "The Matrix 2");
Director director1 = new Director("1", "Lana Wachowski");
final EntityModel<Director> director1EntityModel = EntityModel.of(director1);
Director director2 = new Director("2", "Lilly Wachowski");
final EntityModel<Director> director2EntityModel = EntityModel.of(director2);

final RepresentationModel<?> jsonApiModel1 =
        jsonApiModel()
                .model(movie)
                .relationship("directors", director1EntityModel)
                .relationship("directors", director2EntityModel)
                .relationship("relatedMovies", EntityModel.of(relatedMovie))
                .build();

Movie movie2 = new Movie("3", "Star Wars");
Director director3 = new Director("3", "George Lucas");
final EntityModel<Director> director3EntityModel = EntityModel.of(director3);

final RepresentationModel<?> jsonApiModel2 =
        jsonApiModel()
                .model(movie2)
                .relationship("directors", director3EntityModel)
                .build();

List<RepresentationModel<?>> movies = new ArrayList<>();
movies.add(jsonApiModel1);
movies.add(jsonApiModel2);

PagedModel.PageMetadata pageMetadata = new PagedModel.PageMetadata(2, 1, 100, 50);
Link selfLink = Link.of("http://localhost/movies").withSelfRel();
final PagedModel<RepresentationModel<?>> pagedModel = PagedModel.of(movies, pageMetadata, selfLink);

RepresentationModel<?> pagedJasonApiModel =
        jsonApiModel()
                .model(pagedModel)
                .included(director1EntityModel)
                .included(director2EntityModel)
                .included(director3EntityModel)
                .pageMeta()
                .pageLinks("http://localhost/movies")
                .build();

This model will be rendered as

{
  "data": [
    {
      "id": "1",
      "type": "movies",
      "attributes": {
        "title": "The Matrix"
      },
      "relationships": {
        "relatedMovies": {
          "data": {
            "id": "2",
            "type": "movies"
          }
        },
        "directors": {
          "data": [
            {
              "id": "1",
              "type": "directors"
            },
            {
              "id": "2",
              "type": "directors"
            }
          ]
        }
      }
    },
    {
      "id": "3",
      "type": "movies",
      "attributes": {
        "title": "Star Wars"
      },
      "relationships": {
        "directors": {
          "data": {
            "id": "3",
            "type": "directors"
          }
        }
      }
    }
  ],
  "included": [
    {
      "id": "1",
      "type": "directors",
      "attributes": {
        "name": "Lana Wachowski"
      }
    },
    {
      "id": "2",
      "type": "directors",
      "attributes": {
        "name": "Lilly Wachowski"
      }
    },
    {
      "id": "3",
      "type": "directors",
      "attributes": {
        "name": "George Lucas"
      }
    }
  ],
  "links": {
    "self": "http://localhost/movies",
    "first": "http://localhost/movies?page[number]=0&page[size]=2",
    "prev": "http://localhost/movies?page[number]=0&page[size]=2",
    "next": "http://localhost/movies?page[number]=2&page[size]=2",
    "last": "http://localhost/movies?page[number]=49&page[size]=2"
  },
  "meta": {
    "page": {
      "number": 1,
      "size": 2,
      "totalPages": 50,
      "totalElements": 100
    }
  }
}

Creating Resources with HTTP POST

To create new REST resources using HTTP POST, you can provide JSON:API formatted JSON as input. For example, a POST with the body:

{
  "data": {
    "attributes": {
      "title": "Batman Begins"
    }
  }
}

will be deserialized to an EntityModel<Movie> automatically. You can also create REST resources that contain JSON:API relationships. You just have to annotate the underlying domain model class, with JsonApiRelationships(<relationship name>)

For example, a POST with the body:

{
  "data": {
    "type": "movies",
    "attributes": {
      "title": "New Movie"
    },
    "relationships": {
      "directors": {
        "data": [
          {
            "id": "1",
            "type": "directors"
          },
          {
            "id": "2",
            "type": "directors"
          }
        ]
      }
    }
  }
}

will be deserialized to an EntityModel<Movie> with a filled list of directors, where ONLY the id attribute of each director is set. The REST controller then has to interpret those relationships and bind the real director objects to the movie.

Here is an example of a class using the annotation:

@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
@With
public class MovieWithDirectors extends Movie {
    @JsonApiType
    String myType = "movies";

    @JsonIgnore
    @JsonApiRelationships("directors")
    List<Director> directors;
}
If you use the annotation JsonApiRelationships on an attribute of a Java class, the content will NOT be serialized automatically to JSON:API relationships. This is on purpose, please us the JsonApiModelBuilder to decide, which relationships and included objects you want to return.

Configuration

There are several options how to change the output of the JSON:API rendering.

For a specific JSON:API configuration, you can create a Spring bean of type JsonApiConfiguration. Currently, you can configure

  • if the JSON:API version should be rendered automatically, the default is false.

  • if JSON:API types should be rendered as pluralized or non pluralized class names, the default is pluralized.

  • if page information of a PagedModel should be rendered automatically as JSON:API meta object, the default is true.

  • if a specific Java class should be rendered with a specific JSON:API type. This is useful when representation model classes should get the JSON:API type of the domain model or when derived classes should get the JSON:API type of the super class. See example below.

Since the JSON:API recommendation contains square brackets in the request parameter names, make sure you provide the following configuration in your Spring application.properties when using Tomcat: server.tomcat.relaxed-query-chars= [,]

Here is an example how you would implement a JSON:API configuration:

@Bean
JsonApiConfiguration jsonApiConfiguration() {
    return new JsonApiConfiguration()
            .withJsonApiVersionRendered(true)
            .withPluralizedTypeRendered(false)
            .withTypeForClass(MovieRepresentationModelWithoutJsonApiType.class, "my-movies");
}

Error Handling

To create JSON:API compliant error messages, you can use JsonApiErrors and JsonApiError

Here is an example how to produce an error response:

return ResponseEntity.badRequest().body(
        JsonApiErrors.create().withError(
                JsonApiError.create()
                        .withAboutLink("http://movie-db.com/problem")
                        .withTitle("Movie-based problem")
                        .withStatus(HttpStatus.BAD_REQUEST.toString())
                        .withDetail("This is a test case")));

The result would be rendered as:

{
  "errors": [
    {
      "links": {
        "about": "http://movie-db.com/problem"
      },
      "status": "400 BAD_REQUEST",
      "title": "Movie-based problem",
      "detail": "This is a test case"
    }
  ]
}