Azure Cosmos DB + MongoDB API + Spring Boot - Build REST CRUD APIs

Hello everyone, Hope you are doing well. In this tutorial, you will learn how to build REST CRUD APIs with Spring Boot, Spring Data MongoDB, Azure Cosmos DB, and Azure Cosmos DB MongoDB API.


A little bit of Background

Azure Cosmos DB

Azure Cosmos DB is a fully managed NoSQL database for modern app development. Single-digit millisecond response times, and automatic and instant scalability, guarantee speed at any scale. 

Azure Cosmos DB MongoDB API

The Azure Cosmos DB API for MongoDB makes it easy to use Cosmos DB as if it were a MongoDB database. You can apply your MongoDB experience and continue to use your favourite MongoDB drivers, SDKs, and tools by pointing your application to the API for the MongoDB account's connection string.


Spring Boot

Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can "just run". 

Spring Data MongoDB

The Spring Data MongoDB project provides integration with the MongoDB document database. Key functional areas of Spring Data MongoDB are a POJO-centric model for interacting with a MongoDB DBCollection and easily writing a Repository style data access layer.

After completing this tutorial what we will build? 

We will build REST APIs  CRUD features: 




Step 1: Create an Azure Cosmos DB

Sign in to Azure portal https://portal.azure.com/#home and search for "Azure Cosmos DB" like below.

You will be taken to a page like the below image, Then click on the "Create Azure Cosmos DB account" button.

Select API Option,
Then click on the "create" button of the "Azure Cosmos DB API for MongoDB" division.

You will be taken to a page like the below image, 
Enter/Select Resource groupAccount name, etc... Then click on the "Review + create" button.  

You will be taken to a page like the below image, 
Then click on the "Create" button.

Now, You can see "Deployment is in progress" like the below image.

Once deployment is completed you can see the "Your deployment is complete" page like the below image.

Then go to the "Data Explorer" and click on the "New Collection".

Then enter "Database name", "Collection id" etc... like the below image.
Then click on the "OK" button.

Then click on the "Connection String"
Copy "PRIMARY CONNECTION STRING" and keep it safe for future purposes.




Step 2: Creating a simple spring boot web application

First, open the Spring initializr https://start.spring.io/

Then, Provide the Group and Artifact name. We have provided Group name com.knf.dev.demo and Artifact spring-azure-cosmosdb-mongo-api-crud. Here I selected the Maven project - language Java - Spring Boot 2.7.1 and add Spring web dependency and Spring Data MongoDB dependency. 

Then, click on the Generate button. When we click on the Generate button, it starts packing the project in a .zip(spring-azure-cosmosdb-mongo-api-crud.zip) file and downloads the project. 
Then, Extract the Zip file and import the project on your favourite IDE.

Final Project Directory:



Pom.xml

<?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.1</version>
<relativePath/>
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>spring-azure-cosmosdb-mongo-api-crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-azure-cosmosdb-mongo-api-crud</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</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>


application.properties

Configure your Spring Boot application to use your Azure Cosmos DB API for MongoDB.
spring.data.mongodb.database=<Database name>
spring.data.mongodb.uri=<PRIMARY CONNECTION STRING>


Create User Model

package com.knf.dev.demo.model;

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

@Document(collection = "user")
public class User {

@Id
private String id;
private String firstName;
private String lastName;
private String emailId;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmailId() {
return emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

public User(String id, String firstName,
String lastName, String emailId) {

this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
}

public User() {

}
}
  • @Id annotation is currently used by Spring to support mapping for other non-relational persistence databases or frameworks that do not have a defined common persistence API like JPA.
  • @Document is an annotation provided by the Spring Data project. It is used to identify a domain object, which is persisted to MongoDB. So you can use it to map a Java class into a collection inside MongoDB.


Create User Repository

package com.knf.dev.demo.repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import com.knf.dev.demo.model.User;

public interface UserRepository
extends MongoRepository<User, String> {

}
MongoRepository is just a specialized PagingAndSortingRepository suited to Mongo, which in turn is a specialized CrudRepository.



Create Rest Controller

package com.knf.dev.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.knf.dev.demo.model.User;
import com.knf.dev.demo.repository.UserRepository;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api/v1")
public class UserController {
@Autowired
private UserRepository userRepository;

@GetMapping("/users")
public List<User> getAllUsers() {

return userRepository.findAll();
}

@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById
(@PathVariable(value = "id") String id) {

return userRepository.findById(id)
.map(value -> new ResponseEntity<>
(value, HttpStatus.OK))
.orElse(ResponseEntity.notFound().build());

}

@PostMapping("/users")
public User createUser(@RequestBody User user) {

return userRepository.save(user);
}

@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser
(@PathVariable(value = "id") String id,
@RequestBody User userDto) {

Optional<User> userData = userRepository
.findById(id);
if (userData.isEmpty()) {
return ResponseEntity.notFound().build();
}

User user = userData.get();
user.setEmailId(userDto.getEmailId());
user.setLastName(userDto.getLastName());
user.setFirstName(userDto.getFirstName());
user.setId(id);
final User updateUser = userRepository.save(user);
return ResponseEntity.ok(updateUser);
}

@DeleteMapping("/users/{id}")
public Map<String, Boolean> deleteUser
(@PathVariable(value = "id") String id) {

Optional<User> user = userRepository.findById(id);
Map<String, Boolean> response = new HashMap<>();
if (user.isEmpty()) {
response.put("User Not Found", Boolean.FALSE);
} else {
userRepository.delete(user.get());
response.put("deleted", Boolean.TRUE);
}
return response;
}
}


Spring Boot Main Driver

package com.knf.dev.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}



Step 3: Local Setup and Run the application

Step 1: Download or clone the source code from GitHub to a local machine - Click here


Step 2: mvn clean install


Step 3: Run the Spring Boot application - 

mvn spring-boot:run or Run as Spring Boot application.



Step 4: Test the APIs using postman

1. Add User:



2. Get User By Id:



3. Update User:



4. Get All Users:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete