Skip to content

HTTP and REST APIs

Spring MVC maps HTTP exchanges to Java methods, but annotations do not define a good API by themselves. Begin with HTTP semantics and a resource contract.

Method properties

Method Typical meaning Safe Idempotent
GET Retrieve a representation Yes Yes
POST Process or create under a resource No Not guaranteed
PUT Replace state at the target URI No Yes
PATCH Apply a partial modification No Not guaranteed
DELETE Remove target state No Yes

Idempotent means repeating the same intended request has the same intended effect; responses may differ because state, timestamps, or logs changed. For unsafe operations that clients may retry after an ambiguous failure, define an idempotency-key and deduplication protocol.

A resource controller

@RestController
@RequestMapping("/books")
final class BookController {
    private final BookService books;

    BookController(BookService books) {
        this.books = books;
    }

    @GetMapping("/{id}")
    BookResponse find(@PathVariable UUID id) {
        return BookResponse.from(books.require(id));
    }

    @PostMapping
    ResponseEntity<BookResponse> create(@Valid @RequestBody CreateBookRequest request) {
        Book created = books.create(request.toCommand());
        URI location = URI.create("/books/" + created.id());
        return ResponseEntity.created(location).body(BookResponse.from(created));
    }
}

Transport DTOs prevent HTTP representation concerns from leaking into persistence entities. Decide pagination, filtering, sorting, media types, and compatibility rules as part of the public contract.

Status and caching

Use status codes semantically: 201 with Location for creation, 204 for a successful response intentionally without content, 400 for malformed input, 401 for missing/invalid authentication, 403 for insufficient authorization, 404 for an unavailable target, and 409 for an applicable state conflict.

Conditional requests with validators such as ETags can prevent lost updates and avoid retransmitting unchanged representations. Cache behavior belongs to HTTP headers, not only to an application-side cache. HTTP cache semantics and server-side method or data caching are related but separate contracts.

Exercises

  1. Design an idempotent retry strategy for resource creation.
  2. Explain the difference between PUT and PATCH.
  3. Specify cursor- and offset-based pagination trade-offs.

See the HTTP Semantics specification.