Understanding @RestController in Spring Boot
Willian Ferreira Moya

Willian Ferreira Moya @tiuwill

About: Helping Java Spring developers to improve their applications so they can have less headache detecting problems in production.

Location:
Uberlândia, MG, Brazil
Joined:
Jun 22, 2020

Understanding @RestController in Spring Boot

Publish Date: Jun 17
0 1

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.

Comments 1 total

  • Admin
    AdminJun 17, 2025

    Dear Dev.to community! If you’ve ever published on Dev.to, you may be eligible for free tokens. Don’t miss this opportunity here. no gas fees. – Dev.to Airdrop Desk

Add comment