Spring Boot CRUD with MongoDB, Postman For Starters

Arkam_ahamed
Sysco LABS Sri Lanka
8 min readJul 13, 2023

This post will cover the basics of creating a CRUD REST API using Spring Boot with MongoDB as the database. The post will follow a step-by-step approach to creating a simple beginner-friendly REST API using Spring Boot.

You can get the code for this project here — arkamahamed-git/MongoDBRepo (github.com)

Prerequisites

  1. Java 8 or higher
  2. MongoDB
  3. Eclipse / IntelliJ
  4. Maven

What we will cover

  1. Create a Spring Boot project
  2. Adding required dependencies
  3. Connecting to the MongoDB cluster
  4. Connecting MongoDB cluster with Spring Project
  5. Create Model Class(Entity class)
  6. Repository Layer
  7. Create business logic to handle data(Service Layer)
  8. Creating the controller to handle requests
  9. Run the Application in Tomcat Server
  10. Testing the APIs using Postman

1. Create a Spring Boot project

Use Spring initializer at start.spring.io to create a “web” project by selecting maven under project type selection and Java under language selection as shown in the below screenshot.

You can give your preferred name, description, package name, packaging type and the Java version under the project metadata section.

2. Adding required dependencies

Use this option to add required dependencies to your spring project. For this sample, we need Spring Web, Lombok, and Spring Data MongoDB.

Press the generate button to download your created spring project as the project type you have given in your project metadata.

Open IntelliJ and go to File > Open > Select the location of your downloaded spring project.

3. Connecting to the MongoDB cluster

Go to MongoDB cloud at https://cloud.mongodb.com and follow the below steps to create your database for the project

  1. Create/Login into your MongoDB account to access the MongoDB cloud.

2. Create a new Database using the “Create Databases” option and enter the preferred database and collection name.

3. Getting the URL of the cluster to connect it to our Spring boot application

Step 1 (Press connect your application)
Step 2 (Change the driver to Java and select the latest version)
Step 3 (Copy the URL)

Make sure to Replace <password> with the password of the user you logged in. Replace myFirstDatabase with the name of the database that connections will use by default.

4. Connecting MongoDB cluster with Spring Project

Go to /src/main/resources/application. Properties under your spring project and paste the URL which you copied from the previous step

5. Create Model Class(Entity class)

Creating a class named student and mapping it using @Document annotation. The annotations @Data and @AllArgsConstuctor is from the Lombok dependency which is used to generate boilerplate code ( Eg:- Getters and Setters)

@Transient annotation is used for the age to ignore the field to not persist in the database. Since the value of the age will be calculated from the data passed by the DOB.

6. Repository Layer

The repository allows us to store/access the information stored in the Mongo database. We can add more methods inside the repository so we can increase the business logic to our own convenience like below.

7. Create business logic to handle data(Service Layer)

The Service layer’s single responsibility is to do any logic required with the data received by the Controller.

  1. Adding the @Service marks a Java class that performs some services, such as executing business logic, performing calculations, and calling external APIs.

2. The Create operation which stands for the C in CRUD is basically to save data to the repository. In the below screenshot I have written some business logic to first check whether the user is returning a null value to the body( In our case its name and DOB) if they are returning a null value, A bad request(400) will be returned to the user and if the user is returning a proper body value the data will be added to the MongoDB database and a JSON response will be given to the user.

3. The Read operation which stands for the R in CRUD is used to retrieve all the data from the database.

4. The Update operation which stands for the U in CRUD is used to update specific data by passing mostly the id which has a unique value. In the below screenshot I have first checked whether the id passed by the user exists in our database and if it doesn’t a NOT FOUND(404) error is returned and in the other case if it exists the new body passed by the user is set to the previous data with that id in the database.

5. The Delete operation which stands for the D in CRUD is used to delete the data of the id passed by the user. In the screenshot below, I have first checked whether the id passed by the user exists in our database, and if it doesn’t a NOT FOUND(404) error is returned and in the other case if it exists the data with that id passed by the user is deleted and a JSON response is returned to the user.

8. Creating the controller to handle requests

@RestController annotation is used to create RESTful web services using Spring MVC. Spring @RestController takes care of mapping request data to the defined request handler method. Once the response body is generated from the handler method, it converts it to JSON or XML response. The @CrossOrigin annotation enables cross-origin resource sharing. By default, it allows all origins, all headers, and the HTTP methods specified in the @RequestMapping annotation.

  1. @PostMapping annotation maps HTTP POST requests onto specific handler methods. Inside the PostMapping the end path of the URL is specified by using the path like in the below screenshot. Since we are getting the value from the user the @RequestBody annotation is used and then it is saved inside the repository AKA our MongoDB database.

2. @GetMapping annotation maps HTTP GET requests onto specific handler methods. Inside the GetMapping the end path of the URL is specified by using the path like in the below screenshot. We are retrieving the data from the repository.

3.@PutMapping annotation maps HTTP PUT requests onto specific handler methods. Inside the PutMapping the end path of the URL is specified and the id is passed within curly braces and also @PathVariable annotation should be given whatever is inside the curly braces in our case it's “id”. Both of these should be equal then only the Spring boot will know that the value after the slash “/” is from the user and it will be mapped. Then if the id exists in the database the newly sent body will be replaced with the previous one.

4.@DeleteMapping annotation maps HTTP DELETE requests onto specific handler methods. Inside the DeleteMapping the end path of the URL is specified and the id is passed within curly braces and also @PathVariable annotation should be given whatever is inside the curly braces in our case it's “id”. Both of these should be equal then only the Spring boot will know that the value after the slash “/” is from the user and it will be mapped. Then if the id exists in the database that specific data will be deleted and a response will be sent to the user.

9. Run the Application on Tomcat Server

By clicking the green play button the application will start to run on the inbuilt Tomcat Server like in the below screenshot.

10. Testing the APIs using Postman

By heading on to this link download the Postman desktop version Download Postman | Get Started for Free or test the API online by heading to the Postman official site Postman API Platform | Sign Up for Free. In my case, I would be testing it with the desktop version I have installed.

1. First you will have to change the HTTP request, in our case it is a POST request, and then the URL should be passed. By default, the Tomcat server listens to port 8080. In my example below I have added “api/add” as the endpoints since the “/api” was passed to the @RequestMapping annotation and the “/add” was passed to the PostMapping annotation.

We have to click the Body after passing the URL and then change the format to raw and send the body as JSON. Once the POST request is been sent we will get a 200 successful response back as shown in the above screenshot.

2. Now we will retrieve the Data which we added now by using the GET HTTP request and passing the correct URL path which we specified in the Controller.

As we can see in the above screenshot the data which we posted has been retrieved successfully.

3. Now let's update the data which we created by using the PUT HTTP request and passing the correct URL path which we specified in the Controller and also the correct id which the data was added.

As you can see in the below screenshot I have changed the name from “arkam” to “kasun”. If you want to you can double-check it by doing a GET request again( You would get the updated data).

4. Now let’s delete the data which we updated by using the DELETE HTTP request and passing the correct URL path which we specified in the Controller and also the correct id which the data was added.

We can see in the above screenshot that we have successfully deleted the student with that id. If you want to you can double-check it by doing a GET request again( You would get an empty array ).

--

--

Arkam_ahamed
Sysco LABS Sri Lanka

Full-Stack Engineer, Football player and a Tech enthusiast. Writes about Java, Docker, Kubernetes, API testing and the current trends in Technology❤️