This tutorial explains how to implement RESTful web service using SpringBoot and MongoDB. This tutorials uses already implemented REST services using Node.js and ExpressJS frameworks. Here the same examples tested with SpringBoot.
The following are the frameworks used in this tutorial for running the given example. If you are very much interested in learning the REST Web Services concepts, please visit our pal Eugen’s world class video course on BUILD YOUR REST API WITH SPRING.
- Spring Boot
- MongoDB
- ExpressJS
- Node.js
- RESTful Concepts
In this post I will implement the REST API designed in one of my previous posts here.
Creating a simple Maven project in Eclipse
The following steps helps you to create a simple Maven project in Eclipse. We have several good tutorials on Maven for the beginners. If you are looking for interesting reads on Maven, please read Apache Maven for Beginners, Create Web Application Project with Maven and How to Build Spring MVC Application with Maven.
Project Type selection
Workspace and archetype selection
Maven project properties
The final project structure
Now that the basic maven based Spring boot is ready, let me give you an overview of Springboot and the idea behind it.
REST API using Spring Boot and MongoDB
What is Spring Boot?
Spring Boot is approach to develop Spring based application with very less configuration. It leverages existing Spring projects as well as Third party projects to develop production ready applications. It provides a set of Starter Pom’s or gradle build files which one can use to add required dependencies and also facilitate auto configuration.
Depending on the libraries on its classpath, Spring Boot automatically configures required classes. For example to interact with DB, if there is Spring Data libraries on class path then it automatically sets up connection to DB along with the Data Source class.
More about Spring Boot can be found here.
Creating RESTful Web Service
I will not show you how to create a RESTful Web Service using Spring Boot. The API which I am going to implement in this post has already been defined in one of my previous posts here.
spring-boot-starter-parent
Lets update the pom.xml
to add refer to the parent pom which is: spring-boot-starter-parent
. This is the starter pom provided by Spring Boot project. This start pom:
- sets up the maven properties
- basic dependency to spring-core
- setting up location for resource files
- setting up maven plugins including the plugin provided by spring boot to run its application
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.javabeat</groupId> <artifactId>springboot-rest-demo</artifactId> <version>0.1</version> <name>Spring Boot REST API Demo</name> <properties> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.3.RELEASE</version> </parent> </project>
spring-boot-starter-web
In order to build RESTful Service we would need make use of: spring web, JSON processing libraries, embedded tomcat or tomcat libraries, may be some library for validators like Hibernate validator. We might not remember all the dependencies required or might have to refer to some place to know which dependencies are required.
To solve such issues Spring Boot provides a pom already configured with the dependencies required to build a web application and that pom is called: spring-boot-starter-web
. Updating our pom.xml to add it as a dependency we get:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.javabeat</groupId> <artifactId>springboot-rest-demo</artifactId> <version>0.1</version> <name>Spring Boot REST API Demo</name> <properties> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
Similarly we have a pom: spring-boot-starter-data-mongodb
which includes dependencies to mongo java driver, spring transaction, spring data for mongodb. So our final pom.xml looks like:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.javabeat</groupId> <artifactId>springboot-rest-demo</artifactId> <version>0.1</version> <name>Spring Boot REST API Demo</name> <properties> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> </dependencies> </project>
Spring Boot Application
We need to create a main class which initializes the Spring Boot application and runs it. We also annotate the class with @SpringBootApplication
. This annotation is tells the Spring application to enable autoconfiguration and component scan and also tells the Spring application that this particular class is also a configuration:
package app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(new Object[] { Application.class }, args); } }
Implementing the RESTful APIs
Let me create a model class to hold Book details retrieved from DB.
package app.model; import org.springframework.data.annotation.Id; public class Book { @Id private String id; private String name; private String isbn; private String author; private int pages; public Book(){} public Book(String name, String isbn, String author, int pages){ this.name = name; this.isbn = isbn; this.author = author; this.pages = pages; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } }
Lets add Repository class to interact with the DB
package app.repository; import app.model.Book; import org.springframework.data.mongodb.repository.MongoRepository; public interface BookRepository extends MongoRepository<Book, String>{ }
The MongoRepository provides basic CRUD operation methods and also an API to find all documents in the collection.
Implementing Create and Get Details API
Lets implement our controller. First is the API to create new book and also to get the details of a given book:
package app.controller; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import app.model.Book; import app.repository.BookRepository; @RestController @RequestMapping("/book") public class BookController { @Autowired private BookRepository bookRepository; @RequestMapping(method = RequestMethod.POST) public Map<String, Object> createBook(@RequestBody Map<String, Object> bookMap){ Book book = new Book(bookMap.get("name").toString(), bookMap.get("isbn").toString(), bookMap.get("author").toString(), Integer.parseInt(bookMap.get("pages").toString())); bookRepository.save(book); Map<String, Object> response = new LinkedHashMap<String, Object>(); response.put("message", "Book created successfully"); response.put("book", book); return response; } @RequestMapping(method = RequestMethod.GET, value="/{bookId}") public Book getBookDetails(@PathVariable("bookId") String bookId){ return bookRepository.findOne(bookId); } }
Lets run the application by either using Spring Boot maven plugin i.e by running mvn spring-boot:run
or by running the main class Application.java
from Eclipse or your IDE. I will use Postman REST Client to invoke the create API:
The below is the screenshot from Postman to invoke the Get Book Details API:
Implementing Update API
Now lets implement the Update API (just showing the method implemented here, it should be part of the BookController class defined above):
@RequestMapping(method = RequestMethod.PUT, value="/{bookId}") public Map<String, Object> editBook(@PathVariable("bookId") String bookId, @RequestBody Map<String, Object> bookMap){ Book book = new Book(bookMap.get("name").toString(), bookMap.get("isbn").toString(), bookMap.get("author").toString(), Integer.parseInt(bookMap.get("pages").toString())); book.setId(bookId); Map<String, Object> response = new LinkedHashMap<String, Object>(); response.put("message", "Book Updated successfully"); response.put("book", bookRepository.save(book)); return response; }
Screenshot from Postman REST client after executing the Update:
Implementing the Delete API
@RequestMapping(method = RequestMethod.DELETE, value="/{bookId}") public Map<String, String> deleteBook(@PathVariable("bookId") String bookId){ bookRepository.delete(bookId); Map<String, String> response = new HashMap<String, String>(); response.put("message", "Book deleted successfully"); return response; }
Screenshot from Postman REST client after executing the Delete:
Implementing the Get All Books API
@RequestMapping(method = RequestMethod.GET) public Map<String, Object> getAllBooks(){ List<Book> books = bookRepository.findAll(); Map<String, Object> response = new LinkedHashMap<String, Object>(); response.put("totalBooks", books.size()); response.put("books", books); return response; }
Screenshot from Postman REST client after executing the Get all books:
With this I have shown you how to build a REST API for CRUD operations using Spring Boot and MongoDB. One can see that with minimum configuration I have been able to write a full fledged implementation of REST API. I hope this tutorial have helped to understand how to write Spring Boot application with MongoDB.
MongoDB is the popular NoSQL database and Spring Boot is the latest framework from Spring community to run the Spring applications with minimal configurations. Hence, Spring Boot and MongoDB makes good combination to work together for building the RESTful APIs.
If you have any questions on how to write Spring Boot application with MongoDB, please write it in the comments section. Also you can access my Github below for the complete code for Spring Boot and MongoDB integration example. Have a happy reading!!!
The project can be found on Github here.