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

๐Ÿ” Is final Really Final in Java? The Truth May Surprise You ๐Ÿ˜ฒ

๐Ÿ’ฌ “When I was exploring what to do and what not to do in Java, one small keyword caught my eye — final . I thought it meant: locked, sealed, frozen — like my fridge when I forget to defrost it.”   But guess what? Java has its own meaning of final… and it’s not always what you expect! ๐Ÿ˜… Let’s break it down together — with code, questions, confusion, jokes, and everything in between. ๐ŸŽฏ The Confusing Case: You Said It's Final... Then It Changed?! ๐Ÿซ  final List<String> names = new ArrayList <>(); names.add( "Anand" ); names.add( "Rahul" ); System.out.println(names); // [Anand, Rahul] ๐Ÿคฏ Hold on... that’s final , right?! So how on earth is it still changing ? Time to dive deeper... ๐Ÿง  Why Is It Designed Like This? Here’s the key secret: In Java, final applies to the reference , not the object it points to . Let’s decode this like a spy mission ๐Ÿ•ต️‍♂️: Imagine This: final List<String> names = new ArrayList <>(); Be...

๐ŸŒŸ 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...

๐ŸŽข Java Loops: Fun, Fear, and ForEach() Fails

๐ŸŒ€ Oops, I Looped It Again! — The Ultimate Java Loop Guide You Won't Forget “I remember this question from one of my early interviews — I was just 2 years into Java and the interviewer asked, ‘Which loop do you prefer and why?’” At first, I thought, “Duh! for-each is cleaner.” But then he grilled me with cases where it fails. ๐Ÿ˜ต That led me to explore all loop types, their powers, and their pitfalls. Let’s deep-dive into every major Java loop with examples &  real-world guidance so you'll never forget again. ๐Ÿ” Loop Type #1: Classic For Loop — “The Old Reliable” ✅ When to Use: You need an index You want to iterate in reverse You want full control over loop mechanics ✅ Good Example: List<String> names = List.of("A", "B", "C"); for (int i = 0; i < names.size(); i++) { System.out.println(i + ": " + names.get(i)); } ๐Ÿ”ฅ Reverse + Removal Example: List<String> item...