Junior — Middle
Can you explain what a REST controller is and how it is used in API development?
sobes.tech AI
Answer from AI
A REST controller is a component in a web application that handles HTTP requests and forms HTTP responses according to REST principles (Representational State Transfer).
In Java, especially with the Spring Framework, REST controllers are created using the @RestController annotation. They enable the implementation of APIs that interact with clients via standard HTTP methods (GET, POST, PUT, DELETE).
Main features of a REST controller:
- Routes requests based on URL.
- Handles data in JSON or XML format.
- Uses HTTP methods to define actions (e.g., GET — retrieve data, POST — create).
Example of a simple REST controller in Spring Boot:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
// logic to get user by id
return userService.findById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
// logic to create user
return userService.save(user);
}
}
This controller simplifies API creation, making it understandable and standardized.