I'm using Spring Boot and HATEOAS to build a REST API and when my API returns a collection, it is wrapped inside a "_embedded" property, like so:
{ "_links":{ "self":{ "href":"http://localhost:8080/technologies" } }, "_embedded":{ "technologies":[ { "id":1, "description":"A", "_links":{ "self":{ "href":"http://localhost:8080/technologies/1" } } }, { "id":2, "description":"B", "_links":{ "self":{ "href":"http://localhost:8080/technologies/2" } } } ] } }
I want the response to be like this:
{ "_links":{ "self":{ "href":"http://localhost:8080/technologies" } }, "technologies":[ { "id":1, "description":"A", "_links":{ "self":{ "href":"http://localhost:8080/technologies/1" } } }, { "id":2, "description":"B", "_links":{ "self":{ "href":"http://localhost:8080/technologies/2" } } } ] }
My TechnologiesController:
@RestController @ExposesResourceFor(Technology.class) @RequestMapping(value = "/technologies") public class TechnologiesController { ... @ResquestMapping(method = RequestMethod.GET, produces = "application/vnd.xpto-technologies.text+json") public Resources<Resource<Technology>> getAllTechnologies() { List<Technology> technologies = technologyGateway.getAllTechnologies(); Resources<<Resource<Technology>> resources = new Resources<Resource<Technology>>(technologyResourceAssembler.toResources(technologies)); resources.add(linkTo(methodOn(TechnologiesController.class).getAllTechnologies()).withSelfRel()); return resources; }
The configuration class has the annotation @EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL).
What is the best way to produce the response without the "_embedded"?
"_embedded": contains embedded resources. All other properties MUST be valid JSON, and represent the current state of the resource. The reserved "_links" property.
Spring HATEOAS provides some APIs to ease creating REST representations that follow the HATEOAS principle when working with Spring and especially Spring MVC. The core problem it tries to address is link creation and representation assembly.
Spring HATEOAS provides common abstractions (representational models, a Link class, API to build links pointing to Spring MVC controllers, etc.) to ease building hypermedia driven REST APIs with Spring MVC in general. Thus, you can use it alongside Spring MVC to manually build those services.
To implement HATEOAS, we would need to include related resources in the response. Instead of Student we use a return type of EntityModel<Student> . EntityModel is a simple class wrapping a domain object and allows adding links to it. We create a new resource.
As the documentation says
application/hal+json responses should be sent to requests that accept application/json
In order to omit _embedded
in you response you'll need to add
spring.hateoas.use-hal-as-default-json-media-type=false
to application.properties
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With