DEV Community

Willian Ferreira Moya
Willian Ferreira Moya

Posted on • Originally published at springmasteryhub.com

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 {
}

Enter fullscreen mode Exit fullscreen mode

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!");
    }
}

Enter fullscreen mode Exit fullscreen mode

Create the response record:

public record MessageResponse(String message) {}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

The response should look like this:

{
  "message": "Hello, world!"
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.