I'm trying to use HATEOAS with Spring HATEOAS and need to expose enum
s as REST API with Spring HATEOAS.
I tried three ways as follows:
@RestController
@RequestMapping(path = "/fruits")
public class FruitResourceController {
@RequestMapping(method = RequestMethod.GET)
public Fruit[] fruits() {
return Fruit.values();
}
// NOTE: The `produces` attribute is only for browsers.
@RequestMapping(path = "/with-resource", method = RequestMethod.GET,
produces = MediaTypes.HAL_JSON_VALUE)
public Resource<Fruit[]> fruitsWithResource() {
Resource<Fruit[]> resource = new Resource<Fruit[]>(Fruit.values());
Link selfLink = linkTo(methodOn(FruitResourceController.class).fruitsWithResource())
.withSelfRel();
resource.add(selfLink);
return resource;
}
// NOTE: The `produces` attribute is only for browsers.
@RequestMapping(path = "/with-resources", method = RequestMethod.GET,
produces = MediaTypes.HAL_JSON_VALUE)
public Resources<Fruit> fruitsWithResources() {
Resources<Fruit> resources = new Resources<Fruit>(Arrays.asList(Fruit.values()));
Link selfLink = linkTo(methodOn(FruitResourceController.class).fruitsWithResources())
.withSelfRel();
resources.add(selfLink);
return resources;
}
}
But I have no idea which is the right way for HATEOAS. Any advice or reference will be appreciated.
For reference, I have the following Spring Data REST configuration:
@Configuration
public class SpringDataRestConfig {
@Bean
public ResourceProcessor<RepositoryLinksResource> repositoryLinksResourceProcessor() {
return new ResourceProcessor<RepositoryLinksResource>() {
@Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
Link fruitsLink = linkTo(methodOn(FruitResourceController.class).fruitsWithResources())
.withRel("fruits");
resource.add(fruitsLink);
return resource;
}
};
}
}
See the following for a sample project:
https://github.com/izeye/spring-boot-throwaway-branches/blob/data-jpa-and-rest/src/main/java/com/izeye/throwaway/SpringDataRestConfig.java https://github.com/izeye/spring-boot-throwaway-branches/blob/data-jpa-and-rest/src/main/java/com/izeye/throwaway/FruitResourceController.java
--- UPDATED at 2016.01.04
Using ALPS (/profile
) looks nice to get enum listing but I'm not sure this is a right approach.
produces
attribute is only for browsers" - Why do you think it is? – Kelbeeenum
s? Do you want to expose a static, read-only list of string values? Then why don't you simply do exactly that? Simply return the enum itself Fruit.values() in your REST controller. Spring will automatically the HTTP response to an array of Strings. – Quern