@RestController example with Spring Boot and Swagger

In this article I’ll explain how to set up a basic @RestController  in a Spring Boot application, using both @GetMapping and @PostMapping annotations. Besides, this application includes Springfox Swagger so the REST API endpoints are documented and accessible through this tool.

Many people know the advantages of using Spring to create a REST API in a very efficient way. Since version 4 (4.3), Spring has some annotations that make even easier to write REST-enabled Controllers:

  • @RestController: It’s a convenience annotation that combines @Controller and @ResponseBody. This last one, when set at class level, makes all the methods annotated with @RequestMapping being considered as annotated with @ResponseBody as well. And, in case you don’t know, you need @ResponseBody annotation when returning data from your controller methods in order to build a proper REST interface (as you may guess, to return data such as JSON in your response’s body).
  • @GetMapping and @PostMapping are shortcut annotations for @RequestMapping(method = RequestMethod.GET) and @RequestMapping(method = RequestMethod.POST).  When combined with the above-mentioned @RestController, annotated methods will be treated as if they were annotated with @ResponseBody.

Wow! Too many annotations to digest? We’ll get to a more practical explanation about this later when having a look at the Controller class.


To better understand how it works I recommend you to clone or download the code below from my spring-boot-restcontroller Github repository. Don’t forget to give it a star!

Time to see the code! Let’s start with the pom.xml:

The highlighted lines are the dependencies needed to include Springfox Swagger in our project. We’ll see the advantages of this soon. Now, in order to have some code to play with, I’ve created a SpanishGreeting class with just a message in it:

Not much to explain about it, cierto? The only strange part is that empty constructor there. If you’re familiar with working with JSON you’ll know that this constructor is needed by the Jackson deserializer to transform an incoming JSON message to the corresponding Java class (in our case when calling the POST method below). Because usually you don’t need it for anything else, this constructor shouldn’t be public.

And finally the main part of our application, the controller class:

Let’s see what we have here:

  • The class is annotated with @RestController. As explained above, if we use just @Controller instead, then we need some extra annotations @ResponseBody at method level for getSpanishGreetingById and getRandom.  Or, since Spring version 4, we could also annotate the class with @ResponseBody and have the same effect. So, @RestController annotation is just a shortcut of two annotations.
  • The class is also annotated with @RequestMapping, that’s a convenient way for setting the same context url to all methods defined inside the class. In our case, the resulting endpoints will be:
    • GET /spanish-greetings/{id}
    • GET /spanish-greetings/random
    • POST /spanish-greetings
  • Methods annotated with @GetMapping are just same as if they were annotated with @RequestMapping(method = RequestMethod.GET). Again, we don’t need @ResponseBody in these methods. The @PathVariable annotation indicates Spring from where to pick that variable value, in this case from the path. We could use also @RequestParam if it were a parameter instead (also changing the mapping pattern).
  • @PostMapping, as you may guess, is actually same as @RequestMapping(method = RequestMethod.POST). We don’t use here any extra mapping value because we want to post our data to the collection mapping, following best REST API conventions.
  • The @ResponseStatus(HttpStatus.OK) is not needed here, it’s just there to see explicitly that we want to return that status code, but it’s actually the default one.

And now some curiosities:

  • As you might have imagined, there are some other shortcut annotations for DELETE, PUT, etc. Check out this link if you’re curious.
  • In Spring, if you don’t use the method for a @RequestMapping, you’re accepting all of them. That means that if you for example change the @GetMapping("/random") for @RequestMapping("/random"), you can do a DELETE /spanish-greetings/random and you will still receive a nice Spanish greeting. Always specify the method when defining your API with Spring or you will easily fall in bad practices. You can try this in the code and check the changes in the Swagger UI (you’ll see a lot more of endpoints).
  • As many other smart features of Spring MVC, it is able to convert our id path variable to int magically, using default type converter.
  • You might be asking yourself why the @ResponseBody annotation was magically embedded inside @RestController but we still need to write the @RequestBody annotation for our POST method. Why not doing the same? You can find a good reasoning in this JIRA ticket for the Spring project. Summary: because it would be going too far with assumptions, depending on the client library you use there could be some useful query parameters.


Get now the Practical Book about Microservices and start learning from zero to expert, from Monolith-first to AMQP, Routing and Service Discovery.

Trying out the API with Swagger UI

Thanks to the dependencies added to the project and this configuration added to our Spring Boot application,

we can navigate to http://localhost:8080/swagger-ui.html (after we start our application) and play with the REST API:

swagger screenshot

In this case, we’re using Swagger in the most basic way, and mainly to use the UI, but it’s a powerful tool to add documentation to your REST API just by adding annotations to your code.

You can try the API in the following ways:

  • Do some GETs to /random, you should see the predefined Spanish Greetings being retrieved.
  • GET some of them by id, the default ones are 1, 2, 3.
  • POST a new greeting, it will be included in the list and you can access it by id or randomly. Do you want suggestions? Just try “Buenos días!” or “Buenas tardes!”…

Github project and the book

You can find the full code for this sample project in Github: https://github.com/mechero/spring-boot-restcontroller

If you’re interested in Spring Boot and creating real (not one-class) microservices with Restful APIs, get my book today and get real experience on Microservice Architecture.

Related Posts

A practical book about Microservices Microservices are getting very popular these days. This type of software architecture has a lot of advantages like flexibility and ease at scale. Mapp...
Test Coverage analysis (with JaCoCo and Sonar) for... One of the main metrics for a software project is Test Coverage: if done properly, it gives you a quick picture about how much code is 'protected' by ...


  1. Hi Moi!
    Nice example here! It is worth keeping pace with the latest Spring versions so you can use all these goodies!
    I liked the concept of narrowing the REST methods avaiable by just using the @GetMapping. Otherwise you would have had to mess with security or with @ReadOnly annotations in lower layers…

    One you thing you might want to take a look at is Spring Data Rest as there are some interesting functionality (like entity projections, paging/sorting) all the way from JPA to the REST layer.


    PS Good luck with the book!

    • Thanks Victor! Indeed, Spring Data Rest is very useful for simple CRUD for entities. The only thing I don’t like is that it comes with HATEOAS by default and can’t be disabled, what could imply more work on the client side…

Leave a Reply