Sobes.tech
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:

  1. 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.

  2. Use method annotations such as @GetMapping, @PostMapping, @PutMapping, @DeleteMapping to handle corresponding HTTP methods and specify URL paths.

  3. Inject necessary services or components via @Autowired for business logic.

  4. 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.

What steps and components are necessary to implement… - sobes.tech