Rest API Annotations in Java: A Comprehensive Guide

In the world of Java web development, building robust and scalable RESTful APIs has become a standard practice. Spring Boot, one of the most popular frameworks, simplifies API creation by offering a plethora of annotations that reduce boilerplate code and improve clarity. In this blog, we will explore key REST API annotations in Java and understand how they work.

What Are Annotations in Java?

Annotations in Java are metadata tags that provide additional information to the compiler and runtime. In the context of REST APIs, annotations help configure request mappings, validation, security, and other essential behaviors.


Key Annotations for REST APIs

1. @RestController

This annotation is a combination of @Controller and @ResponseBody. It marks a class as a RESTful controller and ensures that the return value of each method is directly written to the HTTP response body.

@RestController
public class UserController {
    @GetMapping("/users")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
}

2. @RequestMapping

Used to map HTTP requests to handler methods of a controller. It can also be applied at the class level to set a common base URI for all methods.

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

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
}

3. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

These are shorthand annotations for @RequestMapping with specific HTTP methods (GET, POST, PUT, DELETE).

@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
    return userService.getUserById(id);
}

@PostMapping
public User createUser(@RequestBody User user) {
    return userService.createUser(user);
}

4. @PathVariable

Used to extract values from URI templates.

@GetMapping("/users/{id}")
public User getUserById(@PathVariable("id") Long userId) {
    return userService.getUserById(userId);
}

5. @RequestParam

Binds query parameters to method arguments.

@GetMapping("/users")
public List<User> getUsersByStatus(@RequestParam String status) {
    return userService.getUsersByStatus(status);
}

6. @RequestBody

Maps the body of an HTTP request to a Java object.

@PostMapping("/users")
public User createUser(@RequestBody User user) {
    return userService.createUser(user);
}

7. @ResponseStatus

Defines the HTTP status code to return for a method.

@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/users")
public User createUser(@RequestBody User user) {
    return userService.createUser(user);
}

8. @ExceptionHandler

Handles exceptions thrown by request handlers.

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleResourceNotFound(ResourceNotFoundException ex) {
        return ex.getMessage();
    }
}

Advanced Annotations

9. @CrossOrigin

Enables Cross-Origin Resource Sharing (CORS) for specific endpoints or controllers.

@CrossOrigin(origins = "http://example.com")
@GetMapping("/users")
public List<User> getAllUsers() {
    return userService.getAllUsers();
}

10. @Valid

Used to trigger validation on request bodies or parameters.

@PostMapping("/users")
public User createUser(@Valid @RequestBody User user) {
    return userService.createUser(user);
}

By leveraging these annotations, you can create clean, maintainable, and scalable RESTful APIs in Java with Spring Boot. Happy coding!