Creating RESTful API using SpringBoot and MongoDB

Reading Time: 3 minutes

In this blog, we are going to create RESTful APIs using spring boot and containerized MongoDB.

What are RESTful API, SpringBoot, and Containerized MongoDB

In this section, we will go through the term’s REST API, SpringBoot, and Containerized MongoDB

RESTful API

A REST API (also known as RESTful API) is an application programming interface that conforms to the constraints of REST architecture. REST stands for representational state transfer. REST has quickly become the de-facto standard for building web services on the web because they’re easy to make and easy to consume.

Spring Boot

Spring Boot is an open-source Java-based framework used to create a micro Service. It provides a good platform to develop a stand-alone and production-grade spring application that you can just run. Most Spring Boot applications need minimal Spring configuration.

Features

  • Create stand-alone Spring applications
  • Embed Tomcat
  • Automatically configure Spring and 3rd party libraries
  • Need Minimal Spring configuration

Containerized MongoDB

MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need. MongoDB stores data in flexible, JSON-like documents. The document model maps to the objects in your application code, making data easy to work with. A Docker container is a single unit containing an application and all of its necessary configurations or dependencies. MongoDB can run in a container.

Maven Dependencies

pom.xml file will be as below −

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>io.knoldus</groupId>
	<artifactId>MongoDB-SpringBoot-Rest-API</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>MongoDB-SpringBoot-Rest-API</name>
	<description>Project for </description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Model Class

In this class, we will be annotating it with @Document annotation.

POJO structure of the Course object

package io.knoldus.course;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Course {
    @Id
    private String id;
    private String name;
    private String description;

    public Course() {
    }

    public Course(String id, String name, String description) {
        this.id = id;
        this.name = name;
        this.description = description;
    }


    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 getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Controller Class

In this class, we will be annotating it with @RestController annotation. Hence it will handle our web requests.

package io.knoldus.course;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
public class CourseController {

    @Autowired
    private CourseService courseService;

    @RequestMapping("/courses")
    public List<Course> getAllCourses() {
        return courseService.getAllCourses();
    }

    @RequestMapping("/courses/{id}")
    public Optional<Course> getCourse(@PathVariable String id) {
        return courseService.getCourse(id);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/courses")
    public void addCourse(@RequestBody Course course) {
        courseService.addCourse(course);
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/courses/{id}")
    public void updateCourse(@RequestBody Course course) {
        courseService.updateCourse(course);
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/courses/{id}")
    public void deleteCourse(@PathVariable String id) {
        courseService.deleteCourse(id);
    }
}

Repository

This interface extends the MongoRepository interface, as we are using MongoDB for persisting data.

package io.knoldus.course;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CourseRepository extends MongoRepository<Course, String> {
}

Application.Properties

We will create this file under the resources folder. This file will contain MongoDB connection parameters.

spring.data.mongodb.authentication-database=user-value
spring.data.mongodb.username=user-username
spring.data.mongodb.password=user-password
spring.data.mongodb.database=user-dbname
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
spring.data.mongodb.auto-index-creation=true

Docker File

Create the docker-compose.yml at the root of your project directory. Configure and install MongoDB and Mongo Express using the official images.

version: "3.3"
services:
  # MongoDB Service
  mongodb:
    image: mongo:latest
    container_name: mongodb
    restart: unless-stopped
    environment:
      MONGO_INITDB_ROOT_USERNAME: user_username
      MONGO_INITDB_ROOT_PASSWORD: user_password
    ports:
      - 27017:27017
    volumes:
      - ./database-data:/data/db

  # Mongo Express Service
  mongo-express:
    image: mongo-express:latest
    container_name: mongo-express
    restart: unless-stopped
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: user_username
      ME_CONFIG_MONGODB_ADMINPASSWORD: user_password
      ME_CONFIG_MONGODB_SERVER: mongodb

Thanks for reading !!

Written by 

I am Software Consultant at Knoldus and I am curious about learning new technologies.