I am trying to follow best practices imagine a basic API with /books endpoint.
I've the following classes: Book BookRepository (PagingAndSortingRepository but not exported!!) BookController (this is the serving class) BookResource ("representation" of the book in "REpresentational State Transfer") BookResourceAssembler
My BookController looks like this:
@RequestMapping(path="/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getBook(@PathVariable Long id) {
Book book = bookRepository.findOne(id);
BookResource bookResource = this.bookResourceAssembler.toResource(book);
return ResponseEntity.ok(bookResource);
}
my BookResource looks like this:
public class BookResource extends ResourceSupport{
public String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
BookResourceAssembler:
@Component
public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> {
public BookResourceAssembler() {
super(BookController.class, BookResource.class);
}
@Override
public BookResource toResource(Book entity) {
BookResource resource = createResourceWithId(entity.getDbid(), entity);
return resource;
}
}
My first problem is easy one to solve I guess, title is not initialized so when I call /books/1 I get title: null.
Second and more important question is how do I do content-negotiation and versioning, which is a really important aspect of RESTful API. How should I introduce BookResourceV2 and where should I negotiate it? Let's say I want
"Content-Type: application/vnd.company.book+json.v2"
where do I state this? Which new classes/functions should I add to handle this v2 of the same resource?
I couldn't find a good tutorial that covers all aspects.