1. What is an API Contract?
An API contract is a shared agreement between the server and the client. It defines the endpoint, the request body, and the response structure.
The "Leaky Abstraction" Problem
Many developers return their JPA/Hibernate entities directly from the controller:
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userRepository.findById(id).get(); // DANGEROUS
}
Why this is bad:
- Security: You might leak sensitive fields (e.g.,
passwordHash). - Coupling: A database change forces a frontend change.
- Performance: You might trigger lazy-loading of 50 other related objects.
2. The Solution: Data Transfer Objects (DTOs)
A DTO is a plain object designed specifically for carrying data. It contains only what the client needs.
public class UserResponseDTO {
private String username;
private String profileUrl;
// No password, no DB IDs, no complex relationships
}
3. Best Practices for REST in LLD
- Use Nouns, not Verbs:
/v1/ordersinstead of/v1/getOrders. - Hierarchical Pathing:
/v1/users/{id}/ordersfor sub-resources. - Versioning: Always include a version (e.g.,
/v1/) to allow for breaking changes.
4. Interview Checklist for API Design
- Are we using the correct HTTP methods (POST for creation, PUT for updates)?
- Is there validation on the input (e.g.,
@Valid,@NotNull)? - How are we handling errors? Do we have a global
@ExceptionHandler? - Is the response paginated for large lists?
Final Takeaway
The DTO pattern is a Senior Engineer's best friend. It ensures that your code remains modular and your system remains secure.