Lesson 6 of 17 2 min

LLD Lesson: API Contract Design (REST & DTOs)

Learn how to design clean API contracts that decouple your frontend from your internal data models using DTOs.

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:

  1. Security: You might leak sensitive fields (e.g., passwordHash).
  2. Coupling: A database change forces a frontend change.
  3. 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/orders instead of /v1/getOrders.
  • Hierarchical Pathing: /v1/users/{id}/orders for 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.

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.