Skip to Content

What does the rest controller do?

A REST controller handles HTTP requests in Spring Boot applications. It provides access to resources through RESTful endpoints. The REST controller is responsible for handling all RESTful API requests and responses.

What is a REST Controller?

A REST controller allows you to access resources such as retrieving user data, adding a new user, updating user information, removing a user, etc. It exposes various REST API endpoints. When you make an HTTP request to that endpoint, the controller handles that request accordingly.

For example, let’s say you have a UserController class that has methods like:

  • getUser() – To retrieve user data
  • addUser() – To add a new user
  • updateUser() – To update existing user
  • deleteUser() – To delete a user

So when you make a GET request to /users, the getUser() method will handle that request and return the list of users. When you make a POST request to /users, the addUser() method will be called which will create a new user resource.

Key Characteristics of a REST Controller

  • Handles HTTP requests by exposing various REST API endpoints
  • Each endpoint is mapped to a specific HTTP method and URL path
  • The request is handled by the controller method designed for that endpoint
  • After processing the request, returns the response to the caller
  • Responds with proper HTTP status codes

Creating a REST Controller

Here are the key steps to create a REST controller in Spring Boot:

  1. Create a controller class and annotate it with @RestController annotation
  2. Define methods to handle specific HTTP requests and annotate them with @GetMapping, @PostMapping, etc annotations
  3. The method name should match the HTTP method
  4. Method arguments can have parameters like @PathVariable, @RequestParam, @RequestBody etc to access request data
  5. Return appropriate response object, it will automatically converted to JSON or XML
  6. Methods should return proper HTTP status codes like 200, 404, 400 etc

Let’s take an example of a UserController REST controller:

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

  @GetMapping
  public List getAllUsers() {
    // ...
  }

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

  @PostMapping
  public User addUser(@RequestBody User user) {
    //...
  } 
}

Here we have:

  • @RestController annotation to mark this class as REST controller
  • @RequestMapping for the base URL mapping
  • @GetMapping, @PostMapping to map HTTP methods to method handlers
  • Handler methods like getUserById(), addUser() etc
  • Method arguments using @PathVariable, @RequestBody to access request parameters

Key Responsibilities

The main responsibilities of a REST controller include:

Handling HTTP Requests

The primary job of the REST controller is to handle the HTTP requests coming to the API endpoints. Based on the HTTP method and endpoint URL mapping, the appropriate controller method is called.

Accessing & Validating Data

The controller is responsible for accessing and validating any request data passed as method parameters. This includes path variables, request parameters or request body.

Interacting with Services

It delegates business logic to the service layer. The service classes contain the actual business logic. The controller interacts with these services to perform operations.

Generating HTTP Responses

Once the request is handled by the service layer, the controller needs to prepare and return the appropriate HTTP response. This includes setting the response status code, headers, and serializing the response body.

Exception Handling

The controller should handle any exceptions thrown during the request handling and return appropriate error responses.

Mapping HTTP Requests

The REST controller maps HTTP requests to handler methods. Let’s see how we can map various HTTP methods:

@GetMapping

Maps HTTP GET requests onto specific handler methods.

Example:

@GetMapping("/users")
public List getAllUsers() {
  // ...
}

@PostMapping

Maps HTTP POST requests onto specific handler methods.

Example:

  
@PostMapping("/users")
public User addUser(@RequestBody User user) {
  // ...
}

@PutMapping

Maps HTTP PUT requests onto specific handler methods.

Example:

@PutMapping("/users/{userId}") 
public User updateUser(@PathVariable Long userId, @RequestBody User user) {
  // ...
}

@DeleteMapping

Maps HTTP DELETE requests onto specific handler methods.

Example:

@DeleteMapping("/users/{userId}")
public void deleteUser(@PathVariable Long userId) {
  // ...
}

@PatchMapping

Maps HTTP PATCH requests onto specific handler methods.

Example:

@PatchMapping("/users/{id}")
public User partiallyUpdateUser(@PathVariable Long id, @RequestBody User user) {
  // ...
}

Accessing Request Data

The REST controller can access request data using annotations like:

@PathVariable

To access URI template variables.

Example:

@GetMapping("/users/{userId}")
public User getUser(@PathVariable Long userId) {
  // ...
} 

@RequestParam

To access query parameters.

Example:

@GetMapping("/users")
public List searchUsers(@RequestParam String name) {
  // ...
}

@RequestBody

To access the request body, usually for POST, PUT requests.

Example:

@PostMapping("/users") 
public void addUser(@RequestBody User user) {
  // ...
}

@RequestHeader

To access request headers.

Example:

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id, @RequestHeader("User-Agent") String clientInfo) {
  // ...
}

Generating Responses

The REST controller returns response to the caller after processing the request. Here are some ways to generate the response:

Return Object

Return a plain Java object, it will automatically get converted to JSON.

Example:

@GetMapping("/users")
public List getAllUsers() {
  return userService.getAllUsers(); 
}

ResponseEntity

Wrap response in ResponseEntity to add headers, status code.

Example:

@GetMapping("/users/{id}")  
public ResponseEntity getUser(@PathVariable Long id) {
  
  User user = userService.getUser(id);
  
  return ResponseEntity.ok(user);
}

HttpStatus

Return proper HTTP status codes like OK(200), CREATED(201), NO_CONTENT(204) etc.

@PostMapping("/users")
@ResponseStatus(HttpStatus.CREATED)
public void addUser(@RequestBody User user) {
  // ...
}

REST Controller Advice

We can use @RestControllerAdvice annotation to handle exceptions globally.

Example:

@RestControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(ResourceNotFoundException.class)
  @ResponseStatus(HttpStatus.NOT_FOUND)
  public ErrorResponse handleNotFound(Exception ex) {    
    return new ErrorResponse(ex.getMessage());
  }
}  

The @ExceptionHandler methods will be invoked for exceptions thrown from any controller.

Conclusion

To summarize, a REST controller is responsible for:

  • Exposing REST API endpoints
  • Handling HTTP requests and mapping to handler methods
  • Accessing request data using parameters
  • Delegating business logic to services
  • Generating HTTP response
  • Handling exceptions

By creating REST controllers, you can build robust RESTful web services in Spring Boot. Proper request mapping, validation, exception handling and well-defined endpoints are key to developing good REST APIs.