Junior — Middle
What steps and components are necessary to implement a REST API using the @RestController annotation in Spring?
sobes.tech AI
Answer from AI
To implement a REST API using the @RestController annotation in Spring, you need to:
-
Create a class and annotate it with
@RestController. This indicates to Spring that the class will handle HTTP requests and return data in JSON or XML format. -
Use method annotations such as
@GetMapping,@PostMapping,@PutMapping,@DeleteMappingto handle corresponding HTTP methods and specify URL paths. -
Inject necessary services or components via
@Autowiredfor business logic. -
Configure serialization/deserialization of objects if needed.
Example:
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.save(user);
}
}
Main components: controller with @RestController, methods with HTTP method annotations, service layer for logic, data models.