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:
- GET Request to /students returns an empty list initially:
[] - POST Request to /students?name=Sarthak adds a student named "Sarthak".
"Student added successfully!"
- 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.