@RestController: The Heart of Your REST API
So far, we've set up our Spring Boot project and understood the basic structure. Now, let's dive into building the actual API endpoints. This is where @RestController comes into play.
What is @RestController?
@RestController is a convenience annotation that combines @Controller and @ResponseBody. Let's break that down:
@Controller: Marks a class as a controller, handling incoming web requests.@ResponseBody: Indicates that the return value of a method should be directly written to the response body, rather than being interpreted as a view name.
Essentially, @RestController simplifies the process of creating RESTful web services by automatically serializing the return value of your methods into formats like JSON or XML. This is perfect for APIs where you're sending data, not rendering HTML views.
Creating Your First REST Endpoint
Let's create a simple endpoint that returns a greeting.
Create a new class: Inside your
src/main/java/com/example/demopackage (or your project's equivalent), create a new class calledGreetingController.Annotate with
@RestController: Add the@RestControllerannotation to the class.import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { }Create a method to handle requests: Let's create a method that handles GET requests to the
/greetingendpoint. We'll use the@GetMappingannotation for this.import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { @GetMapping("/greeting") public String greeting() { return "Hello, World!"; } }@GetMapping("/greeting"): This annotation maps HTTP GET requests to the/greetingpath to thegreeting()method.public String greeting(): This is the method that will handle the request. It returns aString, which will be written directly to the response body.
Running and Testing Your API
Start your Spring Boot application.
Open your web browser or use a tool like
curlor Postman and navigate tohttp://localhost:8080/greeting. (Assuming you haven't changed the default port).You should see the text "Hello, World!" displayed in your browser or in the response body of your tool.
Understanding Request Mappings
Spring Boot provides several annotations for mapping requests to methods:
@GetMapping: Maps HTTP GET requests.@PostMapping: Maps HTTP POST requests.@PutMapping: Maps HTTP PUT requests.@DeleteMapping: Maps HTTP DELETE requests.@PatchMapping: Maps HTTP PATCH requests.@RequestMapping: A more general annotation that can handle multiple HTTP methods and paths.
Returning JSON Data
APIs often return data in JSON format. Let's modify our example to return a JSON object.
Create a simple data class:
public class Greeting { private String message; public Greeting(String message) { this.message = message; } public String getMessage() { return message; } }Modify the
GreetingController:import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { @GetMapping("/greeting") public Greeting greeting() { return new Greeting("Hello, World!"); } }Run your application and navigate to
http://localhost:8080/greeting.You should now see a JSON response like this:
{"message":"Hello, World!"}
Spring Boot automatically handles the serialization of the Greeting object into JSON because of the @RestController annotation. It uses a library like Jackson under the hood to perform this conversion.
Key Takeaways
@RestControlleris a powerful annotation for building REST APIs in Spring Boot.- It combines
@Controllerand@ResponseBodyfor simplified development. - Use
@GetMapping,@PostMapping, etc., to map HTTP requests to your methods. - Spring Boot automatically serializes return values into JSON (or other formats) when using
@RestController.
This is just the beginning! In the next sections, we'll explore more advanced features like path variables, request parameters, and handling more complex data.