I wrote this code in order to return a http status of not found to my users in case the resource is not present in the DB.
@RestController
public class ExampleController {
public final ExampleService exampleService;
@Autowired
public ExampleController(ExampleService exampleService) {
this.exampleService = exampleService;
}
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
}
@GetMapping("/api/mappings/get-by-id/{id}")
public ExampleDto getExampleById(@PathVariable String id) {
Example example = exampleService.findById(id).orElse(null );
if (example == null) throw new ResourceNotFoundException();
return new ExampleDto(example);
}
}
I would like to know if this code can be considered good and robust enough or if it can be improved and how.
2 Answers 2
Your URL path isn't very RESTlike. You have built the URL to describe an operation when a more common approach is to build the URL to describe a resource.
So instead of https://example.com/api/mappings/get-by-id/42
one would build a URL like https://example.com/api/mappings/42
.
The name get-by-id
is fully redundant in REST world as the "get" operation is already defined in the HTTP GET-method (the @GetMapping
annotation in Spring Boot) and identifying resources by their identifier is always the default operation :).
-
\$\begingroup\$ While that is correct this is a specific case where you can get an item by a property that I called id here but it was just to write an example. The key part of my question if how to handle the 404. Thanks for your contribution in any case! \$\endgroup\$Pitto– Pitto2020年05月20日 06:44:34 +00:00Commented May 20, 2020 at 6:44
-
\$\begingroup\$ Ps I have made my pseudocode more precise regarding your observation. xxxId is a specific property of my object, therefore the route I specified. \$\endgroup\$Pitto– Pitto2020年05月20日 06:59:12 +00:00Commented May 20, 2020 at 6:59
-
\$\begingroup\$ Still you have a very valid point, +1 \$\endgroup\$Pitto– Pitto2020年05月20日 07:17:22 +00:00Commented May 20, 2020 at 7:17
As often happens after sleeping on it I had a better solution:
.orElseThrow(ResourceNotFoundException::new);
@Autowired
on constructor injection. Cheers just saved 2 line of code in each Component \$\endgroup\$