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

Fixing 'java RMI - ConnectException: Operation timed out' in WSO2 Enterprise Integrator 6.4

If you ever come across the below exception when running WSO2 Enterprise Integrator 6.4, here is the fix. This error occurs when you have multiple IP addresses from different networks configured in your etc/hosts as below. 10.xxx.x.xxx localhost 192.xxx.x.xxx localhost So simply, removing the unnecessary one and leaving the one of the network that you are currently connected to should resolve this issue. 10.xxx.x.xxx localhost

Student Information System - Java (SLIIT - ST2 PROJECT)

Student Information System (Github Project) This system is developed in Java and mySQL as a group project by me and 3 other members during a period of 1 month. The system allows the administrator to,  enroll students to the system  update enroll information  add/update course and degree program details  generate reports  create exams and edit relevant information  calculate gpa of the relevant exam  assign lecturers to courses  add lecturers/update details Lecturers to,  assign course grades  view their feedback  generate reports  view student / course / degree program details Students to,  view their profile  view their grading information  give feedback to lecturers   view lecturer / course / degree program details and other features. Below are some interfaces of the project. (Splash Screen) (Login) (Admin View) (Student Re...

SIMPLE BLACKJACK GAME IN JAVA (CONSOLE)

import java.util.Scanner; class BlackJack{     public static void main(String[] args)      {         int player_random1 = 100;         int player_random2 = 100;         while(player_random1 >= 12 || player_random2 >= 12  || player_random1 < 3 || player_random2 <3)         {             player_random1 = (int)(Math.random()*100);             player_random2 = (int)(Math.random()*100);         }                  int player_total = player_random1 + player_random2;                  System.out.println("You get a "+player_random1+" and a "+player_random2);         System.out.println("Your total is "+player_total); if(player_total==21)  ...