REST Controllers

Basic Spring
≈ 1 min read

@RestController for APIs

In a REST API, controller methods usually return data directly in the HTTP response body. To avoid placing @ResponseBody on every method, Spring MVC provides @RestController. Conceptually, it combines @Controller with @ResponseBody behavior for the class methods.

@RestController
@RequestMapping("/api/users")
class UserController {

    @GetMapping("/{id}")
    UserDto find(@PathVariable long id) {
        return userService.find(id);
    }
}

The returned UserDto becomes the response body. The controller does not need to serialize the object manually or write data into the Servlet response. This makes REST API methods look like regular Java methods: the arguments describe the input, while the return type describes the operation result.

When ResponseEntity is useful

Sometimes a response body alone is not enough: you need to choose an HTTP status explicitly or add headers. In that case, the method can return ResponseEntity.

@PostMapping
ResponseEntity<UserDto> create(@RequestBody CreateUserRequest request) {
    UserDto user = userService.create(request);
    return ResponseEntity.status(201).body(user);
}

You do not need to use ResponseEntity in every method. When the default status and a regular body are sufficient, returning a DTO directly is usually easier to read.