Understanding @RestController in Spring Boot

What is it?

This annotation is a specialization of @Controller, specifically designed for creating REST endpoints.

It combines the @Controller and @ResponseBody annotations, making it easier to create RESTful applications.

If your application works with RESTful APIs, this is the go-to annotation to define your controllers. It simplifies your code and communicates the intent: this class serves REST endpoints.

How to use it?

Create a class and annotate it with @RestController:

import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
}

Define a method to respond to an HTTP method:

import org.springframework.web.bind.annotation.GetMapping;

@RestController
public class MyController {

    @GetMapping("/hello")
    public MessageResponse hello() {
        return new MessageResponse("Hello, world!");
    }
}

Create the response record:

public record MessageResponse(String message) {}

And that’s it! Now you have a controller and method that will respond to an endpoint for a particular HTTP method in a REST-compatible format.

Let’s test it out:

curl <http://localhost:8080/hello>

The response should look like this:

{
  "message": "Hello, world!"
}

Conclusion

By using this annotation, Spring simplifies the creation of RESTful applications.

Now that you know the difference between @Controller and @RestController, you can make sure to choose the better option for your context.


Posted

in

,

by