Building a Product REST Controller in Spring Boot

Admin, Student's Library
0
Spring REST Controller

Key Components: @RestController | @PostMapping | @RequestBody

In modern microservices architecture, creating well-structured REST endpoints is fundamental. Spring Boot's @RestController annotation simplifies this process by combining @Controller and @ResponseBody. This guide walks through creating a product creation endpoint that accepts JSON payloads and prepares for database persistence and event publishing.

Creating the Product Controller

ProductController.java
package com.example.productservice.rest;

import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;

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

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void createProduct(@RequestBody CreateProductRequestModel requestModel) {
        // Product creation logic will be added here
    }
}
Annotation Purpose Example
@RestController Marks class as request handler Combines @Controller + @ResponseBody
@RequestMapping Base path for all endpoints /products

Request Model Class

CreateProductRequestModel.java
package com.example.productservice.rest;

import java.math.BigDecimal;

public class CreateProductRequestModel {
    private String title;
    private BigDecimal price;
    private Integer quantity;

    // Getters and Setters
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }
}

JSON Binding: Spring automatically converts incoming JSON to Java objects when properly annotated with @RequestBody. Field names must match JSON property names.

Complete Endpoint Implementation

Enhanced ProductController.java
package com.example.productservice.rest;

import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

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

    @PostMapping
    public ResponseEntity<String> createProduct(
            @RequestBody CreateProductRequestModel requestModel) {
        
        // 1. Validate input
        if (requestModel.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            return ResponseEntity.badRequest().body("Price must be positive");
        }

        // 2. Process product creation (will be implemented in service layer)
        // productService.createProduct(requestModel);
        
        // 3. Return success response
        return ResponseEntity.status(HttpStatus.CREATED)
               .body("Product created successfully");
    }
}

Important: Always validate incoming request data before processing. Never trust client input directly.

Sample JSON Request

Example POST Request
POST /products HTTP/1.1
Host: localhost:8080
Content-Type: application/json

{
    "title": "Premium Wireless Headphones",
    "price": 199.99,
    "quantity": 50
}

Implementation Steps

  1. Create new Java class in rest package
  2. Annotate with @RestController and @RequestMapping
  3. Define POST endpoint with @PostMapping
  4. Create request model class with matching JSON fields
  5. Add input validation and proper error handling

Next Steps: Learn about service layer implementation | Complete code samples available

Frequently Asked Questions

Q1. Why use @RestController instead of @Controller?
A: @RestController automatically adds @ResponseBody to all methods, making it perfect for APIs that return JSON/XML instead of views.

Q2. How to handle different response formats (JSON/XML)?
A: Spring Boot automatically handles content negotiation. Just ensure you have the right HttpMessageConverter implementations (like Jackson for JSON).

Q3. What's the best practice for request validation?
A: Use Bean Validation annotations (@NotNull, @Min, etc.) on your request model combined with @Valid annotation on the method parameter.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !