Build a RESTful Web Service with Spring Boot
· One min read
Spring Boot can expose JSON APIs with @RestController and request-mapping annotations.
@RestController
@RequestMapping("/api/users")
class UserController {
@GetMapping("/{id}")
ResponseEntity<UserDto> find(@PathVariable long id) {
return ResponseEntity.ok(service.find(id));
}
@PostMapping
ResponseEntity<UserDto> create(@Valid @RequestBody CreateUserRequest request) {
UserDto created = service.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
}
Use DTOs rather than exposing persistence entities directly. Apply Bean Validation to input and return accurate status codes such as 201, 400, 404, and 409.
Centralize errors with @RestControllerAdvice:
@ExceptionHandler(UserNotFoundException.class)
ResponseEntity<ProblemDetail> handleNotFound(UserNotFoundException ex) {
return ResponseEntity.of(ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, ex.getMessage())).build();
}
Version public contracts deliberately, document them with OpenAPI, authenticate sensitive operations, limit request sizes, and test serialization and failure responses as carefully as the success path.