Skip to content
javahacks.dev
Spring MVC

REST API Design Rules for Java Teams That Age Well

A short set of REST API design rules for Java teams: resources, verbs, status codes, errors, pagination, versioning and what to leave out until it is needed.

6 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the OpenJDK, Spring, Swagger, GraphQL and Spring Boot logos.

A REST API outlives the team that wrote it. Clients you never meet depend on a field name from year one. Most design rules are about not regretting a choice in year three. This list is for Java services, with the Spring MVC examples in building REST APIs with Spring MVC. Each rule says what to do and what it costs.

1. Model resources as plural nouns

GET /orders, GET /orders/42, POST /orders. Not /getOrder or /createOrder. The method says what happens. Nested paths only where the child cannot exist without the parent: /orders/42/lines. Details in resource URL design.

2. Use methods for what they mean

MethodMeaningSafeIdempotent
GETReadyesyes
POSTCreate or run an actionnono
PUTReplacenoyes
PATCHPartial updatenonot guaranteed
DELETERemovenoyes

A GET that changes data breaks caches and crawlers. Making POST safe to retry is covered in idempotent endpoints.

3. Match the status code to the outcome

SituationCode
Created201 with a Location header
Success, no body204
Malformed request400
Not authenticated401
Not allowed403
Not found404
Conflict, such as a duplicate or stale version409
Valid format, failed business rule422
Too many requests429 with Retry-After

Never return 200 with {"error": ...}. Clients, proxies and monitoring read status codes.

4. One error format

Use problem details (RFC 9457, application/problem+json): type, title, status, detail, plus extension fields. In Spring, ProblemDetail implements it. Clients write one error handler. Do not leak stack traces, class names or SQL.

5. Paginate every collection

A list endpoint without paging works until a table has a million rows. Return a page and the means to get the next one:

JSON
{
  "items": [ { "id": 1 } ],
  "page": 0,
  "size": 20,
  "total": 1534
}

Offset pagination is simple and slows on deep pages; cursor pagination (?after=<token>) stays fast and fits changing data. Set a maximum page size on the server.

6. Filter, sort and select with the query string

GET /orders?status=open&sort=-created&size=50. Document the allowed fields and reject others with 400. Never pass a sort field into SQL without an allow-list, as in SQL injection prevention.

7. Name JSON fields consistently

One style for the whole API: camelCase suits JavaScript clients, snake_case is common elsewhere. Use ISO-8601 for dates and times, strings for money amounts or integer minor units with a currency code. Use enums as stable strings. See Jackson date serialization.

8. Version before you need it

A change is breaking if it removes a field, renames it, changes a type or makes an optional input required. Adding an optional field is not. Choose a mechanism up front: a path prefix (/v1/orders) is visible and simple; a media type or header is more RESTful and harder to test with a browser. Whichever you choose, keep old versions running for a published period. Ignore unknown fields when you consume APIs (unrecognized fields).

9. Do not expose your entities

Return DTOs. Entities leak columns, trigger lazy loading and create cycles (infinite recursion). The mapping cost is small and the freedom to change the database is large.

10. Secure by default

HTTPS only, authentication on everything but the documented public endpoints, authorization checks per resource and rate limits. Validate input on the server; the client's validation is a courtesy. Keep secrets out of URLs, which end up in logs.

What to leave out until needed

HATEOAS links, a custom media type for every resource, GraphQL-style field selection and batch endpoints each add maintenance. Add them when a real client needs one. Where a different protocol fits better, see REST vs GraphQL vs gRPC.

Rules 3 and 4 in one controller

Status codes and the error format are the rules most often applied halfway. This controller creates a resource with 201 and a Location header, and one handler turns every failure into the same problem document:

java
@RestController
@RequestMapping("/orders")
class OrderController {

    private final OrderService orders;

    OrderController(OrderService orders) {
        this.orders = orders;
    }

    @PostMapping
    ResponseEntity<OrderResponse> create(@Valid @RequestBody CreateOrderRequest request,
                                         UriComponentsBuilder uri) {
        OrderResponse created = orders.create(request);
        URI location = uri.path("/orders/{id}").buildAndExpand(created.id()).toUri();
        return ResponseEntity.created(location).body(created);
    }

    @GetMapping("/{id}")
    OrderResponse get(@PathVariable long id) {
        return orders.get(id);
    }
}
java
@RestControllerAdvice
class ApiErrors extends ResponseEntityExceptionHandler {

    @ExceptionHandler(OrderNotFound.class)
    ProblemDetail notFound(OrderNotFound e) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
        problem.setTitle("Order not found");
        problem.setType(URI.create("https://api.example.com/problems/order-not-found"));
        return problem;
    }

    @ExceptionHandler(StaleOrderVersion.class)
    ProblemDetail conflict(StaleOrderVersion e) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
            "The order changed since you read it. Reload and try again.");
        problem.setTitle("Stale version");
        return problem;
    }
}

Extending ResponseEntityExceptionHandler gives validation failures and malformed JSON the same format for free, once spring.mvc.problemdetails.enabled=true is set. A failed request then looks the same whatever caused it:

Shell
curl -i -X POST localhost:8080/orders -H 'Content-Type: application/json' -d '{"items":[]}'
Text
HTTP/1.1 400
Content-Type: application/problem+json

{"type":"about:blank","title":"Bad Request","status":400,"detail":"Invalid request content.","instance":"/orders"}

Rule 5 done properly: cursor pagination

Offset pagination is fine for small tables. For a large, changing one, a cursor keeps pages stable and fast, because the query seeks to a key instead of counting past rows:

java
@GetMapping
PageResponse<OrderResponse> list(@RequestParam(required = false) Long after,
                                 @RequestParam(defaultValue = "50") @Max(200) int size) {
    List<OrderResponse> items = orders.listAfter(after, size + 1);
    boolean more = items.size() > size;
    List<OrderResponse> page = more ? items.subList(0, size) : items;
    Long next = more ? page.get(page.size() - 1).id() : null;
    return new PageResponse<>(page, next);
}
java
@Query("select o from Order o where (:after is null or o.id > :after) order by o.id")
List<Order> findAfter(@Param("after") Long after, Pageable limit);

The service fetches one extra row to learn whether another page exists without a count query. The response carries next as an opaque value the client passes back, so you can change what the cursor contains later. The server enforces the maximum size, since a client that asks for a million rows will get them otherwise.

Optimistic concurrency with ETags

A PUT that overwrites a newer version loses someone's work. Return an ETag on reads and require If-Match on writes, and the client has a standard way to say "update the version that was read" in a standard way:

java
@GetMapping("/{id}")
ResponseEntity<OrderResponse> get(@PathVariable long id) {
    OrderResponse order = orders.get(id);
    return ResponseEntity.ok().eTag("\"" + order.version() + "\"").body(order);
}

@PutMapping("/{id}")
OrderResponse replace(@PathVariable long id,
                      @RequestHeader("If-Match") String ifMatch,
                      @Valid @RequestBody UpdateOrderRequest request) {
    long expected = Long.parseLong(ifMatch.replace("\"", ""));
    return orders.replace(id, expected, request);      // throws StaleOrderVersion on mismatch
}

A request without If-Match should get 428 Precondition Required, which tells the client the API needs the header. This is rule 2's idempotency in practice: a retried PUT with the same If-Match either succeeds once or conflicts, and never silently overwrites.

Rule 8 in the code: a version you can host twice

If the version lives in the path, keep controllers for each version side by side and share the service underneath. The old version maps to the same domain, with its own DTOs:

java
@RestController
@RequestMapping("/v1/orders")
class OrderControllerV1 {
    @GetMapping("/{id}")
    OrderV1 get(@PathVariable long id) {
        return OrderV1.from(orders.get(id));
    }
}

@RestController
@RequestMapping("/v2/orders")
class OrderControllerV2 {
    @GetMapping("/{id}")
    OrderV2 get(@PathVariable long id) {
        return OrderV2.from(orders.get(id));
    }
}

Each DTO type is a published contract, so changing OrderV1 is a breaking change by definition, and the compiler shows you which mappers are affected. Add a contract test per version that parses a saved example response, so that an accidental rename fails the build. When the last client leaves v1, you delete one controller and one DTO, and nothing in the domain moves.

Where these rules bend

Internal service-to-service calls can use a binary protocol, and a public API for third parties needs stricter versioning than a private one. The HTTP semantics specification, RFC 9110 defines methods and status codes, and RFC 9457 defines problem details.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.