Creating REST API in Spring boot – Part5

In Part4 we implemented our service layer which sits between controller and DB. Now we will use QuoteService to fetch data from QuoteDB to serve content to end user.

As we have annotated QueryServiceImpl as service component, we can ask spring to provide us an instance of this service. This is done by Dependency injection

One of the way to use dependency injection in spring is using annotation @Autowire. When spring boots it initializes all annotated components. If a member variable in annotated class is annotated with @Autowire then spring assign it the required instance (if available, otherwise process fails to start).

We will use @Autowire to get instance of our QuoteService. We can do this as below

@Autowired
private QuotesService service;

Now we can implement our first end point for fetching quotes page by page as below

@GetMapping("/quotes/{page}")
public List<Quote> getQuotes(@PathVariable("page") int page) {
if(page == 0) {
return Collections.emptyList();
}
return service.getQuotes(page);
}

At this point if you run the process either from IDE or using mvn spring-boot:run command and then hit url http://localhost:8080/quotes/1 then it should return you list of 20 quotes.

Like this we can implement rest as well. Below is complete implementation of our RestController

@RestController
public class QuotesResource {

@Autowired
private QuotesService service;


@GetMapping("/quotes/{page}")
public List<Quote> getQuotes(@PathVariable("page") int page) {
if(page == 0) {
return Collections.emptyList();
}
return service.getQuotes(page);
}

@GetMapping("/quotes")
public List<Quote> getQuotes(@RequestParam("topic") String topic
,@RequestParam(value= "page", required = false, defaultValue = "0") int page) {
if(topic == null || topic.trim().length() == 0) {
return getQuotes(1);
}
return service.getQuotes(topic, page);
}

@GetMapping("/topics")
public List<Topic> getTopics() {
return service.getTopics();
}
}

Apply this change and re-run the spring application. Try to hit endpoint using browser or any other REST client (eg:Postman).

What’s Next:

I created this service in order to create an application which shows quotes to user. Its nice to show relevant images with quotes. Pexels provides API for fetching royalty free images on any topic. We can use this to create an endpoint which will provide images to our end user. In Next post we will create PexelService to consume API provided by Pexels.com using a very sophisticated library provided by Netflix named feign client.

Leave a comment

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