When updating data in a Spring Boot API, standard validation can be too restrictive, often requiring all fields to be sent even for minor changes. A more flexible solution is to use @Validated with validation groups. This approach allows you to define separate sets of rules. For example, you can have a "create" group that requires all fields to be present, and a "default" group that only checks the format of fields that are actually provided in the request. In your controller, you then apply the appropriate rule set: the strict rules for creating new items and the flexible rules for updating them. This allows your API to handle both full and partial updates cleanly while reusing the same data object, resulting in more efficient code. #SpringBoot #Java #API #Validation #SoftwareDevelopment
Flexible Validation in Spring Boot API with @Validated
More Relevant Posts
-
🚀 Spring Boot — Why I stopped using Entity in request body Earlier, I used to accept Entity directly in my APIs: @PostMapping("/users") public User createUser(@RequestBody User user) { return userService.save(user); } It worked… but later I realized the problem. ⸻ Issues I faced: ✔ Unnecessary fields coming from request ✔ Hard to control what client sends ✔ Tight coupling with DB structure What I do now: Use DTO instead: @PostMapping("/users") public User createUser(@RequestBody UserDto dto) { return userService.create(dto); } ✔ Only required fields ✔ Better validation ✔ Cleaner API contract ⸻ ⭐ Simple rule: 👉 Entity → database 👉 DTO → request/response Small change, but made APIs much safer. Do you accept Entity or DTO in your request body? #SpringBoot #JavaDeveloper #BackendDevelopment #LearningInPublic #Java
To view or add a comment, sign in
-
-
@Service in Spring Boot @Service is used to define the business logic layer in a Spring Boot application. It tells Spring: “This class contains the core logic of the application.” Key idea: • Processes data • Applies business rules • Connects Controller and Repository Works closely with: • @Repository → Fetches data • @RestController → Handles requests In simple terms: @Service → Handles Logic Understanding @Service helps you keep your application clean, organized, and maintainable. #SpringBoot #Java #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
One thing I’ve learned building backend systems: Audit logging always starts as a “simple requirement” …and ends up being a complex subsystem. - Who changed what? - When did it happen? - Can we query it efficiently? Most teams either: 1. Over-engineer it 2. Or build something they regret later So I decided to build it properly once. Introducing nerv-audit (now on Maven Central): A Spring Boot audit framework powered by Hibernate Envers, with: - Clean architecture - Queryable audit history - Production-ready design If you're building serious systems, this is something you’ll eventually need. Full write-up here: https://lnkd.in/g2sv9dsM Curious how others are handling audit trails in their systems 👇 #SpringBoot #Java #SoftwareEngineering #Backend #OpenSource
To view or add a comment, sign in
-
How Spring Boot Handles Requests Internally (Deep Dive) Ever wondered what happens when you hit an API in Spring Boot? 🤔 Here’s the real flow 👇 🔹 DispatcherServlet Acts as the front controller receives all incoming requests 🔹 Handler Mapping Maps the request to the correct controller method 🔹 Controller Layer Handles request & sends response 🔹 Service Layer Contains business logic 🔹 Repository Layer Interacts with database using JPA/Hibernate 🔹 Response Handling Spring converts response into JSON using Jackson 🔹 Exception Handling Handled globally using @ControllerAdvice 💡 Understanding this flow helped me debug issues faster and design better APIs. #Java #SpringBoot #BackendDeveloper #Microservices #RESTAPI #FullStackDeveloper #LearningInPublic
To view or add a comment, sign in
-
-
dmx-fun 0.0.14 Released! Version 0.0.14 is the ecosystem release. Where previous milestones built out the core type system, this one connects dmx-fun to the frameworks and infrastructure that production Java applications actually run on: Spring, Spring Boot, Micrometer, and Resilience4J. Five new production modules ship alongside new core types, collector façades, and a full Spring Boot reference application. Here is everything that changed: https://lnkd.in/ecRis2JM
To view or add a comment, sign in
-
#Post6 In the previous posts, we built basic REST APIs step by step. But what happens when something goes wrong? 🤔 Example: User not found Invalid input Server error 👉 By default, Spring Boot returns a generic error response. But in real applications, we need proper and meaningful error handling. That’s where Exception Handling comes in 🔥 Instead of handling exceptions in every method, Spring provides a better approach using @ControllerAdvice 👉 It allows us to handle exceptions globally Example: @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public String handleException(Exception ex) { return ex.getMessage(); } } 💡 Why use this? • Centralized error handling • Cleaner controller code • Better API response Key takeaway: Use global exception handling to manage errors in a clean and scalable way 🚀 In the next post, we will create custom exceptions for better control 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
Last weekend I’ve been studying more about error handling and I watched a great video from Dan Vega — an interesting view on how to implement error handling and retries. 🚀 I pushed a small demo repo that captures those ideas using Spring Boot’s new RestClient and a clean error-handling pattern: 🔁 Retry transient failures with @Retryable (exponential backoff). 🧭 Centralize response-to-exception mapping via RestClient’s defaultStatusHandler (ApiException, NotFoundException). 🛡️ Serve consistent ProblemDetail (RFC 7807) responses from a GlobalExceptionHandler for clearer API errors. 🧪 Uses https://httpbin.org/ to simulate status codes and unstable endpoints for deterministic testing. Why this is valuable: - Increases reliability by handling transient errors consistently. - Keeps controllers and business logic clean — the client layer interprets remote errors. - Improves client experience with predictable, machine-readable error payloads. Inspired by Dan Vega’s walkthroughs — credit to him for the patterns and clarity. 🙏 Feel curious how that I did it, check the repo to see the config, examples, and how to adapt this pattern: https://lnkd.in/dEe3HNKr #SpringBoot #Java #Resilience #ErrorHandling #RestClient #Microservices
To view or add a comment, sign in
-
#Post7 In the previous post, we saw how to handle exceptions globally using @ControllerAdvice. Now let’s take it one step further 👇 How do we handle specific errors properly? That’s where Custom Exceptions come in 🔥 Instead of using generic exceptions, we can create our own exception based on the use case. Example: public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } } 👉 Now we can throw this exception when user is not found Example usage: if(user == null){ throw new UserNotFoundException("User not found"); } 💡 Why use Custom Exceptions? • Better error clarity • Easy debugging • More control over API responses Key takeaway: Use custom exceptions to make your API errors more meaningful and structured 👍 In the next post, we will understand validation using @Valid 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
🧬 Spring Boot – Understanding API Responses Today I explored how Spring Boot sends data from backend to frontend. 🧠 Key Learnings: ✔️ Returning a Java object automatically converts it to JSON ✔️ Spring Boot uses Jackson internally for this conversion ✔️ "@ResponseBody" ensures data is sent directly as response 💡 Best Practice: 👉 Using "@RestController" simplifies everything (Combination of @Controller + @ResponseBody) ✔️ Explored different return types: • Object • List • String • ResponseEntity (for better control over status & response) 🔁 API Flow: Request → Controller → Service → Return Object → JSON Response → Client 💻DSA Practice: • Even/Odd check using modulus • Sum of first N numbers (optimized using formula) ✨ Understanding how backend responses work is key to building real-world REST APIs. #SpringBoot #Java #BackendDevelopment #RESTAPI #WebDevelopment #DSA #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
#Post8 In the previous post, we learned how to create custom exceptions. Now the next question is 👇 How do we validate incoming request data? That’s where validation comes in 🔥 In Spring Boot, we use @Valid along with validation annotations. Example 👇 public class User { @NotNull private String name; @Min(18) private int age; } Controller: @PostMapping("/user") public User addUser(@Valid @RequestBody User user) { return user; } 👉 If invalid data is sent, Spring automatically triggers validation errors 💡 Common validation annotations: • @NotNull • @NotEmpty • @Size • @Min / @Max 💡 Why use validation? • Prevent invalid data • Improve API reliability • Reduce manual checks Key takeaway: Always validate incoming data to build robust APIs 🚀 In the next post, we will handle these validation errors globally 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development