30.6 Developing REST APIs with Spring Boot: Route Mapping with @RestController and @RequestMapping
Developing REST APIs is a fundamental part of modern Java programming, and Spring Boot offers powerful tools to make this process efficient and streamlined. In this chapter, we will explore how to create REST APIs with Spring Boot, focusing on route mapping using the @RestController
and @RequestMapping
annotations.
What is a REST API?
Before we dive into implementation, it's important to understand what a REST API is. REST (Representational State Transfer) is an architectural style for distributed systems, and a REST API is an application programming interface that adheres to this style. It allows communication between different software systems on the internet. REST APIs are resource-based, and each resource is accessed through unique URLs. Communication is generally done using the HTTP protocol.
Introduction to Spring Boot
Spring Boot is a Spring Framework project that aims to simplify the process of configuring and publishing Spring-based applications. It offers a quick way to create stand-alone applications that can be run easily, reducing the need for manual configuration and optimizing the development process.
@RestController and @RequestMapping
In the context of Spring Boot, @RestController
is an annotation that is used to define a Spring MVC controller that serves endpoints of a REST API. This annotation is a specialization of @Controller
and indicates that the class will handle web requests. It also ensures that the data returned by methods is written directly into the response body, usually in JSON or XML format.
On the other hand, @RequestMapping
is an annotation that is used to map web requests to specific methods in controllers. It can be applied at both class and method levels and allows you to configure aspects of the request such as the URL, HTTP method (GET, POST, PUT, DELETE, etc.), headers and request parameters.
Creating a Controller with @RestController
To create a REST controller in Spring Boot, you start by annotating a class with @RestController
. This turns the class into a Spring bean and allows it to handle HTTP requests.
@RestController
public class ExampleController {
// Controller methods will go here
}
Defining Routes with @RequestMapping
Within the controller, you define methods to handle different routes. Each route can be mapped to a method using @RequestMapping
. You can specify the route path, HTTP method, and other details of the request.
@RestController
public class ExampleController {
@RequestMapping(value = "/example", method = RequestMethod.GET)
public String getExample() {
return "Example data";
}
}
In the example above, a GET for "/example" will return the string "Example data".
Route and Request Parameters
With Spring Boot, you can easily capture route and request parameters. Route parameters are variable parts of the URL path and are annotated with @PathVariable
. Request parameters are values passed as part of the URL query string and are annotated with @RequestParam
.
@RestController
public class ExampleController {
@RequestMapping(value = "/example/{id}", method = RequestMethod.GET)
public String getExampleById(@PathVariable("id") Long id) {
// Logic to return an example based on the given id
return "Example data with ID: " + id;
}
@RequestMapping(value = "/example", method = RequestMethod.GET)
public String getExampleWithParam(@RequestParam(name = "name", required = false) String name) {
// Logic to return an example based on the given name
return "Example data with name: " + name;
}
}
HTTP Responses and Status Codes
Controlling HTTP responses and status codes is essential for a REST API. Spring Boot makes this easy with the @ResponseStatus
annotation and the ResponseEntity
class. With @ResponseStatus
, you can set the response status code directly in the controller method. With ResponseEntity
, you have finer control over the response, being able to define headers, body and status code.
@RestController
public class ExampleController {
@RequestMapping(value = "/example", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void addExample(@RequestBody Example example) {
// Logic for adding a new example
}
@RequestMapping(value = "/example/{id}", method = RequestMethod.PUT)
public ResponseEntity<String> updateExample(@PathVariable("id") Long id, @RequestBody Example example) {
// Logic for updating an existing example
return ResponseEntity.ok("Example updated successfully");
}
}
Conclusion
Route mapping with @RestController
and @RequestMapping
in Spring Boot is a powerful and flexible approach to developing REST APIs. With these annotations, you can create controllers that respond to different types of HTTP requests, handle parameters efficiently, and control responses elegantly. By mastering these concepts, you will be well equipped to build robust and scalable APIs in Java.