Search code examples
restspring-bootresponserestful-architecturerestful-url

REST Resource Naming & @PathVariable annotation


I am reading a tutotral regarding the REST Resource Naming...

http://api.example.com/device-management/managed-devices/{id}/scripts/{id}:clone

This is an example of a best practice in the naming, but I don't know how to declare it using the @PathVariable annotation and distinguish one {id} from {id}:clone

public ResponseEntity<?> clone (
HttpServletRequest request, 
@PathVariable long id, ...) {
..
}

Solution

  • You need to distinguish the two IDs by the name of the variable or by the attribute value from @PathVariable, like:

    @GetMapping("http://api.example.com/device-management/managed-devices/{idManagedDevice}/scripts/{idScript}"
    public ResponseEntity<?> clone (HttpServletRequest request, 
        @PathVariable long idManagedDevice,
        @PathVariable long idScript,
    ) {
    ..
    }
    

    Or:

    @GetMapping("http://api.example.com/device-management/managed-devices/{id}/scripts/{idScript}"
    public ResponseEntity<?> clone (HttpServletRequest request, 
        @PathVariable(value="id") long idOfManagedDevice,
        @PathVariable(value="idScript") long idOfScript,
    ) {
    ..
    }