Let's create a REST API using SpringBoot + MongoDB

What is this article?

This is a hands-on page for building a REST API using Spring Boot using MongoDB as a data store. Since it is a training rush, the goal is to easily summarize the procedures in sequence and copy them so that you can easily experience them.

The content itself is almost the following copy and paste. I wanted to use Gradle, so I changed the content a little. https://stackabuse.com/spring-data-mongodb-tutorial/

Premise

Implementation overview

Create a REST API using Spring Boot. Use MongoDB for datastore and CRUD MongoDB data on request

The finished product is listed on GitHub below, so please refer to it if it doesn't work. https://github.com/theMistletoe/MongoDB-SpringBoot-sample

Hands-on procedure

MongoDB setup

Sign up for MongoDB https://account.mongodb.com/account/register

After signing up, click "Build a Cluster"

image.png

I want to do it for free, so choose FREE

image.png

cluster settings. You don't have to change it.

image.png

The cluster construction will start.

image.png

After building the cluster, first create a user for Database access. image.png

Select password authentication and enter the user name and password to create a user. Remember this username and password as you will use them later.

image.png

User was created

image.png

Next, set up Network Access. You can define a whitelist using IP addresses, so let's set it to accept any IP address for practice. (Since security is loose for practice, please do not use it in production)

image.png

Click [ALLOW ACCESS FROM ANYWHERE] to confirm

image.png

Let's make a DB Click on Clusters COLLECTIONS

image.png

Click Add My Own Data

image.png

Enter "jobs" for the database name and "candidate" for the collection name to create

image.png

After creating the database, the console screen will be displayed. Later data updates will be reflected here.

image.png

This is the end of MongoDB setup.

Spring Boot environment construction

Go to Spring Initializr, set the template as shown in the image, and download the zip with Generate.

image.png

Unzip the zip and open it in IntelliJ. First, open application.properties and set MongoDB access information.


spring.data.mongodb.uri=mongodb+srv://user:<password>@cluster0.ayoho.mongodb.net/<dbname>?retryWrites=true&w=majority

You can get the settings for spring.data.mongodb.uri from the MongoDB console.

image.png

image.png

image.png

Use the password and dbname set during MongoDB setup. (If you follow the procedure, dbname will be "jobs")

Java program implementation

Now let's write Java. I can't explain the detailed implementation, so please try to write while solving any unclear points. You can place it anywhere, but please refer to the package information or refer to GitHub.

Candidate.java


package com.example.mongoDBsample.entity;

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

@Document(collection = "candidate")
public class Candidate {
    @Id
    private String id;

    private String name;

    private double exp;

    @Indexed(unique = true)
    private String email;

    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 double getExp() {
        return exp;
    }

    public void setExp(double exp) {
        this.exp = exp;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

CandidateRepository.java


package com.example.mongoDBsample.repository;

import com.example.mongoDBsample.entity.Candidate;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;
import java.util.Optional;

public interface CandidateRepository extends MongoRepository<Candidate, String> {
    Optional<Candidate> findByEmail(String email);

    List<Candidate> findByExpGreaterThanEqual(double exp);

    List<Candidate> findByExpBetween(double from, double to);
}

CandidateController.java


package com.example.mongoDBsample.controller;

import com.example.mongoDBsample.exception.ResourceNotFoundException;
import com.example.mongoDBsample.entity.Candidate;
import com.example.mongoDBsample.repository.CandidateRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/candidate")
public class CandidateController {

    @Autowired
    private CandidateRepository candidateRepository;

    @PostMapping
    @ResponseStatus(code = HttpStatus.CREATED)
    public Candidate add(@RequestBody Candidate candidate) {
        return candidateRepository.save(candidate);
    }

    @GetMapping
    public List<Candidate> getAll() {
        return candidateRepository.findAll();
    }

    @GetMapping(value = "/{id}")
    public Candidate getOne(@PathVariable String id) {
        return candidateRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException());
    }

    @PutMapping(value = "/{id}")
    public Candidate update(@PathVariable String id, @RequestBody Candidate updatedCandidate) {
        Candidate candidate = candidateRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException());
        candidate.setName(updatedCandidate.getName());
        candidate.setExp(updatedCandidate.getExp());
        candidate.setEmail(updatedCandidate.getEmail());
        return candidateRepository.save(candidate);
    }

    @DeleteMapping(value = "/{id}")
    @ResponseStatus(code = HttpStatus.ACCEPTED)
    public void delete(@PathVariable String id) {
        Candidate candidate = candidateRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException());
        candidateRepository.delete(candidate);
    }

    @GetMapping("/searchByEmail")
    public Candidate searchByEmail(@RequestParam(name = "email") String email) {
        return candidateRepository.findByEmail(email)
                .orElseThrow(() -> new ResourceNotFoundException());

    }

    @GetMapping("/searchByExp")
    public List<Candidate> searchByExp(@RequestParam(name = "expFrom") Double expFrom, @RequestParam(name = "expTo", required = false) Double expTo) {
        List<Candidate> result = new ArrayList<>();
        if (expTo != null) {
            result = candidateRepository.findByExpBetween(expFrom, expTo);
        } else {
            result = candidateRepository.findByExpGreaterThanEqual(expFrom);
        }
        return result;
    }
}

ResourceNotFoundException.java


package com.example.mongoDBsample.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException() {
    }
}

Confirmation of implementation

Now that the implementation is complete, let's check if data access is possible via the API.

Launch the app in IntelliJ

image.png

image.png

Or execute the following with CUI to start

./gradlew bootRun

Register user

First, let's register the user. If you send a POST request to http: // localhost: 8080 / candidate / with the following JSON object attached to the body, The registered user information will be returned in the response.

{
    "name": "Axel",
    "exp": "10",
    "email": "[email protected]"
}

image.png

If you look at the MongoDB console, you can see that the data has been added.

image.png

Browse users

If you send a GET request to http: // localhost: 8080 / candidate, all registered users will be returned.

image.png

Update user information

In a PUT request to http: // localhost: 8080 / candidate / {user id} If you attach the updated JSON object to the body, the registration information will be updated.

image.png

image.png

Delete user

By throwing a DELETE request to http: // localhost: 8080 / candidate / {user id} You can delete the user.

image.png

image.png


that's all.

I think you've created MongoDB / SpringBoot to implement the basics of a REST API backend that allows you to use your datastore. Let's extend this and create an application in cooperation with the front end!

Recommended Posts

Let's create a REST API using SpringBoot + MongoDB
Create a pseudo REST API server using GitHub Pages
Create a CRUD API using FastAPI
How to create a Rest Api in Django
Create a REST API using the model learned in Lobe and TensorFlow Serving.
Let's create a function for parametrized test using frame object
Create a real-time auto-reply bot using the Twitter Streaming API
Get Salesforce data using REST API
Create a python GUI using tkinter
Create a nested dictionary using defaultdict
Create API using hug with mod_wsgi
Create a C wrapper using Boost.Python
Create a TalkBot easily using Discord.py and A3RT's Talk API (pya3rt).
[Python] I wrote a REST API using AWS API Gateway and Lambda.
Try to create a Qiita article with REST API [Environmental preparation]
Create a REST API to operate dynamodb with the Django REST Framework
Let's create a virtual environment for Python
Let's create a free group with Python
Create a graph using the Sympy module
[Python] Create a Batch environment using AWS-CDK
Create an application using the Spotify API
Let's make a multilingual site using flask-babel
Create a dataframe from excel using pandas
FX data collection using OANDA REST API
Create a GIF file using Pillow in Python
Create a beauty pageant support app using PyLearn2
Create a phylogenetic tree from Biopyton using ClustalW2
Let's judge emotions using Emotion API in Python
Create a binary data parser using Kaitai Struct
Create a web map using Python and GDAL
Create a visitor notification system using Raspberry Pi
Create a Mac app using py2app and Python3! !!
Create a MIDI file in Python using pretty_midi
Let's make a module for Python using SWIG
Prepare a pseudo API server using GitHub Actions
Create a GUI on the terminal using curses
Create a data collection bot in Python using Selenium
Create a Todo app with Django REST Framework + Angular
Create a color sensor using a Raspberry Pi and a camera
FX data collection using OANDA REST API
Try drawing a social graph using Twitter API v2
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
[LINE Messaging API] Create a rich menu in Python
[Python] Create a ValueObject with a complete constructor using dataclasses
Let's create RDF using PubMed's dissertation information-Paper information acquisition-
Create a Todo app with the Django REST framework
Get LEAD data using Marketo's REST API in Python
Register a ticket with redmine API using python requests
I tried APN (remote notification) using Parse.com REST API
Create a tweet heatmap with the Google Maps API
Learning neural networks using Chainer-Creating a Web API server
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
Building a seq2seq model using keras' Functional API Inference
Create a company name extractor with python using JCLdic
Let's easily make a math gif using Google Colaboratory
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
A little bit from Python using the Jenkins API
Create a dictionary by searching the table using sqlalchemy
Build a lightweight Fast API development environment using Docker