Build a RESTful API with Spring boot and MongoDB

Build a RESTful API with Spring boot and MongoDB

A beginner's guide to building RESTful APIs using Spring boot and MongoDB

What is Spring boot?

According to the Spring boot documentation, Spring Boot is a web development framework that is based on the Spring framework that enables you to develop standalone, production-ready Spring-based apps. It has a strong opinion on the Spring platform and third-party libraries, so you can get started quickly. Spring setup isn't required in most Spring Boot applications.

Some of the objectives of this technology are as follows: • Make all Spring development radically faster and more generally accessible by providing a radically faster and more widely accessible getting-started experience. • Be opinionated right out of the gate, but move out of the way as requirements deviate from the defaults. • Include non-functional elements such as embedded servers, security, metrics, health checks, and externalized settings that are common to big groups of projects. • There is no need to generate code and no XML configuration is required.

So enough with the definitions. Let’s move on to the fun stuff.

In this article, I will show you how easy it is to build a RESTful API using spring boot. First, we need to bootstrap our application using spring initializer. So go to start.spring.io. To follow along with this, you need to understand the basics of java and spring boot. We will be using intellij Idea from jetbrains. You can also eclipse or Visual studio code. This is an article showing how to configure vs code for spring boot here. We will also use an http client. There are two popular options - Postman and insomnia

image.png

So let's walk through this website, this website is good for bootstrapping a bare-bones application that you can now build on.

  1. First is to choose to make our application a Maven project, you can choose either Maven or Gradle.
  2. Next, you make the project a Java project.
  3. Next is to choose the Spring boot version you want, any of the options is fine, so I will leave it at 2.6.1.
  4. Now, we choose our project metadata starting from the Group id, this group id is the url of your website starting from the domain, if your company is google.com, your group id can be com.google. My group id will be tech.mahbub.
  5. Next is the artifact and name which are basically the same thing. The artifact is the project name. You can name it anyhow you like, I am naming mine spring-boot-rest-api-with-mongodb.
  6. Next we have the description. I will describe our project as spring boot rest api with mongodb.
  7. Next we choose jar as the way we want to package our application when we are done.
  8. I will choose Java 17 as my Java version.
  9. We move to the right side where we will choose our dependencies for this project, so click on Add dependencies. Now choose the following:

image.png

  • Spring Web: used for building web including RESTful, applications using Spring MVC. It uses Apache Tomcat as the default embedded container.

  • Spring Data MongoDB Store data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time.

After choosing the dependencies, we can now click on the Generate button. This then downloads a zip file of the project. You can double-click it and extract it to a folder that you can now open in your IDE. We will be using the community edition of intellij IDEA which is a great IDE for developing Java applications. It is also free and you can download at jetbrains.com/idea/download.

image.png So this is our interface. We can explore our application metadata by opening the 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.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>tech.mahbub</groupId>
    <artifactId>spring-boot-rest-api-with-mongodb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-rest-api-with-mongodb</name>
    <description>spring boot rest api with mongodb</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>

So what are we going to be building? We will build a RESTful API for a school system to manage the subjects a student takes in school. So we will create two packages under the main package which in this case is tech.mahbub.springbootrestapiwithmongodb. So name the package subject and this will define how the subject class will look like. Now let's focus on what the subject will look like. We can now create a class called Subject and define it.

package tech.mahbub.brainsspringdatajpa.subject;

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

@Document(collection = "subject")
public class Subject {

    @Id
    private String id;
    private String name;
    private String description;

    public Subject() {
    }

    public Subject(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;
    }
}

As we see, we are defining this model with the id, name, and description of the subject. We then annotate the Id with @Id which tells us that it is the primary key of the whole model. We also annotate the whole Subject class with @Document since mongoDB stores things as documents which is unlike databases like mySQL that stores stuff in tables. We then create all args constructor and getters and setters.

application.properties

Now to setup our database, we will need to add our connection string to our project. I will be using the cloud instance of mongoDB as it is very easy to set up. Simply go to the mongoDB atlas website, create an account and get a cloud instance setup. You can learn more here. Now navigate to where the resources are and you will find the application.properties file.

image.png

Now paste in your connection string as seen below.

spring.data.mongodb.uri=mongodbConnectionString

So of course I won't share my personal connection string with you guys, lol, I'm trying to be secure here. However, if you go through the guide, you should be able to get your mongoDB atlas connection setup. If you don't, you can leave a comment below. You can also download the mongoDB community server and run the database on your system locally. Check it out here

SubjectRepository

Next, we create a class called SubjectRepository which will be an interface that extends the MongoRepository. The MongoRepository will bring in all the CRUD (Create, Read, Update and Delete, and many more) implementations of mongoDB into our project.

package tech.mahbub.brainsspringdatajpa.subject;

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

@Repository
public interface SubjectRepository extends MongoRepository<Subject, String> {


}

SubjectService

Next we create the SubjectService layer which implements the CRUD methods that we will use in this application.

package tech.mahbub.brainsspringdatajpa.subject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SubjectService {
    @Autowired
    private SubjectRepository subjectRepository;

    public List<Subject> getAllSubjects(){
        List<Subject> subjects = new ArrayList<>();
        subjectRepository.findAll()
                .forEach(subjects::add);
        return subjects;
    }
    public Subject getSubject(String id){

        return subjectRepository.findById(id).orElse(new Subject());
    }
    public void addSubject(Subject subject){

        subjectRepository.save(subject);
    }
    public void updateSubject(String id, Subject subject){
        subjectRepository.save(subject);
    }
    public void deleteSubject(String id){

        subjectRepository.deleteById(id);
    }

}

In this class, we have methods to get all the subjects in the database (getAllSubject), get a single subject (getSubject), add a new subject (addSubject), update a subject (updateSubject), and lastly delete a subject (deleteSubject).

SubjectController

Our subject controller will be used to interact with the SubjectService (the service is interacting with the database directly). We will use that to create the RESTful side of the API

package tech.mahbub.brainsspringdatajpa.subject;

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

import java.util.List;

@RestController
public class SubjectController {

    @Autowired
    private SubjectService subjectService;

    @RequestMapping("/subjects")
    public List<Subject> getAllSubjects(){
        return subjectService.getAllSubjects();
    }

    @RequestMapping("/subjects/{id}")
    public Subject getSubject(@PathVariable String id){
        return subjectService.getSubject(id);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/subjects")
    public void addSubject(@RequestBody Subject subject){
        subjectService.addSubject(subject);
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/subjects/{id}")
    public void updateSubject(@RequestBody Subject subject, @PathVariable String id){
        subjectService.updateSubject(id, subject);
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/subjects/{id}")
    public void deleteSubject(@PathVariable String id){
        subjectService.deleteSubject(id);
    }

}

Here we use the annotation @RequestMapping which simply is what will be in the url in the browser or http client that we will use i.e. localhost:8080/subjects for getting all the subjects in the database as well as for creating a new subject. We also have request mapping which includes a path variable which is the id for a particular subject. Now we are done with the Subject controller.

Finally... Let us run the application and test the endpoints using Postman. First, I will create a few records using POST.

POST request for subjects.PNG

So, now we have a few records in the database, we can now test the GET endpoints to get all the records and get a particular record.

GET request for all subjects.PNG

GET request for specific subject.PNG

Let's update one of the subjects in the database.

PUT request for a subject.PNG

Then lastly, let's delete one of the subjects in the database.

DELETE request for a subject.PNG

So, we are done with this API, I hope you understand to an extent how spring boot and how you can use it to create RESTful web services.

This has been my first article on Hashnode. I would like to read your comments.

Cheers.