Skip to main content

A noob Introduction to creating a REST API using Spring Boot and MongoDB

Intro

This post is a beginner's guide to getting started with creating a simple REST API within seconds using Spring Boot and MongoDB.

Contains all basic CRUD operations.

Few confusions I faced as a beginner was when packaging was done and Spring Boot could locate several components.

So this blog post will follow the standard packaging alongside the implementation.

For further understanding of the annotations to be used, [1] and [2] can be referenced

Prerequisites 

  • Maven
  • MongoDB setup

Code

Step 1 : Initiate maven directory structure

|__src
         |__main
                     |__java
                                |__com.example.project
                     |__resources
        |__test

Initiate the pom.xml as below. Here, the mongoDB dependency is added as well.


<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example.project</groupId>
    <artifactId>movie-reservation</artifactId>
    <version>1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.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>

    <properties>
        <java.version>1.8</java.version>
    </properties>


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

Step 2 : Initiating Spring Boot Application


|__src
         |__main
                     |__java
                                |__com.example.project
                                                                     |__Application.java


Application.java


package com.example.project;

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

@SpringBootApplication
public class Application implements CommandLineRunner{

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

    @Override
    public void run(String... strings) throws Exception {
    }
}

Step 3 : Implementing the Model


Next, we have to implement the model which will represent the entity in the database.


|__src
         |__main
                     |__java
                                |__com.example.project
                                                                     |__models
                                                                                     |__Movie.java
                                                                     |__Application.java

Movie.java
package com.example.project.models;

import org.springframework.data.annotation.Id;
import java.io.Serializable;

public class Movie implements Serializable{

    @Id
    public String id;

    public String name;
    public int releasedYear;

    public Movie() {}

    public Movie(String name, int releasedYear) {
        this.name = name;
        this.releasedYear = releasedYear;
    }

    @Override
    public String toString() {
        return "Movie{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", releasedYear=" + releasedYear +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Movie movie = (Movie) o;

        if (releasedYear != movie.releasedYear) return false;
        if (id != null ? !id.equals(movie.id) : movie.id != null) return false;
        return name != null ? name.equals(movie.name) : movie.name == null;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + releasedYear;
        return result;
    }
}

Step 5: Implementing a repository

Next, we should implement a repository which will handle the database.

|__src
         |__main
                     |__java

                                |__com.example.project
                                                                     |__models
                                                                                     |__Movie.java
                                                                     |__repositories
                                                                                     |__MovieRepository.java
                                                                     |__Application.java

MovieRepository.java



package com.example.project.repositories;

import com.example.project.models.Movie;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface MovieRepository extends MongoRepository<Movie,String>{

}

We do not have explicitly implement the basic operations to the DB. They are already defined in MongoRepository. And they will be inherited to MovieRepository here.

Step 6: Implementing a service

We will now implement a service that handle the manipulations done to this model.


|__src
         |__main
                     |__java
                                |__com.example.project
                                                                     |__models
                                                                                     |__Movie.java
                                                                     |__repositories
                                                                                     |__MovieRepository.java
                                                                     |__services
                                                                                     |__MovieService.java
                                                                                     |__MovieServiceImpl.java
                                                                     |__Application.java

MovieService.java

package com.example.project.services;

import com.example.project.Movie;

import java.util.List;

public interface MovieService {

    List<Movie> getAllMovies();
    Movie getMovieById(String id);
    Movie addMovie(Movie movie);
    Movie updateMovie(Movie movie);
    void deleteMovie(String id);
}

MovieServiceImpl.java

package com.example.project.services;

import com.example.project.models.Movie;
import com.example.project.repositories.MovieRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MovieServiceImpl implements MovieService {

    @Autowired
    private MovieRepository movieRepository;

    public List<Movie> getAllMovies(){
        return movieRepository.findAll();
    }

    @Override
    public Movie getMovieById(String id) {
        return movieRepository.findOne(id);
    }

    @Override
    public Movie addMovie(Movie movie) {
        return movieRepository.save(movie);
    }

    @Override
    public Movie updateMovie(Movie movie) {
        return movieRepository.save(movie);
    }

    @Override
    public void deleteMovie(String id) {
        movieRepository.delete(id);
    }


}

Step 7: Implementing the controller

|__src
         |__main
                     |__java
                                |__com.example.project
                                                                     |__controllers
                                                                                     |__MovieController.java
                                                                     |__models
                                                                                     |__Movie.java
                                                                     |__repositories
                                                                                     |__MovieRepository.java
                                                                     |__services
                                                                                     |__MovieService.java
                                                                                     |__MovieServiceImpl.java
                                                                     |__Application.java

MovieController.java

package com.example.package.controllers;

import com.example.package.models.Movie;
import com.example.package.services.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class MovieController {

    @Autowired
    private MovieService movieService;

    @ResponseBody
    @RequestMapping(value = "/movies", method = RequestMethod.GET)
    public List<Movie> getAllMovies() {
        return movieService.getAllMovies();
    }

    @ResponseBody
    @RequestMapping(value = "/movies/{id}", method = RequestMethod.GET)
    public Movie getMovieByName(@PathVariable String id) {
        return movieService.getMovieById(id);
    }

    @ResponseBody
    @RequestMapping(value = "/movies", method = RequestMethod.POST)
    public Movie addMovie(@RequestBody Movie movie) {
        return movieService.addMovie(movie);
    }

    @ResponseBody
    @RequestMapping(value = "/movies", method = RequestMethod.PUT)
    public Movie updateMovie(@RequestBody Movie movie) {
        return movieService.updateMovie(movie);
    }

    @ResponseBody
    @RequestMapping(value = "/movies/{id}", method = RequestMethod.DELETE)
    public String deleteMovie(@PathVariable String id) {
        movieService.deleteMovie(id);
        return "Deleted";
    }
}

When @RequestBody is used, the JSON request body will automatically be mapped to a object specified. In this case, it is Movie. For this, the model class must have a default constructor. Else, you will get an error.

By using @ResponseBody, the response will be automatically parsed to JSON.

@PathVariable is used to retrieve URL parameters.


Few Requests and Responses





References

Comments

Popular posts from this blog

Admin panel of a Q & A Forum

In a Q & A Forum, when a user posts a question, it should be sent to the administrator for approval in case it contains inappropriate content. After approval it should be removed from this pending approval page and other users should be able to see the question afterwards. To enable this, we should maintain an approval column in our database table of records and for each record approval should be set to false by default. In the Pending approvals page only the records with approval=false should be displayed. Below is  the MySQL  statement for retrieval, $sql="SELECT * FROM topics WHERE approval=false"; To know which post was approved we should embed the post_id to the URL. And the relevant post should be updated as approval=true. Below is the complete code. <?php $sql="SELECT * FROM topics WHERE approval=false"; $query=mysqli_query($conn,$sql); echo '<form name="approve" method="p...

Getting Started with OAuth 2.0 using WSO2 Identity Server 5.3.0 and Playground2 Sample

This blog post provides step by step instructions for trying out OAuth 2.0 using WSO2 Identity Server . Here I use Identity Server 5.3.0 which is the latest released version by the time of this writing. The official documentation for this is available in https://docs.wso2.com/display/IS530/OAuth+2.0+with+WSO2+Playground , however for a beginner, it does not provide all the instructions such as creating a Service Provider with necessary configuration. However, by following the steps below, you can simply setup Identity Server and the playground2 sample webapp and test the entire OAuth 2.0 flow. Creating the Service Provider First step is to create a service provider in Identity Server. This is required because when a client application talks to Identity Server via OAuth 2.0, Identity Server has to identify the client and the incoming traffic. We set this configuration inside the service provider. Login to the Management Console of Identity Server and create a service provi...

Interacting with an Ethereum Smart Contract using Meteor and Ethereum

This blog post contains steps on how to interact with a specific contract on the blockchain extending the application created in the previous blog post [1]. Step 1: Add  frozeman:template-var This is used since we use callback very often. This wrapper can be found at [2]. Give the following command in order to add it to our application. meteor add frozeman:template-var Step 2: Adding the balance to be viewed inside the template Alter your code as below. main.js main.html When you refresh the browser, you should get the below output without having to click the button. Step 3: Writing the Smart Contract in Solidity Solidity is the language that ethereum uses to write smart contracts. In order to write the smart contract for our application we will use the online Solidity compiler which can be found at [3]. Step 4: Deploying the Smart Contract Log in to the MetaMask and make sure you are on the testnet. Select 'Create' in the right side p...