Skip to primary content
Java Technical Tutorial

How to Build a RESTful API in Spring Boot 3: Best Practices & Validation

Step-by-step tutorial for Spring Boot 3 REST API development: @RestController, @PostMapping, @Valid, DTO patterns, ProblemDetails, and HttpStatus.

Java
package com.programmingwala.demo;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;

@RestController
@RequestMapping("/api/v1/inquiries")
public class InquiryController {

    public record InquiryDTO(
        @NotBlank(message = "Name cannot be empty") String name,
        @Pattern(regexp = "^\\d{10}$", message = "Phone must be 10 digits") String phone
    ) {}

    @PostMapping
    public ResponseEntity<String> submitInquiry(@Valid @RequestBody InquiryDTO dto) {
        // Service processing logic here...
        return ResponseEntity.status(HttpStatus.CREATED).body("Inquiry logged for: " + dto.name());
    }
}

1. REST Controller Architecture

Spring Boot simplifies REST API creation with annotations like @RestController, which combines @Controller and @ResponseBody. Each method serializes return values directly into JSON using the Jackson library.

2. Separation of Concerns with DTOs

Never expose database entity models directly over HTTP APIs. Use Record classes or Data Transfer Objects (DTOs) with Jakarta Validation annotations to enforce input boundaries before business logic executes.

Key Engineering Takeaways
  • Always validate incoming HTTP payloads with Jakarta Validation annotations.
  • Use proper HTTP response status codes: 201 Created, 200 OK, 400 Bad Request, 404 Not Found.
  • Centralize error handling with @ControllerAdvice and RFC 7807 ProblemDetails.

Frequently Asked Questions

Why use Records for DTOs in modern Java?
Records offer immutable, concise data carriers with auto-generated constructors, getters, equals, and hashCode.
Master This in Our Ghaziabad Coding Labs

Gain deep mastery over these concepts with direct instructor guidance, code reviews, and mock interviews at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.

Explore Related Course Call 7503962162
Physical Training Center

Visit Our Ghaziabad Training Center

Join classroom batches, attend interactive lab sessions, code with mentors, and take advantage of our high-speed dev workstations.

Campus Address:
C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad, Ghaziabad, Uttar Pradesh
Direct Counseling Helpline:
Call 7503962162
Get Google Maps Directions Call Now: 7503962162 Explore Ghaziabad Training Hub
Call 7503962162 Get Course Details