Skip to content
javahacks.dev
Spring MVC

How to Design REST API Resource URLs and Naming That Last

Design stable REST URLs: plural nouns, shallow nesting, query strings for filters, identifiers that never change and a plan for the day a name must change.

8 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the Spring, Spring Boot and Hibernate logos.

A URL is the part of an API that clients copy into code, bookmarks, logs, documentation and other people's integrations. It is the hardest thing to change later. A rename that takes five minutes in your controller takes a year of deprecation in the field. Good resource URLs follow a small set of habits: plural nouns for collections, stable ids, nesting only for ownership, filters in the query string and a considered answer for operations that are not create-read-update-delete. This post sets out those habits with Spring MVC controllers, shows the before and after for each, covers the conventions worth fixing early, explains how to rename a URL without breaking clients and says where the rules bend. Examples use Spring Boot 4; the rules apply to any HTTP API. The grammar of URIs is in RFC 3986, and the meaning of methods in RFC 9110.

Use plural nouns for collections

A URL names a thing, and the HTTP method says what to do with it. A path that contains a verb repeats the method and ties the API to its implementation:

AvoidPrefer
POST /createOrderPOST /orders
GET /getOrder?id=7GET /orders/7
POST /deleteOrder/7DELETE /orders/7
GET /orderListGET /orders
POST /order/updatePUT /orders/7 or PATCH /orders/7

Use the plural for the collection and the same path with an id for one member. Singular for some resources and plural for others forces clients to remember which, so pick plural everywhere, including /users/7, /categories/3. A controller then reads like the table above:

src/main/java/dev/javahacks/orders/OrderController.javajava
@RestController
@RequestMapping("/orders")
class OrderController {

    @GetMapping
    Page<OrderSummary> list(Pageable page) { /* ... */ }

    @PostMapping
    ResponseEntity<Order> create(@RequestBody @Valid NewOrder body) {
        Order created = service.create(body);
        return ResponseEntity.created(URI.create("/orders/" + created.id())).body(created);
    }

    @GetMapping("/{id}")
    Order get(@PathVariable long id) { /* ... */ }

    @PutMapping("/{id}")
    Order replace(@PathVariable long id, @RequestBody @Valid NewOrder body) { /* ... */ }

    @DeleteMapping("/{id}")
    ResponseEntity<Void> delete(@PathVariable long id) { /* ... */ }
}

The 201 Created response carries a Location header pointing at the new member, which lets a client follow it without constructing the URL. Wrong methods answer 405 with an Allow header, as explained in fixing 405 Method Not Allowed in Spring MVC.

Keep the path lower case, with hyphens between words (/line-items, not /lineItems or /line_items): URLs are case-sensitive in the path, and mixed case produces 404s from typos that a lower-case rule prevents. No trailing slash, no file extension (/orders.json couples the URL to a format that the Accept header should choose), and no implementation words (/api/v1/OrderServiceImpl).

Identify with stable ids

The id in the path is a promise that the URL keeps meaning the same thing. Choose ids that do not change and do not reveal more than intended.

  • Never use a value that can change as the id. An email, a name or a slug that the user can edit makes every saved link break on the edit. If you also want a human-friendly path, redirect from it to the stable one.
  • Sequential integers are fine for most APIs, provided authorization is checked per object. An attacker who changes 7 to 8 should get a 404 for an order that is not theirs. If you prefer not to reveal volume or ordering (how many orders you have, how fast they grow), use UUIDs or another opaque id.
  • Do not leak the database. An internal surrogate key is acceptable; a composite of internal column values or a table name is not.
  • Types in the path are strict. GET /orders/abc for a long id fails type conversion and should return 400 with a clear message, not a stack trace; see the web-layer handling in MissingServletRequestParameterException and its neighbors.

A representation should include its own canonical URL ("self": "/orders/7") so clients never build URLs by string concatenation, and so that when you do move something you can hand out the new address.

Nest only for ownership, and only to two levels

A nested path says "this thing belongs to that thing": /customers/3/orders lists the orders of customer 3. Use nesting when the child has no meaning without the parent, or when the parent is the natural way to find the children. Stop at two levels. Beyond that the path becomes long, clients must know every ancestor to address a leaf, and a change to the hierarchy breaks everything below it.

Text
/customers/3/orders             the orders of customer 3        good
/customers/3/orders/7           order 7 of customer 3           acceptable
/customers/3/orders/7/lines/2   deep: promote lines instead     avoid
/orders/7/lines/2               order 7's line 2                two levels, fine

When an object has its own id that is unique across the system, address it directly: /orders/7. Offer both only if each answers a distinct need (list the customer's orders under the customer, fetch a single order at the top level), and make both return the same representation of the same resource. A relationship that is not ownership, such as an order and the products it contains, is a reference in the body, not a nesting in the path.

Put filters in the query string

Selecting, sorting and paging a collection is not a different resource, it is a different view of the same one. Use query parameters:

Text
GET /orders?status=SHIPPED&customerId=3&sort=-createdAt&page=2&size=20
java
@GetMapping
Page<OrderSummary> list(@RequestParam(required = false) OrderStatus status,
                        @RequestParam(required = false) Long customerId,
                        @PageableDefault(size = 20) Pageable page) {
    return orders.search(status, customerId, page);
}

Path segments identify a resource; query parameters refine a request for one. A path like /orders/status/shipped bakes one filter into the URL structure and leaves nowhere to put the second. Treat query parameters as optional, accept unknown ones gracefully or reject them consistently, and cap the page size on the server. Pagination, sorting and filtering design is detailed in the pagination post of this series, and the rule set for teams is in REST API design rules for Java teams. Never put secrets or personal data in a query string: URLs are written to access logs, browser history and referrer headers.

Actions that are not CRUD

Not every operation fits create, read, update, delete: cancelling an order, publishing a post, resetting a password, running a report. The temptation is a verb in the path, POST /orders/7/cancel. There are three tidier options, in order of preference.

Model the result as a resource. A cancellation is a thing that comes into existence: POST /orders/7/cancellation creates it, GET /orders/7/cancellation reads it. Payments, approvals, exports and password resets are natural resources too (POST /password-resets). This keeps the verb in the method and gives the operation a state you can query.

Change a field. If the action is a state transition, PATCH /orders/7 with {"status": "CANCELLED"} is honest, and the server enforces which transitions are legal (409 Conflict for an illegal one).

A custom verb as a last resort. When neither fits, use POST with a verb sub-resource, and be consistent about the style: POST /orders/7:cancel (Google's convention) or POST /orders/7/actions/cancel. Accept that the API is now partly RPC, and document it.

java
@PostMapping("/{id}/cancellation")
ResponseEntity<Cancellation> cancel(@PathVariable long id, @RequestBody(required = false) CancelRequest body) {
    Cancellation c = service.cancel(id, body);
    return ResponseEntity.status(HttpStatus.CREATED).body(c);
}

Whatever the choice, POST for non-idempotent actions, and give any action that matters an idempotency key so a retry does not run it twice; see making REST endpoints idempotent for the mechanism.

Conventions worth fixing early

Decide these once, write them in the API guidelines and enforce them in review.

  • Naming style for multi-word segments and parameters: hyphens in paths, camelCase or snake_case in query parameters and JSON, and one of them everywhere.
  • Version placement: a prefix such as /v1 or a header, chosen before the first client; the options and costs are in API versioning strategies.
  • Base path: /api or a subdomain, so API traffic is routable separately from pages.
  • Date and number formats in parameters: ISO 8601 dates, no locale-specific formats.
  • Boolean and list parameters: ?active=true, ?ids=1,2,3 or ?id=1&id=2; pick one for lists.
  • Error format: one body shape for every failure.
  • Collection responses: an envelope with items and paging metadata, not a bare array, so you can add fields later.

Renaming safely

Sometimes a URL has to change: a product was renamed, a resource was split. Do it without breaking clients.

  1. Add the new URL alongside the old one, serving the same behavior.
  2. Redirect or alias the old one. For GET, a 301 Moved Permanently (or 308 to preserve the method) to the new location lets clients and caches follow. For POST and PUT, a redirect is unreliable across clients, so serve both until clients move.
  3. Mark the old one deprecated with Deprecation and Sunset headers and a changelog entry.
  4. Measure usage of the old URL in access logs, and contact the callers that remain.
  5. Remove it only when traffic is zero, or after the announced date.
java
@GetMapping({"/orders/{id}", "/order/{id}"})      // new path first, old path kept temporarily
Order get(@PathVariable long id) { /* ... */ }

Keep the representation stable across the move; changing the URL and the body together doubles the migration.

Where these rules bend

A pure RPC style, a command endpoint (POST /payments/charge), is acceptable when the operation is the product and there is no resource worth modeling, as long as you are consistent. Internal APIs consumed by one front end can follow looser naming, since both sides change together. Legacy systems may already have URLs with verbs and mixed case; consistency inside the existing style beats a half-migration. And for APIs that follow an industry standard (a payment, a healthcare or an open banking specification), the standard's URLs win over these habits. The test for any rule is whether a client developer, reading the URLs cold, can guess the next one.

Taggedhow to
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.