Type Here to Get Search Results !

How to develop REST CRUD API using Spring Boot?

How to develop REST CRUD API using Spring Boot?

Introduction

Spring Boot CRUD API

How to develop REST CRUD API using Spring Boot?

Introduction

Spring Boot has emerged as one of the most popular frameworks for building Java-based web applications. It simplifies the process of creating stand-alone, production-grade Spring applications with minimal configuration. One of the most common use cases for Spring Boot is building RESTful APIs. In this blog, we’ll walk through the process of creating a REST API with CRUD (Create, Read, Update, Delete) operations in Spring Boot.

What is REST?

REST (Representational State Transfer) is an architectural style that uses standard HTTP methods to interact with resources. It is widely used for building scalable web services. In a REST API, resources are represented as URIs, and operations are performed using HTTP methods like GET, POST, PUT, and DELETE.

Prerequisites

Before diving into the tutorial, ensure you have the following:

  • Basic knowledge of Java and Spring Framework.
  • Java Development Kit (JDK) installed.
  • Maven installed for managing dependencies.
  • An Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse.
Spring Boot

Setting Up the Spring Boot Project

We’ll start by setting up a new Spring Boot project.

Step 1: Create a New Spring Boot Project

You can create a new Spring Boot project using Spring Initializr (https://start.spring.io/):

  • Project: Maven
  • Language: Java
  • Spring Boot Version: 3.0.0 or later
  • Group: com.example
  • Artifact: crud-demo
  • Dependencies: Spring Web, Spring Data JPA, H2 Database (for in-memory database)

Click “Generate” to download the project, then extract and open it in your IDE.

Step 2: Define the Model

Let’s create a simple Product entity that will represent our data model.

package com.example.cruddemo.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;
private double price;

// Getters and Setters
}

Step 3: Create the Repository

Next, create a repository interface that will handle the data access logic. Spring Data JPA provides an interface called JpaRepository that comes with methods for CRUD operations.

package com.example.cruddemo.repository;

import com.example.cruddemo.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
}

Step 4: Create the Service Layer

The service layer contains the business logic of the application. We’ll create a ProductService to handle CRUD operations.

package com.example.cruddemo.service;

import com.example.cruddemo.model.Product;
import com.example.cruddemo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class ProductService {

@Autowired
private ProductRepository productRepository;

public List<Product> getAllProducts() {
return productRepository.findAll();
}

public Optional<Product> getProductById(Long id) {
return productRepository.findById(id);
}

public Product createProduct(Product product) {
return productRepository.save(product);
}

public Product updateProduct(Long id, Product productDetails) {
Product product = productRepository.findById(id).orElseThrow(() -> new RuntimeException("Product not found"));
product.setName(productDetails.getName());
product.setPrice(productDetails.getPrice());
return productRepository.save(product);
}

public void deleteProduct(Long id) {
Product product = productRepository.findById(id).orElseThrow(() -> new RuntimeException("Product not found"));
productRepository.delete(product);
}
}

Step 5: Create the REST Controller

Now, we’ll create a ProductController that will handle HTTP requests and map them to the appropriate service methods.

package com.example.cruddemo.controller;

import com.example.cruddemo.model.Product;
import com.example.cruddemo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

@Autowired
private ProductService productService;

@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}

@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
return productService.getProductById(id)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}

@PostMapping
public Product createProduct(@RequestBody Product product) {
return productService.createProduct(product);
}

@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product productDetails) {
return ResponseEntity.ok(productService.updateProduct(id, productDetails));
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
return ResponseEntity.noContent().build();
}
}

Testing the API

With everything set up, we can now test our CRUD API using Postman or curl.

  1. GET /api/products: Fetch all products.
  2. GET /api/products/{id}: Fetch a single product by ID.
  3. POST /api/products: Create a new product.
  4. PUT /api/products/{id}: Update an existing product.
  5. DELETE /api/products/{id}: Delete a product.

Example Requests

  1. Create a Product:
curl -X POST http://localhost:8080/api/products \
-H "Content-Type: application/json
" \
-d '{"
name": "Laptop", "price": 999.99}'

Get All Products:

curl http://localhost:8080/api/products

Get a Product by ID:

curl http://localhost:8080/api/products/1

Update a Product:

curl -X PUT http://localhost:8080/api/products/1 \
-H "Content-Type: application/json" \
-d '{"name": "Gaming Laptop", "price": 1299.99}'

Delete a Product:

curl -X DELETE http://localhost:8080/api/products/1

Conclusion

In this blog, we’ve built a simple REST API with CRUD operations using Spring Boot. We covered setting up a Spring Boot project, defining a data model, creating a repository, service, and controller, and finally, testing our API. Spring Boot’s simplicity and powerful features make it an excellent choice for building RESTful web services.

This basic example can be extended with more advanced features like validation, exception handling, and security as you continue to develop your Spring Boot applications.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad