Module: Building REST APIs

@RestController

@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.

  1. Create a new class: Inside your src/main/java/com/example/demo package (or your project's equivalent), create a new class called GreetingController.

  2. Annotate with @RestController: Add the @RestController annotation to the class.

    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class GreetingController {
    
    }
    
  3. Create a method to handle requests: Let's create a method that handles GET requests to the /greeting endpoint. We'll use the @GetMapping annotation 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 /greeting path to the greeting() method.
    • public String greeting(): This is the method that will handle the request. It returns a String, which will be written directly to the response body.

Running and Testing Your API

  1. Start your Spring Boot application.

  2. Open your web browser or use a tool like curl or Postman and navigate to http://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.

  1. Create a simple data class:

    public class Greeting {
        private String message;
    
        public Greeting(String message) {
            this.message = message;
        }
    
        public String getMessage() {
            return message;
        }
    }
    
  2. 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!");
        }
    }
    
  3. 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

  • @RestController is a powerful annotation for building REST APIs in Spring Boot.
  • It combines @Controller and @ResponseBody for 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.