You create a REST service by adding the web starter and writing a class annotated with @RestController. Each handler method maps an HTTP method and a path to Java code, and Spring converts the return value to JSON.
- Add the web starter,
spring-boot-starter-webmvc, namedspring-boot-starter-webbefore Spring Boot 4. It brings Spring MVC, the Jackson JSON library and an embedded Tomcat web server. - Annotate a class with
@RestControllerand give it a base path with@RequestMapping. - Map each operation with a shortcut annotation that has the HTTP method built in, such as
@GetMappingor@PostMapping. - Read input with
@PathVariablefor a path segment and@RequestBodyfor a JSON body.
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getAllUsers() {
return userService.findAll();
}
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.save(user);
}
// ...
}
Start the @SpringBootApplication main class, and a GET request to /api/users/1 returns that user as JSON. To choose the status code yourself, return a ResponseEntity, for example 201 Created from the POST method.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓