Building REST APIs with Spring MVC [Java Spring Boot Mastery Series – Part 3]
🎯 Objective
In this section, you will learn how to:
- Create RESTful APIs
- Handle requests and responses
- Use HTTP methods correctly
- Return proper HTTP status codes
🔧 Step 1: Create a Model Class
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Double price;
// Getters and Setters
}
🔍 Explanation
@Entity: Marks this class as a JPA entity.@Id: Primary key field.@GeneratedValue: Auto-generates ID.name,price: Fields mapped to database columns
📦 Step 2: Create a Repository
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
🔍 Explanation
- Extends
JpaRepository<Product, Long>to get built-in CRUD methods. - No need for implementation — Spring Data provides it at runtime.
🧠 Step 3: Create a Service Layer
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> getAll() {
return productRepository.findAll();
}
public Product getById(Long id) {
return productRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product not found: " + id));
}
public Product save(Product product) {
return productRepository.save(product);
}
public void delete(Long id) {
productRepository.deleteById(id);
}
}
🔍 Explanation
- Encapsulates business logic.
findAll(),save(),findById(),deleteById()are provided by Spring Data.- Custom
ResourceNotFoundExceptionhelps handle 404s.
🌐 Step 4: Create a REST Controller
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping
public List<Product> getAllProducts() {
return productService.getAll();
}
@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
return ResponseEntity.ok(productService.getById(id));
}
@PostMapping
public ResponseEntity<Product> createProduct(@RequestBody Product product) {
return new ResponseEntity<>(productService.save(product), HttpStatus.CREATED);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
productService.delete(id);
return ResponseEntity.noContent().build();
}
}
🔍 Explanation
@RestController: Marks the class for REST API responses.@RequestMapping("/api/products"): Base URL path for the controller.@GetMapping,@PostMapping,@DeleteMapping: Maps HTTP methods to controller actions.@PathVariable: Binds URL segment to method param.@RequestBody: Maps JSON to Java object.ResponseEntity: Builds a response with a status code.
🚫 Optional: Custom Exception Handling
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
🔍 Explanation
- Custom exception class to return HTTP 404 when data not found.
- Annotated with
@ResponseStatus(HttpStatus.NOT_FOUND).
📬 Test the API using Postman
- GET:
http://localhost:8080/api/products - GET by ID:
http://localhost:8080/api/products/1 - POST:
http://localhost:8080/api/products
{
"name": "Laptop",
"price": 55000.0
}
- DELETE:
http://localhost:8080/api/products/1
✅ You’ve now built a fully functional RESTful API with CRUD operations using Spring Boot MVC architecture!
➡️ Next Up: Part 4 – Data Validation and Exception Handling
