Skip to main content

🌱 Spring Boot Interview Series – Q10 : REST API Development Part 2 πŸš€

🌐 Spring Boot REST API Development – Part 2 πŸš€

Continuing our deep dive into REST APIs, this part covers validation, CORS, file uploads/downloads, exception handling, and API versioning — everything you need to impress in interviews and real-world projects! πŸ’‘


54. Difference between @ExceptionHandler and @ControllerAdvice ⚡

@ExceptionHandler is like a local guardian — it only catches exceptions for the controller where it’s declared. @ControllerAdvice, on the other hand, is a global superhero — it can intercept exceptions across multiple controllers. This distinction is critical: using @ExceptionHandler alone can lead to duplicated code if you have 20 controllers, whereas @ControllerAdvice centralizes it.

@RestController

public class UserController {

    @ExceptionHandler(ResourceNotFoundException.class)

    public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex){

        return new ResponseEntity<>("User not found!", HttpStatus.NOT_FOUND);

    }

}

Unknown Fact: @ControllerAdvice can target only specific packages, annotations, or controllers — useful for modular applications! 🎯

Common Mistake: Relying solely on @ExceptionHandler across many controllers creates scattered, inconsistent exception handling. πŸ˜…


55. How to validate REST request bodies πŸ“

Spring Boot integrates **JSR-303 Bean Validation** with annotations like @NotNull, @Size, and @Email. Use @Valid or @Validated on method parameters to trigger automatic validation. This prevents invalid data from entering your service layer — a real production safeguard. πŸ”’

@PostMapping("/users")

public ResponseEntity<User> createUser(@Valid @RequestBody User user){

    return ResponseEntity.ok(user);

}

Unknown Fact: You can create **custom validators** implementing ConstraintValidator for complex business rules, like validating age ranges based on user type. 🧩

Common Mistake: Forgetting @Valid results in controllers silently accepting invalid input — a common source of production bugs. 🚨


56. Difference between @Valid and @Validated ⚡

@Valid is a standard JSR-303 annotation that triggers validation on a single object. @Validated is Spring-specific and supports **validation groups**, allowing you to validate fields differently for creation vs. update operations. This subtle distinction can impress interviewers because it demonstrates **practical understanding of advanced validation scenarios**. πŸ•΅️‍♂️

@Validated(User.Create.class)

@PostMapping("/users")

public ResponseEntity<User> createUser(@RequestBody User user){ ... }

@Validated(User.Update.class)

@PutMapping("/users/{id}")

public ResponseEntity<User> updateUser(@RequestBody User user){ ... }

Unknown Fact: You can combine multiple validation groups in a single request, giving full control over complex entity validations in large enterprise systems. 🏒


57. How to enable CORS for a specific endpoint 🌍

Cross-Origin Resource Sharing (CORS) is a **common frontend-backend pain point**. Use @CrossOrigin to allow specific origins, headers, or methods. For global settings, implement WebMvcConfigurer. Knowledge of CORS shows **security awareness** and practical understanding of client-server interactions. πŸ”’

@CrossOrigin(origins = "http://example.com")

@GetMapping("/users")

public List<User> getUsers(){ ... }

Unknown Fact: Misconfigured CORS is one of the top reasons front-end devs report “API not working” — knowing this in interviews shows real-world insight. πŸ˜…


58. How to handle file uploads in Spring Boot πŸ“€

Handle uploads with @RequestParam("file") MultipartFile file. Spring Boot auto-configures multipart handling, but you can also use CommonsMultipartResolver. Validating file type and size is crucial to prevent security issues. πŸ›‘️

@PostMapping("/upload")

public String uploadFile(@RequestParam("file") MultipartFile file) {

    String filename = file.getOriginalFilename();

    file.transferTo(new File("/uploads/" + filename));

    return "Uploaded " + filename;

}

Unknown Fact: You can implement **virus scanning** or content validation during upload — showing enterprise-level thought in interviews. 🦠


59. How to stream file downloads in Spring Boot πŸ“₯

Use ResponseEntity<Resource> with proper HTTP headers. For large files, stream them with InputStreamResource to avoid memory overload — showing you think like a **real production engineer**. πŸ’Ύ

@GetMapping("/download/{filename}")

public ResponseEntity<Resource> downloadFile(@PathVariable String filename) throws MalformedURLException {

    Path path = Paths.get("/uploads/" + filename);

    Resource resource = new UrlResource(path.toUri());

    return ResponseEntity.ok()

        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")

        .body(resource);

}

Unknown Fact: Using streaming avoids OutOfMemoryErrors in production — a huge point to discuss in interviews. ⚡


60. How to version REST APIs in Spring Boot πŸ†•

API versioning is key for backward compatibility. Common strategies:

  • URL Path: /api/v1/users
  • Request Parameter: ?version=1
  • Header: X-API-VERSION=1
  • Content Negotiation: Accept: application/vnd.app.v1+json
Highlighting multiple strategies in interviews shows **practical knowledge** of long-term API maintenance. πŸ› ️

Unknown Fact: Header-based versioning keeps URLs clean, but path-based versioning is often preferred in enterprise systems for simplicity and readability. 🎯


Wrapping Up 🌟

Mastering REST APIs in Spring Boot isn’t just about returning JSON — it’s about **robust, secure, and maintainable endpoints**. From advanced exception handling with @RestControllerAdvice and validation groups to CORS configuration, file streaming, and API versioning, this part equips you with **production-ready knowledge** that surprises interviewers. πŸš€ πŸ’‘ Interview tip: Discuss **mixing exception handlers, validation groups, streaming large files safely, and API versioning strategies**. These show real-world thinking beyond textbook knowledge. 🌟 Real-world wisdom: REST mastery means anticipating scale, security, and maintainability — showing that you code not just for today, but for **years of production evolution**. 😎

Comments

Popular posts from this blog

🐱 Tomcat vs ⚡ Netty – Which One Should You Use?

🐱 Tomcat vs ⚡ Netty – Which One Should You Use? So recently I got curious about this too πŸ€”. Everywhere in Spring Boot tutorials we see Tomcat . Then suddenly while exploring Spring WebFlux , the name Netty pops up. And I was like – “Wait, who’s this Netty guy trying to replace Tomcat?” πŸ˜… Let’s break it down with real-time examples , icons , and fun comparisons . 🐱 Tomcat – The Traditional Web Server Type: Servlet Container (blocking I/O) World: Used with Spring MVC Style: Thread-per-request model πŸ‘©‍πŸ’» Pros: Stable, widely used, battle-tested Cons: Struggles with huge concurrent connections πŸ‘‰ Example in real life: Tomcat is like a restaurant with fixed waiters 🍴. - Each customer = one thread/waiter - If too many customers come in at once → waiters run out → customers wait outside πŸšͺ ⚡ Netty – The Reactive Rockstar Type: Asynchronous Event-Driven Network Framework World: Default for Spring WebFlux Style: Event-lo...

🎭 Spring’s Secret: Why @Transactional & Friends Betray You Silently

πŸ’‘ Lesson Learned — Not a Prod Bug, But a Real Pain No, this wasn’t a production outage. Nobody screamed at me. But I sat for 3 hours wondering: “Why the heck is my @Transactional not rolling back!?” 😡‍πŸ’« “Why is Redis cache not working?” 🀯 Turned out, the issue was one silent villain: 🧱 Self-invocation 🀷 What Is @Transactional ? If you're new: @Transactional = Tells Spring to start a DB transaction when a method is called. It’ll commit if everything’s okay. It’ll rollback if something fails. 🧠 Think of it like wrapping your code in: try { beginTransaction(); // your logic commit(); } catch(Exception e) { rollback(); } πŸ•΅️ Real-Life Analogy — The Gateway Community 🏘️ Let me tell you about my society — it has a strict watchman at the gate. Here’s how it works: πŸ›‚ Watchman = Spring Proxy 🏠 Your apartment = Your service class πŸšͺ Your room = A method inside that class πŸƒ Scenario 1: Outsider Visits Your friend from outside...

🌟 My Journey – From Zero to Senior Java Tech Lead 🌟

 There’s one thing I truly believe… If I can become a Java developer, then anyone in the world can. πŸ’― Sounds crazy? Let me take you back. πŸ•“ Back in 2015… I had zero coding knowledge . Not just that — I had no interest in coding either. But life has its own plans. In 2016, I got a chance to move to Bangalore and joined a Java course at a training center. That’s where it all started — Every day, every session made me feel like: "Ohhh! Even I can be a developer!" That course didn’t just teach Java — it gave me confidence . πŸ§ͺ Two Life-Changing Incidents 1️⃣ The Interview That Wasn't Planned Halfway through my course, I had to urgently travel to Chennai to donate blood to a family member. After that emotional rollercoaster, I found myself reflecting on my skills and the future. The next day, as I was preparing for my move to Bangalore to complete the remaining four months of my course, I randomly thought — "Let me test my skills... let me just see...