๐ 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
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
Post a Comment