Skip to main content

Command Palette

Search for a command to run...

Building RESTful Services with Spring Boot

Published
1 min read
M

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 @RestController annotation to create a REST controller.

  • Mapping Requests: Use @GetMapping, @PostMapping, @PutMapping, @DeleteMapping for respective HTTP methods.

Example: Simple CRUD Operations for a Product Entity

  1. Create a Product Entity:

    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
     }
    
  2. Create a ProductRepository:

    java

     package com.example.demo;
    
     import org.springframework.data.repository.CrudRepository;
    
     public interface ProductRepository extends CrudRepository<Product, Long> {
     }
    
  3. 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 @RequestBody to map the body of the request to a Java object.

  • Use @PathVariable to extract values from the URI.

  • Use @RequestParam for query parameters.