SteelReed

Search

Search posts, questions…

5. Spring Boot

Designing REST APIs that don't break clients: URLs, pagination, versioning, errors, caching and Spring Boot structure

An API is a contract with clients you don't control. The six REST constraints, URL conventions, offset vs cursor, a compatibility policy and versioning (built into Spring Framework 7), RFC 9457 errors, ETags, choosing REST, gRPC or GraphQL, layering a Spring Boot project, and how to review an AI-generated API.

17 Nov 20268 min readMid

–

1. The problem

A team changes price from the number 250000 to the object {"amount": 250000, "currency": "VND"} to be "more correct". 30% of users are on an old app version: it fails to parse and crashes on the cart screen. The same week, a partner reports page 2 repeating orders from page 1.

2. Key idea

The server changes in one deploy; clients don't. Design for the oldest client still running; the default is to add, not to modify.

Decision Cost of getting it wrong
Returning entities instead of DTOs leaks sensitive fields, the DB schema becomes the contract, lazy loading during serialization
Offset pagination for feeds slow deep pages, repeated or skipped items
No compatibility policy every field change breaks old apps
Errors in a different shape everywhere, returned as 200 clients can't tell "fix the request" from "retry"
long ids as JSON numbers JavaScript rounds ids above 2^53

2.1 Which technique?

Technique Use when Don't use when
Cursor pagination feeds, public APIs, big tables small admin tables that need page jumps
URI versioning (/v1) public APIs compatible changes: no new version needed
ETag + If-Match several people edit one resource (412 if it changed) write-once resources
gRPC internal services, low latency browsers calling directly
GraphQL many client types need different data you want simple HTTP caching, small team

2.2 Small conventions, big consequences

  • Adding fields or endpoints is compatible. Renaming, removing, retyping or changing meaning is breaking. Retire versions with Deprecation and Sunset headers.
  • Timestamps are RFC 3339 strings in UTC; money is never a double.
  • A creating POST returns 201 with Location; errors return application/problem+json with only a trace_id, no stack traces.

3. In Java

JAVA
public record CourseResponse(String id, String title, long version) {}   // string id: safe for JS
 
@RestController
@RequestMapping("/v1/courses")
class CourseController {
    @GetMapping("/{id}")
    ResponseEntity<CourseResponse> get(@PathVariable long id) {
        CourseResponse c = courseService.get(id);                         // the service returns a DTO, not an entity
        return ResponseEntity.ok().eTag(String.valueOf(c.version())).body(c);
    }
}
 
@RestControllerAdvice
class ApiExceptionHandler {
    @ExceptionHandler(CourseFullException.class)
    ProblemDetail full(CourseFullException e) {
        ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
        p.setType(URI.create("https://api.example.com/problems/course-full"));
        return p;                                                         // 409, application/problem+json
    }
}

Spring Framework 7 (Boot 4) has built-in API versioning: @GetMapping(version = "1.1"). Other languages: NestJS uses DTO classes and exception filters; ASP.NET Core ships ProblemDetails.

What REST really is

REST is an architectural style, not a protocol: resources have URLs, and clients exchange representations (JSON) through standard HTTP methods. Six constraints: Client-Server, Stateless (each request carries everything needed), Cacheable, Uniform Interface, Layered System, Code on Demand (optional).

"Stateless" is about conversation state; business data still lives in the database, and sessions in Redis still scale horizontally. Most "REST" APIs only reach level 2 of the Richardson Maturity Model (right methods and status codes); very few do HATEOAS. Say so in interviews.

4. Working with AI

Give the AI: OpenAPI from your endpoint table, DTOs and mappers, a @RestControllerAdvice in the repo's error format, contract tests for each status code.

Check in AI-written code:

  • No @Entity in any controller return type.
  • Diff old and new OpenAPI with oasdiff: no renamed, removed or retyped fields within a version.
  • Lists have a maximum size; cursors have an id tie-breaker.
  • Large long ids go out as JSON strings.
  • /me/... endpoints take the user from the token, not a client-sent user_id.

5. Exercises

Exercise 1: Renaming a field

Product wants fullName renamed to name in GET /v1/users/{id}. The AI offers: (A) rename it in v1 and write a release note; (B) add name, keep fullName marked deprecated, send Deprecation/Sunset, remove it in v2. Choose, and say what would change your choice.

Solution to Exercise 1

Choose B: adding a field is compatible, and old clients still read fullName. (A) is breaking: old apps read null.

The choice flips when you control every client and deploy together (an internal frontend in the same repo, no mobile or partners). Before removing fullName in v2, measure who still calls it (logs by User-Agent or API key), don't guess.

Exercise 2: Rounded ids

After switching ids to Snowflake, the frontend reports "order not found". Logs: GET /v1/orders/1234567890123456800 returns 404; the DB has order 1234567890123456789; the list JSON returns "id": 1234567890123456789. Diagnose, the 15-minute action, the root fix.

Solution to Exercise 2
  • Diagnosis: the id exceeds 2^53; JSON.parse reads it as a double and rounds it, and the frontend calls back with the wrong id.
  • 15 minutes: add an id_str string field (adding is compatible) and have the frontend use it.
  • Root fix: every DTO serializes long ids as strings; write it into the API conventions and add a contract test on the type of id.

Summary

  • An API is a contract with clients you don't control; the default is to add, not modify.
  • Only DTOs leave the service; large ids are strings.
  • Feeds and public APIs use cursors with a tie-breaker.
  • Renaming, removing and retyping are breaking; retire with Deprecation and Sunset.
  • Errors as Problem Details; ETag + If-Match for optimistic locking.

Read more: Advanced REST API design.

Practice interview questions on this topic

All Web & REST API questions →All Spring Boot questions →All SQL & Query Tuning questions →All JPA & Hibernate questions →

Loading comments…
Next on the roadmapAdvanced REST API design: idempotent methods, gateway URLs, pagination and sorting