#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
Validating Incoming Request Data with Spring Boot
More Relevant Posts
-
#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
-
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
To view or add a comment, sign in
-
-
#Post5 In the previous post, we saw how @RequestBody helps us handle request data. Now the next question is 👇 How do we get data from the URL? There are two common ways: • @PathVariable • @RequestParam Let’s understand 👇 👉 @PathVariable Used when the value is part of the URL path Example: GET /users/10 @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return "User id: " + id; } 👉 @RequestParam Used when the value comes as a query parameter Example: GET /users?id=10 @GetMapping("/users") public String getUser(@RequestParam int id) { return "User id: " + id; } 💡 Key difference: @PathVariable → part of URL @RequestParam → query parameter Key takeaway: Use the right approach based on how data is passed in the request 👍 In the next post, we will explore exception handling in Spring Boot 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
🚀 Day 15/100: Spring Boot From Zero to Production Topic: Default Logging in Spring Boot Logging is your application’s Black Box recorder. It captures every action, error, and heartbeat so you aren't flying blind when things break. The best part? In Spring Boot, it works like magic from the moment you hit "Run." The "Zero-Config" Starter You don't have to download a single library to get started. Every Spring Boot Starter (Web, Data, etc.) automatically pulls in spring-boot-starter-logging. By default, it uses Logback as the engine and SLF4J as the universal interface. > Set to INFO by default (it hides the "noisy" DEBUG/TRACE logs). > It automatically shows the Date, Time, Log Level, PID, Thread Name, and the actual Message. You can steer the "defaults" directly from your application.properties file: Change the Volume: logging.level.root=DEBUG to see everything. Save to Disk: logging.file.name=app.log to stop losing logs when the console closes. Target Packages: logging.level.org.hibernate=SQL to only watch specific internal actions. While the default is great for your local machine, it’s not enough for production. For big projects, we need file rotation, JSON formatting, and environment-specific rules. In the next post, we’ll look at how to take this to a Professional Grade using XML configuration. Stay tuned! #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend #Logging #Logback #SoftwareEngineering
To view or add a comment, sign in
-
-
💡 The file upload mistake that would've haunted me in production storing a full URL in your database is a trap. https://lnkd.in/getwKNqc — looks fine. works fine. until you switch storage providers and realize you now have 50,000 rows to update in production. Took me an embarrassing amount of time to figure out the right way: store only the key → users/abc123.jpg keep the base URL in your config combine them at runtime when building responses One env variable change. entire system migrated. database never stores a domain name again. That was just one of three things I got wrong building file uploads this week. The second one: skipping compression. a user uploads a 4MB phone photo, you store a 4MB phone photo. your storage bill is quiet now. it won't be later. compress before upload, not after. a 3MB image should leave your server under 150KB. The third: public storage buckets. if your file URL works forever with no auth, that's not a feature. generate signed URLs with expiry instead. 10 extra lines of code, one less thing to regret. File uploads feel like a solved problem until you actually build one properly. #Java #SpringBoot #BackendDev
To view or add a comment, sign in
-
-
Is your @Transactional annotation actually doing what you think? 🧐 In Spring Boot, data integrity is everything. But I often see a common trap: Self-invocation. If you call a transactional method from another method within the same class, the Spring Proxy is bypassed. 📉 The result? No transaction starts, and your data might end up inconsistent without any error message. Check: ✅ The Proxy Rule: Spring uses AOP proxies. External calls go through the proxy; internal calls don't. ✅ The Fix: Move the transactional logic to a separate Service or use AspectJ if complexity scales. ✅ Bonus: Always use readOnly = true for fetch operations to improve performance and avoid unnecessary flush calls. It’s not just about using the framework; it’s about understanding the "Magic" behind it. 🚀 Have you ever faced a "phantom" database bug because of this? Let's swap stories! 👇 hashtag #Java #SpringBoot #Backend #Database #CleanCode #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
-
Spring Boot in Real Projects — Day 19 We already know how APIs return data. But what happens when your application grows and starts handling hundreds or even thousands of tasks daily whether from a single user or many users? For example: User1 → 50 tasks User2 → 120 tasks User3 → 300 tasks It's simple to fetch data for user-1 and next user-2 with 120 tasks gets heavy to fetch and for the next user-3 its hard to fetch and the API response may gets slow, to solve this Pagination & Sorting come in What is Pagination? Pagination is the process of dividing data into smaller chunks (pages) and fetching only the required portion instead of loading everything at once. What is Sorting? Sorting allows us to order data based on a specific field like createdAt, title, etc. Flow Client → Controller → Pageable → Repository → Database (applies LIMIT, OFFSET, ORDER BY) → Returns Page → Response to Client #SpringBoot #Java #BackendDevelopment #Pagination #APIDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
Spent 25 minutes wondering why my Spring Boot API was returning empty response The controller looked fine @GetMapping("/users") public List<User> getUsers() { return userService.findAll(); } Service was returning data when I debugged But the API response was always empty The problem was the User class had no getters Jackson needs getters to serialize objects to JSON No getters means no fields in the response The fix was adding @Data from Lombok One annotation and everything worked Spring Boot returned the data but Jackson could not read the fields without getters Ever had a bug that made you question everything #Java #SpringBoot #Jackson #Debugging #BackendDevelopment
To view or add a comment, sign in
-
Most transaction bugs in Spring Boot are not SQL bugs—they’re transaction boundary bugs. Today’s focus is a deep dive into @Transactional: propagation, isolation, and rollback rules. If you only use the default settings everywhere, you may accidentally create hidden data inconsistencies or unexpected commits. Example: @Service public class PaymentService { @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public void processPayment(Order order) { paymentRepository.save(new Payment(order.getId(), order.getTotal())); inventoryService.reserve(order.getItems()); } } Key idea: REQUIRED joins an existing transaction or starts a new one, REQUIRES_NEW creates a separate one, and isolation controls visibility of concurrent changes. By default, rollback happens for unchecked exceptions, so checked exceptions often need explicit rollbackFor. Treat @Transactional as an architectural decision, not just an annotation. #Java #SpringBoot #BackendDevelopment
To view or add a comment, sign in
-
-
Most transaction bugs in Spring Boot are not SQL bugs—they’re transaction boundary bugs. Today’s focus is a deep dive into @Transactional: propagation, isolation, and rollback rules. If you only use the default settings everywhere, you may accidentally create hidden data inconsistencies or unexpected commits. Example: @Service public class PaymentService { @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public void processPayment(Order order) { paymentRepository.save(new Payment(order.getId(), order.getTotal())); inventoryService.reserve(order.getItems()); } } Key idea: REQUIRED joins an existing transaction or starts a new one, REQUIRES_NEW creates a separate one, and isolation controls visibility of concurrent changes. By default, rollback happens for unchecked exceptions, so checked exceptions often need explicit rollbackFor. Treat @Transactional as an architectural decision, not just an annotation. #Java #SpringBoot #BackendDevelopment
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