Skip to main content

Building REST Services

Standard MVC Controllers return logical "View" template labels mapping to HTML code. REST APIs explicitly return serialized text formats (like JSON).

@RestController

In Spring, a REST API structure is achieved via @RestController. This annotation combines @Controller and @ResponseBody internally, forcing Java object conversion to generic JSON upon HTTP return.

@RestController
@RequestMapping("/api/v1/users")
public class UserRestController {

private final UserService userService;

public UserRestController(UserService userService) {
this.userService = userService;
}

@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.findById(id);

// Returns generic mapped JSON code
return ResponseEntity.ok(user);
}
}