REST Full CRUD Operations
REST Full CRUD Operations
Step1:
Step2:
Package folder structure:
Step3:
package com.example.restapi;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestapiApplication {
Step4:
package com.example.restapi.model;
Step 5:
package com.example.restapi.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import com.example.restapi.model.Product;
import java.util.HashMap;
import java.util.Map;
import java.util.Collection;
@RestController
@RequestMapping("/products")
public class ProductServiceController {
private static Map<Integer, Product> productRepo = new
HashMap<>();
static {
Product honey = new Product();
honey.setId(1);
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
@DeleteMapping("/{id}")
public ResponseEntity<Object> delete(@PathVariable("id")
Integer id) {
if (!productRepo.containsKey(id)) {
return new ResponseEntity<>("Product not found",
HttpStatus.NOT_FOUND);
}
productRepo.remove(id);
return new ResponseEntity<>("Product is deleted
successfully", HttpStatus.OK);
}
@PutMapping("/{id}")
public ResponseEntity<Object>
updateProduct(@PathVariable("id") Integer id, @RequestBody
Product product) {
if (!productRepo.containsKey(id)) {
return new ResponseEntity<>("Product not found",
HttpStatus.NOT_FOUND);
}
product.setId(id); // Set the ID in the product
productRepo.put(id, product); // Update the product
return new ResponseEntity<>("Product is updated
successfully", HttpStatus.OK);
}
@PostMapping
public ResponseEntity<Object> createProduct(@RequestBody
Product product) {
if (productRepo.containsKey(product.getId())) {
return new ResponseEntity<>("Product with this ID
already exists", HttpStatus.CONFLICT);
}
productRepo.put(product.getId(), product);
return new ResponseEntity<>("Product is created
successfully", HttpStatus.CREATED);
}
@GetMapping
public ResponseEntity<Collection<Product>>
getAllProducts() {
return new ResponseEntity<>(productRepo.values(),
HttpStatus.OK);
}
}
Output:
`