Proper vs. Improper Way to Implement CRUD in RESTful Services
In this quick recipe, we'll explore the proper and improper ways to implement CRUD (Create, Read, Update, Delete) operations in RESTful services
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
// Create
@PostMapping
public ResponseEntity<Object> createUser(@RequestBody User user, UriComponentsBuilder uriBuilder) {
User createdUser = userService.saveUser(user);
// Create URI of the created user using UriComponentsBuilder parameter
URI location = uriBuilder.path("/api/users/{id}")
.buildAndExpand(createdUser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
// Read
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.findById(id);
return ResponseEntity.ok(user);
}
// Update
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
User updatedUser = userService.updateUser(id, userDetails);
return ResponseEntity.ok(updatedUser);
}
// Delete
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return ResponseEntity.noContent().build();
}
}Key Points:
PreviousGlobal REST Error Responses via @ControllerAdviceNextReferencing Values from Properties File in Components
Last updated