Introduction of Spring Boot and MongoDB Rest API

We’ll create a Spring Boot and MongoDB Rest API in this tutorial to handle employee data kept in a MongoDB database. Establishing a project, building data models, carrying out CRUD (Create, Read, Update, Delete) actions, and testing your API endpoints are among the skills you’ll acquire.

Required conditions:
-> JDK, or Java Development Kit, version 17 or higher
-> An IDE such as VS Code or IntelliJ IDEA
-> A fundamental knowledge of REST APIs, Spring Boot, and locally installed and operational MongoDB- ClickHere

1. Project Setup

  • Spring Initializr: Visit SpringInitiazr and create a project with these dependencies: Spring Web, Spring Data MongoDB, SpringBoot DevTools
  • IDE Import: Import the generated project into your IDE.

2. Define the Employee Model

Create Employee.java:

package com.example.tech.model;

//Spring Boot and MongoDB Rest API
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "employees")
public class Employee {
	@Id
	private String id;
	private String name;
	private String designation;

	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 getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

}

3. Create The Repository

Create EmployeeRepository.java

package com.example.tech.repository;

// Spring Boot and MongoDB Rest API
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.example.tech.model.Employee;

@Repository
public interface EmployeeRepository extends MongoRepository<Employee, String> {

}

4. Create the Service Layer

Create EmployeeService.java (Interface)

package com.example.tech.service;

// Spring Boot and MongoDB Rest API
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.example.tech.model.Employee;

@Service
public interface EmployeeService {

	public List<Employee> getAllEmployees();

	public Optional<Employee> getEmployeeById(String id);

	public Employee createEmployee(Employee employee);

	public Employee updateEmployee(String id, Employee employee);

	public void deleteEmployee(String id);

}

Create EmployeeServiceImpl.java (implementation)

package com.example.tech.service;

// Spring Boot and MongoDB Rest API
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.tech.model.Employee;
import com.example.tech.repository.EmployeeRepository;

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

@Service
public class EmployeeServiceImpl implements EmployeeService {
	
	@Autowired(required=true)
	private EmployeeRepository employeeRepository;

	public List<Employee> getAllEmployees() {
		return employeeRepository.findAll();
	}

	public Optional<Employee> getEmployeeById(String id) {
		return employeeRepository.findById(id);
	}

	public Employee createEmployee(Employee employee) {
		return employeeRepository.save(employee);
	}

	public Employee updateEmployee(String id, Employee employee) {
		if (employeeRepository.existsById(id)) {
			employee.setId(id);
			return employeeRepository.save(employee);
		}
		return null; 
	}

	public void deleteEmployee(String id) {
		employeeRepository.deleteById(id);
	}
}

5. Create The Rest Controller

Create EmployeeController.java

package com.example.tech.controller;

// Spring Boot and MongoDB Rest API
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.tech.model.Employee;
import com.example.tech.service.EmployeeService;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/employees")
public class EmployeeController {
	
	@Autowired(required = true)
	private EmployeeService employeeService;

	@GetMapping("/getAll")
	public List<Employee> getAllEmployees() {
		return employeeService.getAllEmployees();
	}

	@GetMapping("/{id}")
	public ResponseEntity<Employee> getEmployeeById(@PathVariable String id) {
		Optional<Employee> employee = employeeService.getEmployeeById(id);
		return employee.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
				.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
	}

	@PostMapping("/saveEmployee")
	public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee) {
		Employee createdEmployee = employeeService.createEmployee(employee);
		return new ResponseEntity<>(createdEmployee, HttpStatus.CREATED);
	}

	@PutMapping("/{id}")
    public ResponseEntity<Employee> updateEmployee(@PathVariable String id, @RequestBody Employee employee) {
        Employee updatedEmployee = employeeService.updateEmployee(id, employee);
        if (updatedEmployee != null) {
            return new ResponseEntity<>(updatedEmployee, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

	@DeleteMapping("/{id}")
	public ResponseEntity<Void> deleteEmployee(@PathVariable String id) {
		employeeService.deleteEmployee(id);
		return new ResponseEntity<>(HttpStatus.NO_CONTENT);
	}
}

6. Application Configuration

Create/Update Application.properties

// Spring Boot and MongoDB Rest API
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=employeeDatabase
server.port=9000

7.Start the Application

Run your Springboot Application from your IDEA.

Testing with Postman (or similar tool)
: Spring Boot and MongoDB Rest API URL’s

  • GET All Employees: GET http://localhost:9000/employees/getAll
  • GET Employee by ID: GET http://localhost:9000/employees/{id} (Replace {id} with an actual ID)
  • POST Create Employee: POST http://localhost:9000/employees/saveEmployee Content-Type: application/json
{
    "name": "Alice Johnson",
    "designation": "Software Engineer" 
}
  • PUT Update Employee (Similar to the above, with JSON in the body)
  • DELETE Employee DELETE http://localhost:9000/employees/{id}

Explore More Topics:

-> Master Spring Data JPA Custom Query Example: A Simple Guide
-> Spring Boot REST API CRUD Example With MySQL Database
-> Login Registration and Forgot Password Form in HTML CSS
-> Step-by-Step Guide: Setting up Jenkins on Amazon EC2 Instance with Ubuntu
-> Creating a Responsive Login and Signup Form in React.js

Share.

Leave A Reply

WhatsApp us

Exit mobile version