Table of contents
1.
Introduction
2.
Step by Step Implementation
3.
Spring RestController Example
4.
Spring RestController Maven Dependencies
5.
Spring RestController Class
6.
Accept and Content-Type Request Headers
7.
Spring RestController Test
8.
Frequently Asked Questions
8.1.
What is @RestController in Spring Boot?
8.2.
How do I test a RestController in Spring Boot?
8.3.
Which dependency is required to use @RestController? 
9.
Conclusion
Last Updated: Dec 20, 2024
Medium

RestController Annotation in Spring Boot

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will discuss the @RestController annotation in Spring Boot, its functions, and its implementation. You will learn how to use this annotation to build RESTful web services and understand concepts like request headers, Maven dependencies, and testing.  By the end of this guide, you will be able to create and test RESTful APIs using the @RestController annotation.

RestController Annotation in Spring Boot

Step by Step Implementation

To utilize the @RestController annotation in a Spring Boot application, follow these steps:

1. Create a new Java class & annotate it with @RestController at the class level. This annotation combines @Controller & @ResponseBody, indicating that the class is a controller that returns data directly in the response body.


2. Define methods within the class to handle different HTTP requests (GET, POST, PUT, DELETE) & specify the respective URL mappings using annotations like @GetMapping, @PostMapping, @PutMapping, or @DeleteMapping.

3. Implement the logic within each method to process the request, perform any necessary operations, & return the appropriate response data. The returned data will be automatically serialized into JSON or XML format, depending on the client's preference.

4. Use additional annotations to further customize the behavior of the controller methods. For example, @RequestParam to extract query parameters, @PathVariable to extract variables from the URL path, or @RequestBody to access the request body.

5. If needed, inject dependencies such as services or repositories into the controller class using the @Autowired annotation. These dependencies can be used to interact with the business logic or data access layers of the application.

6. Configure any necessary Spring Boot properties or application settings related to the controller, such as server port, context path, or custom error handling.

7. Run the Spring Boot application & test the RESTful endpoints using tools like cURL, Postman, or any HTTP client to ensure they are functioning as expected.


By following these steps, you can effectively create a RESTful API using the @RestController annotation in a Spring Boot application. The annotation simplifies the process of mapping methods to HTTP requests & eliminates the need for manual response body serialization.

Spring RestController Example

The @RestController annotation makes it easy to create APIs. Let us see a simple example to understand how it works.

Example

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@SpringBootApplication
public class RestControllerExample {
    public static void main(String[] args) {
        SpringApplication.run(RestControllerExample.class, args);
    }
}


@RestController
@RequestMapping("/api")
class MyController {
    @GetMapping("/greet")
    public String greet() {
        return "Hello, Welcome to Spring Boot!";
    }
}


Output:

When you run the application and open the following URL in your browser:
http://localhost:8080/api/greet
You will see the output:
Hello, Welcome to Spring Boot!


Explanation:

  • The @SpringBootApplication annotation marks the entry point of the Spring Boot application.
     
  • The @RestController class defines a RESTful endpoint.
     
  • @GetMapping("/greet") maps the GET request to the /api/greet endpoint.
     
  • The method returns a plain string as a response.

Spring RestController Maven Dependencies

To use the @RestController annotation in a Spring Boot application, you need to include the necessary Maven dependencies in your project's pom.xml file. The required dependencies are:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

 

  • The `spring-boot-starter-web` dependency is a starter module that includes all the required dependencies for building web applications using Spring Boot, including the Spring MVC framework.
  • This dependency transitively includes other necessary libraries such as `spring-web`, `spring-webmvc`, `jackson-databind` for JSON serialization and deserialization, and `tomcat-embed-core` for the embedded Tomcat server.
     

Note: If you use this dependency in your project, you ensure that all the required libraries and configurations are available to use the @RestController annotation and develop RESTful APIs in your Spring Boot application.

Spring RestController Class

The RestController class is where all the logic for the RESTful service resides. You can define multiple endpoints inside this class using annotations like @GetMapping@PostMapping@PutMapping, and @DeleteMapping.

Example

import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/students")
public class StudentController {
    private List<String> students = new ArrayList<>();


    @GetMapping
    public List<String> getStudents() {
        return students;
    }


    @PostMapping
    public String addStudent(@RequestParam String name) {
        students.add(name);
        return "Student added successfully!";
    }
}


Output:

  1. GET Request to /students returns an empty list initially:

    []
  2. POST Request to /students?name=Sarthak adds a student named "Sarthak".

    "Student added successfully!"
     
  3. GET Request again returns:
    ["Sarthak"]


Explanation:

  • @RequestMapping("/students"): Sets the base path for the endpoints.
     
  • @GetMapping: Fetches the list of students.
     
  • @PostMapping: Adds a student to the list using a request parameter.

Accept and Content-Type Request Headers

When building RESTful APIs with Spring Boot and the `@RestController` annotation, it's important to consider the `Accept` and `Content-Type` request headers. These headers provide information about the desired response format and the format of the request payload, respectively.
 

1. Accept Header:

The `Accept` header is used by the client to specify the desired media type(s) for the response. It indicates the format in which the client expects to receive the data from the server. Common media types include `application/json` for JSON format and `application/xml` for XML format.

Example:

Accept: application/json


Spring Boot automatically handles content negotiation based on the `Accept` header. By default, it returns the response in JSON format if the `Accept` header is not specified or if it matches `application/json`.
 

2. Content-Type Header:

The `Content-Type` header is used to specify the media type of the request payload sent by the client to the server. It indicates the format in which the client is sending the data.

Example:

Content-Type: application/json

 

  • When sending a request with a payload (e.g., POST or PUT), it's important to set the `Content-Type` header appropriately. Spring Boot uses this header to determine how to parse and deserialize the request body into Java objects.
     
  • Spring Boot's `@RestController` annotation, in combination with the underlying Spring MVC framework, automatically handles the serialization and deserialization of request and response payloads based on the `Accept` and `Content-Type` headers.
     
  • For example, if a client sends a POST request with a JSON payload and sets the `Content-Type` header to `application/json`, Spring Boot will automatically deserialize the JSON payload into the corresponding Java object defined in the controller method.
     
  • Similarly, when the server sends a response, Spring Boot sets the `Content-Type` header based on the media type specified in the `Accept` header or the default media type (usually JSON).

Spring RestController Test

Testing is an essential part of developing robust and reliable RESTful APIs. When using the `@RestController` annotation in a Spring Boot application, you can write unit tests to verify the behavior of your controller methods. Spring Boot provides a convenient way to test RESTful APIs using the `@WebMvcTest` annotation. This annotation sets up a Spring MVC test context focused on testing the web layer, including controllers.
 

Let’s look at an example of how to write a test for a `@RestController` class:

@WebMvcTest(UserController.class)
public class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;


    @Test
    public void testGetAllUsers() throws Exception {
        mockMvc.perform(get("/api/users"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$[0].id").value(1))
                .andExpect(jsonPath("$[0].name").value("Rahul Singh"));
    }


    @Test
    public void testCreateUser() throws Exception {
        User user = new User(1L, "Rahul Singh", "rahul@example.com");


        mockMvc.perform(post("/api/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(new ObjectMapper().writeValueAsString(user)))
                .andExpect(status().isCreated());
    }
}

 

  • In this example, we use the `@WebMvcTest` annotation to set up a test context for the `UserController` class. The `MockMvc` instance is autowired and used to perform HTTP requests and verify the responses.
     
  • The `testGetAllUsers()` method tests the GET request to retrieve all users. It uses the `mockMvc.perform()` method to send a GET request to `/api/users` and then asserts the expected response status, content type, and JSON content using the `andExpect()` methods.
     
  • The `testCreateUser()` method tests the POST request to create a new user. It creates a `User` object, converts it to JSON using `ObjectMapper`, and sends a POST request to `/api/users` with the JSON content. It then asserts the expected response status using the `andExpect()` method.
     
  • By writing such tests, you can ensure that your `@RestController` methods are functioning correctly, handling the expected HTTP requests, and returning the appropriate responses.

Note: Spring Boot also provides other testing utilities and annotations, like `@MockBean` for mocking dependencies and `@SpringBootTest` for integration testing, which can be used in combination with `@WebMvcTest` to create comprehensive test suites for your RESTful APIs.

Frequently Asked Questions

What is @RestController in Spring Boot?

It is an annotation that simplifies the creation of RESTful web services by combining @Controller and @ResponseBody.

How do I test a RestController in Spring Boot?

You can test it using MockMvc with JUnit.

Which dependency is required to use @RestController? 

You need to include the spring-boot-starter-web dependency in your Maven project.

Conclusion

In this article, we discussed the @RestController annotation in Spring Boot. We discussed how to implement it step by step, set up Maven dependencies, create endpoints, handle request headers, and test the API. This annotation simplifies creating RESTful APIs and is widely used in modern web development. Now you can confidently build and test APIs using @RestController.

Live masterclass