Getting Started with Microservices using Spring Boot and Cloudant

7 min read

Getting started with microservices using Spring Boot and Cloudant

As part of developing cloud-native business applications, the microservices architecture has gained popularity because it simplifies the delivery of independently packaged and deployed application units as part of a larger application. By breaking down large monolithic applications into components of a microservices-based application, teams can work more independently. Additionally, thanks to devops continuous integration/continuous delivery tools, new application functionality can be delivered as its completed in an automated, replicable fashion.

In this brief how-to, you’ll learn how to create a simple microservice that manages product reviews in a Cloudant NoSQL database. The example code is written in Java and leverages the Spring Boot framework. It provides basic operations of saving and querying social review comments in the Cloudant database hosted on IBM Cloud platform.

This small sample is a modified excerpt of a larger, more complex microservices-based retail web and mobile application that is one of the IBM Cloud Architecture Center reference implementations depicted below:

IBM Cloud Architecture Center

Review microservice described in this post is highlighted above (in context of larger reference architecture implementation)

In the next installment of this series, I’ll walk you through how to package this Spring Boot application as a Docker container and deploy to a IBM Cloud container service.

Get development tools, provision service, get code

There several ways to access a Cloudant database in a Spring Boot application (actually Java app) such as java-cloudant, ektorp, jcouchdb etc. You can see all these libraries here. The Cloudant labs team have also released a Cloudant Spring Boot Starter which extends the java-cloudant library to provide Spring bean auto-configuration. It gives all the power of the java-cloudant library and is well integrated with Spring Boot, so this is what is used in this example.

Step 1: Download and install development tools

To complete this tutorial, you will need the following:

Once you’ve installed the above tools, begin by cloning the sample application from GitHub to your local environment:

git clone<br>

Step 2: Provision a Cloudant NoSQL DB in IBM Cloud

To provision the Cloudant service, you must have a IBM Cloud account. Login to your IBM Cloud account or register for a new account (it’s free).

To create the Cloudant service, go to the catalog: (remember to login to your IBM Cloud account). Give your Cloudant service a name like refarch-cloudantdb (select the Rename Service choice under the ACTIONS dropdown in the list of services).

For testing, you can select the “Lite” plan, then click “Create”. Once created, open the credentials tab and note your Cloudant Service credentials, for example:

 'username': 'xxxx-yyyy-bluemix',<br>
 'password': 'zzzzz',<br>
 'host': '',<br>
 'port': 443,<br>
 'url': ''<br>

Clicking the “Launch” button will open the Cloudant management console. It’s empty now.

Step 3: Build the sample application with Gradle

Now, you can work on the application. Spring Boot application can be built with either Gradle or Maven. For this how-to, the instructions are for Gradle.

Navigate into the GitHub repository root folder refarch-cloudnative-micro-socialreview; you should find the build.gradle file in that folder. It defines the library dependencies and basic build configuration such as built output. The app uses the following dependencies:

    compile("org.springframework.boot:spring-boot-starter-web:1.4.0.RELEASE") {<br>
        exclude module: "spring-boot-starter-tomcat"<br>
    compile group: 'com.cloudant', name: 'cloudant-spring-boot-starter', version: '0.0.2'<br>
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.4.0.RELEASE'<br>

Notice the dependency cloudant-spring-boot-starter; it will assure that the Cloudant Spring Boot Starter will be downloaded and added to the project when you build it. When you run the Gradle build later, all the dependencies will be downloaded when it is first run.

Code walkthrough

With Spring Boot, building cloud-native microservices app is pretty easy and straightforward. Let’s take a look at the code. Under the root directory, most of the files and folders are build-related. The application code is managed under the src folder. I’ll review these four classes:

  • socialreview.cloudant.Application – bootstrap and server

  • socialreview.cloudant.Review – entity representation of a review in the database

  • socialreview.cloudant.ReviewRestController – microservice REST API for reviews

  • socialreview.cloudant.ReviewRestControllerTest – sniff test of microservice REST API for reviews

Code review: src/main/java/socialreview/cloudant/

This is the bootstrap class that loads the web application and starts an embedded server.

public class Application {<br>
    public static void main(String[] args) {<br>, args);<br>
        System.out.println("SocialReview Spring Boot Microservice is ready");<br>

The @SpringBootApplication is a convenience annotation that loads useful Spring components such as the @Configuration@ComponentScan and @EnableAutoConfiguration. It also adds the Spring webmvcto the classpath and activates the DispatcherServlet to start handling request.

The main function invokes to bootstrap the application.

Code review: src/main/java/socialreview/cloudant/

This is an entity class that maps to the document saved in Cloudant NoSQL database. Spring Boot framework will automatically serialize the entity object with the response from the Cloudant database as well as convert it to JSON when sending the request back for the REST request.

public class Review {<p></p>
<p>    private String _rev;<br>
    private String _id;<br>
    private String comment;<br>
    private int itemId;<br>
    private int rating;<br>
    private String reviewer_email;<br>
    private String reviewer_name;<br>
    private String review_date;</p>
<p>    public Review(){}</p>
<p>    public Review(boolean isStub) {<br>
        this.comment = "It works";<br>
        this.itemId = 13401;<br>
        this.rating = 5;<br>
        this.reviewer_email = "";<br>
        this.reviewer_name = "Gang Chen";<br>
        this.review_date = "08/18/2016";<br>

Code review: src/main/java/socialreview/cloudant/

This is the main class that exposes the REST API and interacts with the Cloudant database to perform save and query operations.

public class ReviewRestController {<p></p>
<p>    @Autowired<br>
    private Database db;<br>

The @RestController tells the Spring MVC to handle web requests with the root web context root as review.

When the Cloudant Spring Boot Starter is added as a dependency it is automatically hooked into the Spring application configuration. Using properties provided in the application’s property source the starter configures a Cloudant database bean that can be injected via dependency injection by specifying the @Autowired annotation.

// Create a new review<br>
@RequestMapping(method = RequestMethod.POST, consumes = "application/json")<br>
public @ResponseBody String saveReview(@RequestBody Review review) {<br>
    System.out.println("Save Review " + review);<br>
    Response r = null;<br>
    if (review != null) {<br>
        r =;<br>
    return r.getId();<br>

This code saves/persists a review comment document into the Cloudant database. It is a POST request. The Cloudant Java client makes the persistent very simple with a single API call,, shown above. On the other hand, the GET (query) function is a little bit more complex.

// Query reviews for all documents or by ItemId<br>
public @ResponseBody List getAll(@RequestParam(required=false) Integer itemId) {<br>
    // Get all documents from socialreviewdb<br>
    List allDocs = null;<br>
    try {<br>
        if (itemId == null) {<br>
            allDocs = db.getAllDocsRequestBuilder().includeDocs(true).build().getResponse()<br>
        } else {<br>
            // create Index<br>
            // Create a design doc named designdoc<br>
            // A view named querybyitemIdView<br>
            // and an index named itemId<br>
            new IndexField[]{new IndexField("itemId",SortOrder.asc)});<br>
            System.out.println("Successfully created index");<br>
            allDocs = db.findByIndex("{\"itemId\" : " + itemId + "}", Review.class);<br>
    } catch (Exception e) {<br>
      System.out.println("Exception thrown : " + e.getMessage());<br>
    return allDocs;<br>

The @RequestParam(required=false) Integer itemId parameter allows you to query the entire review documents or just all reviews associated with a specific itemId. Getting all documents is easy, as there is a built-in API from Cloudant Java library to do that.

Query by itemId is slightly more complex. Cloudant database typically uses the MapReduce mechanism to perform queries. To achieve this, normally you will create an index and save that in the design document (a special Cloudant document). It will only be created once at the first use. Once the index is created, the query can be performed by invoking the index using db.findByIndex().

The returned object will be serialized as a Review entity object in JSON format.

Code review: src/main/resources/application.yml

# Spring properties<br>
     name: socialreview-microservice<p></p>
<p># Server configuration<br>
  context-path: /micro<br>
  port: 8080</p>
<p># Cloudant Confiugration<br>
  db: socialreviewdb<br>

This file defines the application configuration such as name of the application, the base URL for the web app and which port it runs on. I also put the Cloudant configuration information in this file. You need to update the cloudant configuration section to fill in the Cloudant instance credentials you created earlier. The ‘db’ property is already set to socialreviewdb to configure the Cloudant client to direct all database requests to that database name.

NOTE: Please use your Cloudant credential ‘url’ or ‘host’ property that doesn’t include the password for your account for the “url” entry in the application.yml file. For instances running on IBM Cloud this will be the ‘host’ value and the protocol. For example:

Code review: src/test/java/socialreview/cloudant/

I’ve written a simple integration test case to validate that the connection to Cloudant is successful and able to fetch all the documents. You can follow the instruction later to run the test case.

Build and Run the application

Once you have Cloudant configured, update the src/main/resources/application.yml file for the Cloudant credentials:

  • username

  • password

  • url

NOTE: Please use your Cloudant credential ‘url’ or ‘host’ property that doesn’t include the password for your account for the “url” entry in the application.yml file. For instances running on IBM Cloud this will be the ‘host’ value and the protocol. For example:

Under the repository root directory, run the following command to build and run the application:

$ cd refarch-cloudnative-micro-socialreview<br>
$ ./gradlew build<br>

Make sure that the application build completes successfully. It will package the compiled application under build/libs directory. Now, you can run the application with the following command:

$ java -jar build/libs/micro-socialreview-0.1.0.jar<br>


Yes, the final distribution of the application is in a jar file and all you need to run is to execute the Jar file. The application should be running at port 8080. Open a browser with following URL:


This will return all the reviews in the database. You can use Chrome POSTMAN to insert a new review document. Or use the following curl command to insert a review comment:

curl --request POST\<br>
  --url 'http://localhost:8080/micro/review' \<br>
  --header 'accept: application/json' \<br>
  --header 'content-type: application/json' \<br>
  --data @- <<'EOF'<br>
  {"comment": "Nice product",<br>
    "itemId": 13402,<br>
    "rating": 3,<br>
    "reviewer_name": "Gang Chen",<br>
    "review_date": "12/31/2017"}'<br>


It should return a Cloudant document ID upon successful execution. You can validate the operation by hitting the GET URL again:


The saved review comment should be returned. Alternatively, you can launch the Cloudant database console and review the documents there as well.

I also provided a simple integration test case that you can run with:

$ ./gradlew clean test<br>


Next: Leveraging containers to simplify deployment and scalability

This post showed you how easily you can build a microservice application to access a Cloudant database using Spring Boot and Cloudant Java client. But it is not that exciting to run the application locally. To demonstrate how the microservice architecture simplifies delivering scalability, the next post in this series will describe how to package the Social Review Spring Boot application as a Docker image, test the Docker container locally, and deploy and run it on IBM Cloud Container platform.

Sign up for IBM Cloud. It’s free!


Be the first to hear about news, product updates, and innovation from IBM Cloud