Building RESTful Services with Spring Boot
Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He is studying at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).
Using Spring MVC to Create REST Endpoints:
Controller Class: Use
@RestControllerannotation to create a REST controller.Mapping Requests: Use
@GetMapping,@PostMapping,@PutMapping,@DeleteMappingfor respective HTTP methods.
Example: Simple CRUD Operations for a Product Entity
Create a
ProductEntity:java
package com.example.demo; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private double price; // Getters and setters }Create a
ProductRepository:java
package com.example.demo; import org.springframework.data.repository.CrudRepository; public interface ProductRepository extends CrudRepository<Product, Long> { }Create a
ProductController:java
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/products") public class ProductController { @Autowired private ProductRepository productRepository; @PostMapping public Product createProduct(@RequestBody Product product) { return productRepository.save(product); } @GetMapping("/{id}") public Product getProduct(@PathVariable Long id) { return productRepository.findById(id).orElse(null); } @PutMapping("/{id}") public Product updateProduct(@PathVariable Long id, @RequestBody Product productDetails) { Product product = productRepository.findById(id).orElse(null); if (product != null) { product.setName(productDetails.getName()); product.setPrice(productDetails.getPrice()); return productRepository.save(product); } return null; } @DeleteMapping("/{id}") public String deleteProduct(@PathVariable Long id) { productRepository.deleteById(id); return "Product deleted successfully!"; } }
Handling HTTP Requests and Responses:
Use
@RequestBodyto map the body of the request to a Java object.Use
@PathVariableto extract values from the URI.Use
@RequestParamfor query parameters.