Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 66 ยท Building REST APIs

Designing a Clean API

Design a clean Spring Boot REST API: resource names, pagination, sorting and filtering, versioning, idempotency keys, HATEOAS and OpenAPI docs.

You know how to write a controller, read a body, validate it and report errors. The next question is harder: what should the API look like? A good design is boring in the best way. Names are predictable, lists are paged, repeating a request does no harm, and a new version does not break old clients. An API is a contract with people you cannot see, and every sloppy choice becomes something you must support for years.

This lesson gives you practical rules for resource naming, collection parameters (paging, sorting, filtering), versioning, idempotency, a short note on HATEOAS, and documentation with OpenAPI. Language-neutral background is in REST API Design; here we focus on how Spring Boot supports each rule.

Spring and springdoc are read-only on this site. The TryIts implement the core logic (paging and idempotency) in plain Java, which is the part that matters when you design the rules.

Name resources, not actions

REST models your domain as resources, identified by URLs, and uses the HTTP method as the verb. The URL is a noun, plural, in lowercase with hyphens:

Goal Request
List books GET /books
Read one GET /books/42
Create POST /books
Replace PUT /books/42
Partial update PATCH /books/42
Delete DELETE /books/42
A book's reviews GET /books/42/reviews

Avoid verbs in the path (/getBooks, /createBook, /books/42/delete): the method already says it. Nest at most one or two levels (/books/42/reviews); deeper paths become hard to evolve, and /reviews/17 is fine once an item has its own identity. When an action truly does not fit CRUD, such as cancelling an order, model it as a sub-resource or a state change: POST /orders/9/cancellation, or PATCH /orders/9 with a new status.

Use the correct status codes: 201 Created with a Location header for a successful POST, 204 No Content for a delete, 404 for a missing item. GET must never change data, because browsers, crawlers and caches assume it is safe to repeat. PUT and DELETE are meant to be idempotent, a property we return to below.

Pagination, sorting and filtering

Any endpoint that returns a list must be able to say "not everything". An unbounded GET /books works with ten rows in development and takes the server down with ten million in production. Define the parameters up front:

Text
GET /books?page=2&size=20&sort=title,asc&author=Le%20Guin
  • page and size pick a slice. Cap size on the server (for example at 100) whatever the client sends.
  • sort names a field and a direction. Accept only an allow-list of fields, never a raw column name that goes into a query.
  • filters are plain query parameters (author, minPrice, status). Keep them few and well named.

Spring Data supplies this for you: a controller can take a Pageable and return a Page, and the repository does the rest. Spring Data also reads page, size and sort from the query string automatically.

Java
@GetMapping
Page<BookResponse> list(
        @RequestParam(required = false) String author,
        @PageableDefault(size = 20, sort = "title") Pageable pageable) {
    return bookService.search(author, pageable).map(BookResponse::from);
}

Boot limits size through spring.data.web.pageable.max-page-size (default 2000, so lower it). Serializing a Page directly exposes Spring Data's internal shape, which can change between releases, so many teams return their own small envelope (items, page, size, totalItems) or use the PagedModel wrapper that recent Spring Data versions provide.

The first TryIt implements the rules you would otherwise take from Pageable: parse and clamp the parameters, validate the sort field against an allow-list, filter, sort, slice and report totals.

Java Paging, sorting and filtering logic

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.

Offset paging and its limits

page and size are offset paging: the database skips page * size rows and returns the next slice. It is simple and lets a user jump to page 50, but it gets slow on huge tables (skipping a million rows still reads them) and can show duplicates or gaps when rows are inserted while someone pages. For feeds and large exports, use keyset paging: the client sends the last id it saw (?after=1042&size=20) and the query becomes WHERE id > 1042 ORDER BY id LIMIT 20, which stays fast and stable. Spring Data supports it through ScrollPosition and Window types.

Versioning

Sooner or later you must change a response in a way that breaks clients: rename a field, change a type, remove an endpoint. Versioning gives old clients time to move. The common choices:

Three ways to version

In the path /v1/books. Simple and visible.
In a header A custom header or media type. Clean URLs.
Query parameter ?version=2. Easy but easy to forget.

Pick one rule and apply it to the whole API.

1 / 2

A path prefix is the easiest to understand, to test with a browser and to route in a gateway. Spring Framework 7 also added first-class API versioning support that resolves the version from a path segment, header, media type parameter or query parameter and lets you mark mappings with a version attribute; check the reference for your release for the exact API. The deeper rule is to make additive changes whenever you can: adding an optional field is not a breaking change, and clients should ignore fields they do not know (which is the default in Boot, as you saw in Request and Response Bodies).

Idempotency

An operation is idempotent if doing it twice has the same effect as doing it once. GET, PUT and DELETE are idempotent by definition: deleting book 42 twice leaves the same state (the second reply may be 404, but nothing new happened). POST is not: two identical POSTs create two orders. That is a real problem, because networks fail. A client that gets a timeout cannot know whether the server processed the request, so it retries, and the customer is charged twice.

The standard fix is an idempotency key. The client generates a unique value per logical action and sends it in a header (Idempotency-Key: 6f1c...). The server remembers the key together with the stored response. If the same key arrives again, the server returns the saved response instead of doing the work a second time.

Java An idempotency key store

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.

A production version also stores a hash of the request body, to reject the same key reused with different data, gives keys an expiry (a day is typical) and writes the key in the same database transaction as the order, so a crash cannot leave one without the other.

A word on HATEOAS

HATEOAS ("hypermedia as the engine of application state") means responses include links that tell a client what it can do next: "_links": {"self": ..., "cancel": ...}. Spring HATEOAS adds helpers to build such links. In theory it lets clients discover the API; in practice most teams ship plain JSON with documented URLs, because hypermedia clients are rare and the links add weight. Consider links where they genuinely help, such as pagination (next, prev) and state-dependent actions, and do not feel obliged to adopt the full model.

Documenting with OpenAPI

An API nobody can read is an API nobody uses. OpenAPI is the standard machine-readable description of a REST API, and springdoc-openapi generates it from your controllers. Add the dependency and the specification appears at /v3/api-docs with an interactive Swagger UI at /swagger-ui.html:

XML
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>${springdoc.version}</version>
</dependency>
Java
@Operation(summary = "Find one book", description = "Returns 404 if the id is unknown.")
@ApiResponse(responseCode = "404", description = "No such book")
@GetMapping("/{id}")
BookResponse find(@PathVariable long id) { ... }

springdoc is not part of Spring Boot, so pick a version compatible with your Boot release. Because the documentation is generated from code, it stays in step with the API, which is its main strength. Expose the UI in development and think twice before exposing it publicly in production; see CSRF, CORS and Secure Defaults for the hardening checklist.

Describing endpoints in detail

springdoc already derives paths, parameters and schemas from your controllers and DTOs. Annotations from io.swagger.v3.oas.annotations add the human part:

Annotation Put it on Adds
@Tag Controller A group name and description shown in the UI
@Operation Handler method summary, description, operationId, deprecated
@Parameter Method parameter Description, example, required
@ApiResponse / @ApiResponses Handler method One entry per status code, with description and body schema
@Schema DTO class or field Description, example, requiredMode, minimum, maximum and similar
@Hidden Controller or method Removes it from the specification
Java
@Tag(name = "Books", description = "Browse and manage the catalog")
@RestController
@RequestMapping("/api/books")
class BookController {

    @Operation(summary = "Create a book", description = "Returns the created book and its Location header.")
    @ApiResponses({
        @ApiResponse(responseCode = "201", description = "Created"),
        @ApiResponse(responseCode = "400", description = "Validation failed",
            content = @Content(schema = @Schema(implementation = ProblemDetail.class))),
        @ApiResponse(responseCode = "401", description = "Missing or invalid token")
    })
    @PostMapping
    ResponseEntity<BookResponse> create(@Valid @RequestBody BookRequest request) { /* ... */ }
}

@Schema(description = "Data needed to create a book")
record BookRequest(
    @Schema(description = "Title as printed on the cover", example = "Refactoring") @NotBlank String title,
    @Schema(description = "Price in cents", example = "4500", minimum = "0") @PositiveOrZero int priceInCents) {}

Bean Validation annotations such as @NotBlank and @Size are picked up automatically, so required and length limits appear in the schema without extra work.

Groups, security and hiding

Groups split a large API into several documents, for example a public and an admin API, each selectable in the UI:

Java
@Bean
GroupedOpenApi publicApi() {
    return GroupedOpenApi.builder().group("public").pathsToMatch("/api/**").pathsToExclude("/api/admin/**").build();
}

@Bean
GroupedOpenApi adminApi() {
    return GroupedOpenApi.builder().group("admin").pathsToMatch("/api/admin/**").build();
}

Security. Declare the scheme once, then reference it. For a JWT bearer token the UI gets an "Authorize" button, and "Try it out" requests carry the token (JWT and OAuth2):

Java
@Bean
OpenAPI apiInfo() {
    return new OpenAPI()
        .info(new Info().title("Bookstore API").version("v1"))
        .components(new Components().addSecuritySchemes("bearerAuth",
            new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")));
}

Then mark protected operations with @SecurityRequirement(name = "bearerAuth"), or add .addSecurityItem(new SecurityRequirement().addList("bearerAuth")) to the bean above to apply it everywhere. This only documents the requirement; actual protection is still your Spring Security configuration, which must also allow the documentation URLs (/v3/api-docs/**, /swagger-ui/**) if you want them public.

Hiding and switching off. Use @Hidden for internal endpoints, springdoc.paths-to-exclude or springdoc.packages-to-scan for broad control, and turn the documentation off where it should not exist:

PROPERTIES
# application-prod.properties
springdoc.api-docs.enabled=false
springdoc.swagger-ui.enabled=false

Exporting the specification. The running application serves /v3/api-docs (JSON) and /v3/api-docs.yaml. Save it into your repository to generate client libraries with OpenAPI Generator, to diff the contract in pull requests and to lint it in CI:

Terminal
curl http://localhost:8080/v3/api-docs.yaml -o openapi.yaml

The springdoc Maven and Gradle plugins automate this during the integration-test phase by starting the application, calling the endpoint and writing the file. A committed spec turns an accidental breaking change (a removed field, a renamed path) into a visible diff.

The idea behind all these annotations is simple: they are metadata that a generator reads by reflection. The stand-in below declares two tiny annotations, reads them from a controller class and prints a specification skeleton. What is real: the annotations-plus-reflection mechanism and the shape of the result. What is the stand-in: the annotations are our own, and springdoc produces a much richer document.

Java Generating an API description from annotations

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.

The hidden cache endpoint never appears, exactly the effect of @Hidden. Because the document is generated from the code, it cannot drift away from the real API as a hand-written file would.

Review a new endpoint with four questions: Is the URL a plural noun? Does the list endpoint page, with a capped size? Is a retry of this request safe? Can I add a field later without breaking anyone? If all four answers are yes, the design is probably sound.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which URL follows good REST naming?

    Resources are plural nouns and the HTTP method is the verb. POST /books creates a book; verbs in the path duplicate what the method says.
  2. 2. Why should the server cap the size parameter of a list endpoint?

    Clients can send any number. A server-side maximum protects memory, database and network, whatever the client asks for.
  3. 3. What problem does an idempotency key solve for POST requests?

    When a response is lost, the client retries. The server looks up the key and replays the saved response instead of creating a duplicate.
  4. 4. Which change is normally safe for existing clients?

    Clients that ignore unknown fields keep working when you add one. Renames, type changes and removals are breaking changes and need a new version or a deprecation period.
  5. 5. What is a drawback of offset paging on a huge table?

    The database still has to walk past the skipped rows, and shifting data moves items between pages. Keyset paging avoids both problems.

Summary

  • Use plural nouns for resources and let the HTTP method be the verb; return 201 with Location, 204 and 404 where they fit.
  • Every list endpoint pages; cap size, allow-list sort fields and keep filters simple. Spring Data's Pageable does the heavy lifting.
  • Offset paging is simple; keyset paging is better for large or fast-changing data.
  • Version with a clear rule (usually a path prefix), but prefer additive changes that need no new version.
  • Make unsafe operations retry-safe with idempotency keys stored together with the result.
  • HATEOAS is optional; document the API with OpenAPI through springdoc.

Next: Filters, Interceptors and Argument Resolvers.