Creating REST API in Spring boot – Part3

Rest controller provides end point which will be consumed by end user. For creating a rest controller in spring boot we simply need to annotate the class with annotation @RestController.

As of now we will define below endpoints

  1. /quotes/{page} – to fetch quotes page by page
  2. /quotes?topic={topic} -> to fetch quotes by topic or tag
  3. /topics – to fetch all available topics and its sub topics

Create a class Named QuoteResource and annotate it with @RestController. Define above mentioned three methods in order to provide endpoints

public class QuotesResource {

public List<Quote> getQuotes(@PathVariable("page") int page) {
return null;

public List<Quote> getQuotes(@RequestParam("topic") String topic
, @RequestParam(value = "page", required = false, defaultValue = "0") int page) {
return null;

public List<Topic> getTopics() {
return null;


@PathVariable : fetches values from URL defined in GetMapping or any other mapping provided. If user hits url /quotes/2 then first method getQuotes will be called and 2 will be passed as param page

@RequestParam: Request param fetches values from Request parameters. In case of GET request request params fetches values from query strings, in case of POST or PUT etc it fetches values from request body as well. Incase a param is optional then we have to define as default value, like we did for page in second getQuotes method

Now we just created a Controller and we have created our backend DB QuoteDB in last post. All we need a communicator or connector which fetches values from DB and provide to controller. We call this piece Service.

What is Service:

You can consider DB as source of data which doesn’t know what it is. It just consider it as piece of data. Controller knows how to present the data to end user. The service layer contains all the business logic and use that to convert raw data received from DB to some useful form. This architecture keeps one responsibility for each component which is easy to manage and test.

Please note: Service layer is supposed to be purely functional. It should never save any state it just contains functions which may or may not take any input and perform particular operation and may or may not return result.

In next post we will create the service layer

Leave a comment

Your email address will not be published. Required fields are marked *