Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 119 ยท Web Fundamentals

REST API Design

Design REST APIs people enjoy using - resource URLs, methods, status codes, pagination, filtering, versioning, idempotency, ETags, problem details and OpenAPI.

Writing an endpoint takes minutes. Living with it takes years. Once other teams, mobile apps or paying customers depend on your API, every URL, field name and status code becomes a promise you can't break without hurting someone. Good API design means making those promises deliberately: predictable URLs, honest status codes, errors that explain themselves, lists that page correctly, and changes that don't break old clients.

This lesson collects the conventions professional teams use for HTTP JSON APIs, usually called REST APIs, and shows the trickier ones in running code: cursor pagination, standard error responses (RFC 9457 "problem details"), ETags for safe concurrent updates, and idempotency keys for retry-safe POST requests. It builds directly on Building a REST API with the JDK, and everything here applies the same way in Spring Boot.

What "REST" means in practice

REST (Representational State Transfer) comes from Roy Fielding's 2000 dissertation, which described the architectural style of the web: clients and servers, stateless requests, cacheable responses, and a uniform interface where you act on resources through a small set of standard methods. Very few APIs follow every constraint of the original definition (in particular, hypermedia links that drive the client). In everyday use, "REST API" means:

  • Resources are identified by URLs (/orders/42).
  • Standard HTTP methods express the action (GET, POST, PUT, PATCH, DELETE) with their standard meaning.
  • Status codes and headers carry outcomes and metadata, the way HTTP intends.
  • Representations are usually JSON.
  • Statelessness: every request carries its own authentication and context; no server-side conversation state between calls.

The rest of this lesson is about doing those five things well.

Resources and URLs

Design URLs around nouns (things), and let the method be the verb.

Good Avoid Why
GET /orders GET /getOrders The method already says "get"
POST /orders POST /orders/create POST on a collection means create
GET /orders/42 GET /order?id=42 An item lives under its collection
GET /customers/7/orders GET /orders/forCustomer/7 Nesting expresses ownership
/shipping-addresses /shippingAddresses, /Shipping_Addresses Lowercase kebab-case is the common convention

Some practical rules:

  • Use plural collection names (/orders, /orders/42), consistently.
  • Nest at most one level. /customers/7/orders is clear; /customers/7/orders/42/items/3/notes is not. Once an item has its own id, give it a top-level URL (/order-items/3).
  • Model actions as resources when you can. Cancelling an order can be POST /orders/42/cancellation (create a cancellation) or a state change PATCH /orders/42 with {"status": "cancelled"}. A few RPC-style actions like POST /reports/monthly/generate are acceptable when nothing else fits; be consistent about it.
  • Never put secrets in URLs. URLs end up in logs, browser history and analytics tools. Tokens belong in the Authorization header.

Methods with their real meaning

Clients, proxies and frameworks rely on the method semantics from How HTTP Works, so follow them exactly:

  • GET reads and must not change anything. Caches and crawlers depend on that.
  • POST to a collection creates a new item; the server picks the id and returns 201 Created with a Location header.
  • PUT replaces the entire resource with the representation in the body. Repeating it changes nothing further (idempotent). Some APIs also allow PUT to create at a client-chosen URL.
  • PATCH changes part of a resource. The simplest format is JSON Merge Patch (RFC 7396, content type application/merge-patch+json): send only the fields to change, and null removes a field. JSON Patch (RFC 6902) is a list of operations (add, remove, replace, test) for more precise edits.
  • DELETE removes the resource. Deleting something already gone can return 404 or 204; either way the end state is the same.

Choosing status codes

Clients branch on status codes, so return the most specific one that is true:

Situation Status
Read or update succeeded, body returned 200 OK
Created 201 Created + Location
Accepted for asynchronous processing 202 Accepted + a URL to poll
Succeeded, nothing to return 204 No Content
Malformed request: bad JSON, wrong type, bad query parameter 400 Bad Request
Missing or invalid credentials 401 Unauthorized + WWW-Authenticate
Authenticated but not allowed 403 Forbidden (or 404 to hide that the resource exists)
Resource doesn't exist 404 Not Found
Method not supported on this URL 405 Method Not Allowed + Allow
State conflict: duplicate email, order already shipped 409 Conflict
Precondition failed: stale If-Match 412 Precondition Failed
Wrong Content-Type 415 Unsupported Media Type
Well-formed but semantically invalid (validation rules) 422 Unprocessable Content (many APIs use 400 instead; pick one)
Rate limit exceeded 429 Too Many Requests + Retry-After
Bug on the server 500 Internal Server Error
Dependency down or overloaded 503 Service Unavailable (+ Retry-After)

Never return 200 OK with {"success": false} in the body. Monitoring, retries, caches and client libraries all look at the status code first.

Errors: problem details (RFC 9457)

Every API needs one error format, used for every failure. Rather than invent your own, use the IETF standard problem details format, defined in RFC 9457 (which replaced RFC 7807 in 2023). The response has the content type application/problem+json and these members, all optional:

  • type: a URI that identifies the kind of problem (and ideally points to documentation). Defaults to about:blank.
  • title: a short, human-readable summary of the problem type. It should be the same for every occurrence of that type.
  • status: the HTTP status code, repeated for convenience.
  • detail: an explanation specific to this occurrence.
  • instance: a URI for this specific occurrence, such as the request path or an error id.

You can add your own extension members, such as a list of field errors. Spring Framework has built-in support (ProblemDetail), as you will see in Validation and Error Handling. Here is the format produced and consumed by hand:

Java Problem details for validation and missing resources

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because the shape is always the same, a client needs only one error handler, and generic tools (API gateways, logging, client SDKs) can understand your errors without custom code. Keep detail helpful but never include stack traces, SQL or internal hostnames.

Pagination

Never return an unbounded list. A collection that has 50 items today will have 5 million next year, and one careless GET /orders will then exhaust memory on both sides. Every collection endpoint should page, with a sensible default and a maximum page size.

Two styles are common:

  • Offset pagination: GET /orders?offset=40&limit=20 (or page=3&size=20). Easy to understand, allows jumping to page 17, and maps to SQL LIMIT 20 OFFSET 40. But it gets slow for deep pages (the database still walks past all skipped rows), and it shifts when data changes between requests.
  • Cursor (keyset) pagination: GET /orders?limit=20&after=eyJpZCI6MTAwfQ. The cursor is an opaque token that encodes "where the last page ended", such as the last id. The query becomes WHERE id < :lastId ORDER BY id DESC LIMIT 20, which uses an index and stays fast at any depth. You can't jump to an arbitrary page, but feeds, logs and "load more" lists rarely need to.

The next example shows the shifting problem. A client reads the newest orders two at a time; between page 1 and page 2, a new order arrives.

Java Offset versus cursor pagination when data changes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With offsets, order 104 appears on both pages, because everything moved down by one. (A deletion would make an item vanish instead.) The cursor remembers which item the page ended at, so page 2 continues exactly after 104, and the last page has no next cursor. Base64 makes the cursor opaque: clients must pass it back unchanged instead of building their own, which leaves you free to change what is inside it later.

A paged response usually looks like this:

JSON
{
  "items": [ { "id": 104, "customer": "Kofi" }, { "id": 103, "customer": "Mei" } ],
  "next": "/orders?limit=2&after=aWQ6MTAz"
}

Returning the full next URL (rather than just the cursor) means clients never need to build URLs themselves. Some APIs put the same link in a Link: </orders?after=...>; rel="next" header instead. Avoid returning a total count by default; COUNT(*) over a big table can cost more than the page itself.

Filtering, sorting and field selection

Use query parameters for everything that narrows or orders a collection, and document the allowed values:

TEXT
GET /orders?status=shipped&customerId=7          filter by fields (AND)
GET /orders?createdAfter=2026-01-01T00:00:00Z    range filters with clear names
GET /orders?sort=-createdAt,total                "-" means descending
GET /orders?fields=id,status,total               return only some fields
GET /products?q=coffee+grinder                   free-text search

Validate every parameter. Allowing sort on any column means users can sort on unindexed columns and slow your database down; an allow-list of sortable fields avoids that. And never paste parameters into SQL: use prepared statements (PreparedStatement and SQL Injection).

Representations: JSON conventions

Small consistent choices make an API pleasant:

  • One naming style for fields, usually camelCase in JSON (it matches Java and JavaScript). Never mix styles.
  • Dates and times as ISO 8601 strings in UTC with an offset: "2026-10-17T14:05:00Z". Epoch numbers are ambiguous (seconds or milliseconds?).
  • Money as a decimal string plus a currency ({"amount": "19.99", "currency": "EUR"}) or as integer minor units (1999). Never as a binary floating-point number.
  • Ids as strings, even if they are numbers today. JavaScript loses precision on integers above 2^53, and you may switch to UUIDs later.
  • Enums as readable strings ("status": "shipped"), and tell clients to expect new values over time.
  • Wrap lists in an object ({"items": [...]}) so you can add next or other metadata later without breaking clients.

Versioning and evolution

The best versioning strategy is to need versions rarely. Most changes can be additive and therefore backward compatible:

  • Adding a new endpoint, a new optional query parameter, or a new field in a response is safe, as long as clients ignore fields they don't know (tell them to).
  • Removing or renaming a field, changing a field's type or meaning, making an optional input required, or changing a status code is a breaking change.

When you must break things, publish a new version and run both for a while. The three common styles:

Style Example Notes
URL path /v2/orders Most common; visible, easy to route and cache
Header Api-Version: 2 Clean URLs; harder to try in a browser
Media type Accept: application/vnd.shop.v2+json Most "RESTful"; the most effort for clients

Whatever you pick, announce deprecations early, measure who still calls the old version, and give dates. The Deprecation and Sunset response headers are a standard way to tell clients a version is going away.

Idempotency and safe retries

Networks fail in the worst possible place: after the server processed a request but before the client got the answer. The client can't know whether its POST /payments succeeded. If it retries, the customer may pay twice; if it doesn't, the payment may be lost.

The standard solution is an idempotency key. The client generates a unique key (a UUID) per logical operation and sends it in an Idempotency-Key header. The server stores the key with the response of the first request. A retry with the same key gets the stored response instead of being processed again. Payment providers have used this pattern for years, and the IETF is standardizing the header.

Java An idempotency key makes POST retry-safe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three attempts, one charge, and every attempt gets the same paymentId. Reusing the key for a different payment is rejected, which protects against client bugs. A production version stores keys in the database (in the same transaction as the payment) with an expiry such as 24 hours, and makes concurrent requests with the same key wait for the first one to finish.

Concurrency control with ETags

Two support agents open the same customer record. Both edit and save. Without protection, the second save silently overwrites the first one: a lost update. HTTP solves this with conditional requests:

  1. Every GET returns an ETag header, a version tag for the current representation (a version number or a hash).
  2. The client sends it back on PUT or PATCH in an If-Match header.
  3. If the resource changed in the meantime, the tag no longer matches and the server answers 412 Precondition Failed instead of overwriting.

The same tag makes caching cheap: a GET with If-None-Match: <etag> returns 304 Not Modified with no body when nothing changed. This is optimistic locking, the HTTP twin of the version column you saw in Transactions with JDBC.

Java ETag, If-None-Match and If-Match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Agent A's save wins and bumps the version to "v2". Agent B's request still carries "v1", so it gets 412 and must reload before saving, instead of erasing A's change. The server also refuses updates without If-Match (428 Precondition Required), which forces every client to use the protection. This demo can check and write in two steps only because HttpServer's default executor handles one request at a time. In a real service, the check and the write must be atomic, for example UPDATE ... WHERE id = ? AND version = ? in the database.

Rate limits, security and other cross-cutting rules

  • Authenticate every request (usually a bearer token) and authorize per resource: being logged in doesn't mean you may read order 42. More in Web Security Basics.
  • Rate-limit clients and answer 429 Too Many Requests with Retry-After when they exceed their quota.
  • Limit request sizes and page sizes, so one client can't exhaust memory.
  • Use HTTPS only, and send Cache-Control on responses that must not be cached (anything user-specific).
  • Accept and return a request id (Request-Id or the W3C traceparent header) and log it, so a failing call can be traced across services.

Documenting with OpenAPI

An API without documentation forces every client developer to read your code or guess. OpenAPI (formerly Swagger) is the standard, machine-readable description format for HTTP APIs: paths, parameters, request and response schemas, status codes and security. From one file, tools generate interactive documentation (Swagger UI, Redoc), client SDKs, server stubs, mock servers and contract tests.

YAML
openapi: 3.1.0
info:
  title: Bookshop API
  version: 1.0.0
paths:
  /books/{id}:
    get:
      summary: Get one book
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        "200":
          description: The book
          headers:
            ETag: { schema: { type: string } }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Book" }
        "404":
          description: No such book
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
components:
  schemas:
    Book:
      type: object
      required: [id, title, author]
      properties:
        id: { type: string }
        title: { type: string }
        author: { type: string }
        year: { type: integer }
    Problem:
      type: object
      properties:
        type: { type: string, format: uri }
        title: { type: string }
        status: { type: integer }
        detail: { type: string }

Two workflows exist. Code-first: write the controllers, and a library such as springdoc-openapi generates the document from your annotations at runtime. Design-first: write the OpenAPI file, review it with the client teams, then generate or implement the code. Design-first catches design mistakes before they are expensive; code-first keeps documentation in sync with less effort. Either way, publish the document and check it in CI.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which URL design follows common REST conventions for "list the orders of customer 7"?

    Use plural nouns, lowercase, nesting for ownership and the GET method as the verb.
  2. 2. A client fetches page 1 with offset=0&limit=20; then 3 new items are inserted at the top; then it fetches offset=20&limit=20. What happens?

    Every existing item moved down by 3, so the first 3 items of page 2 were the last 3 of page 1. Cursor pagination avoids this.
  3. 3. A PUT request with If-Match: "v3" arrives, but the resource is at version v4. What should the server return?

    The precondition (the client's version is current) failed. The client must re-read the resource and try again, so no update is lost.
  4. 4. What does a server do when it receives a second POST with an Idempotency-Key it has already processed (same body)?

    That is the whole point of the key - retries become safe because the server replays the first result.
  5. 5. Which of these changes to a v1 API is backward compatible?

    Adding an optional field is additive; clients that ignore unknown fields keep working. The other changes break existing clients.

Summary

  • Model resources with plural, lowercase noun URLs; let HTTP methods be the verbs; nest one level at most.
  • Respect method semantics: GET is safe, PUT replaces and is idempotent, PATCH changes part (JSON Merge Patch is the simple format), POST creates with 201 and Location.
  • Return the most specific status code, never 200 for errors, and use one error format: RFC 9457 problem details (application/problem+json).
  • Page every collection. Cursor pagination is fast and stable when data changes; offsets allow jumping but shift and slow down.
  • Use query parameters for filters, sorting and field selection, with allow-lists.
  • JSON conventions: one naming style, ISO 8601 UTC timestamps, money as decimal strings or minor units, ids as strings, lists wrapped in objects.
  • Prefer additive changes; version (usually /v2) only for breaking changes, with deprecation notices.
  • Idempotency keys make POST retries safe; ETags with If-Match prevent lost updates and with If-None-Match enable 304 caching.
  • Describe the API with OpenAPI, code-first or design-first, and keep it in CI.

Next: Web Security Basics covers authentication, password hashing, sessions and tokens, HTTPS, CORS, CSRF and the OWASP Top 10.