0

It is fairly common to expose the following endpoints for REST resources

@GET customers/ ==> list of customers
@POST customers/ ==> add a customer
@Get customers/:id ==> specific info of customer
@PUT customers/:id ==> override a customer
@PATCH customers/:id ==> update customer

Spring data rest repository handles this very well.

But if I'd like to add custom end points like

@GET customers/recent ==> retrieve customers recently visited @GET customers/:id/photo ===> all photos belonging to that customer

Is there a way to add to the existing set of endpoints?

Of course, we can repeat all the idiomic code in a @RestController annotated class, but that would be very repetitive for 10+ resources.

What I am looking for is like this

class CustomerController{
    // all @GET, @POST, @PUT, @PATCH methods are already generated, like a data rest repository

    @RequestMapping(value = "/{customerId}/photo", method = RequestMethod.GET)
    public Collection<Photo> getAllPhotos(){
        ...
    }

    // it is also possible to override @POST request here 
    public Collection<Customer> getCustomers(){
        // more logic
    }
}
Han_Chen
  • 195
  • 2
  • 14

1 Answers1

0

Just add a method to you repository interface.

class CustomerRepository {

    public List<Customer> findRecent();      

}

Given method will be exported under /customers/findRecent. You can tweak the paths using @RestResource annotation.

Talking about your second case, e.g. @GET customers/:id/photo,t that is handled transparently by the Spring Data Rest, meaning, that if your entity Customer has a photo association, it is exported under that url out of the box.

David Siro
  • 1,826
  • 14
  • 33