Controllers and Request Mapping

Controllers and Request Mapping in Spring Boot: In a large organisation's mailroom, every incoming item passes across a sorting desk.

The Analogy: A Mailroom Sorting Desk

In a large organisation's mailroom, every incoming item passes across a sorting desk. Two things on the item decide where it goes: the address written on the front, and the class of post -- a first-class letter, a parcel, a registered delivery. The clerk reads both. The address tells them which department pigeonhole the item belongs to; the class of post tells them which handling procedure applies once it gets there. An item is only fully routed when both the address and the class of post match a slot the desk actually serves.

A Spring controller is that sorting desk. Each incoming HTTP request carries an address -- the URL path -- and a class of post -- the HTTP method, GET or POST or DELETE. The dispatcher reads both and routes the request to the one handler method whose path pattern and HTTP method both match. A class-level base path is the department prefix stamped on every pigeonhole in that aisle, so the individual handlers only need to name the part of the address that distinguishes them. Path patterns can contain a placeholder segment, the way a pigeonhole might be labelled "invoices, any number," so a request for a specific resource is routed by shape rather than by an exact string.

Two different failures produce two different rejection stamps, and confusing them is a classic error. If an item arrives with an address the mailroom does not serve at all -- no such pigeonhole exists -- it is returned marked "no such address," which is a 404. But if the address is real and the pigeonhole exists, yet the item was sent by a class of post that slot does not accept -- a parcel sent to a letter-only slot -- it is returned marked "wrong service for this address," which is a 405. The distinction matters: 404 means the resource does not exist, while 405 means it exists but not for the method you used, and a client debugging the two needs to know which.

The failure that does real damage is quieter. A well-run desk replies to an enquiry with a purpose-written summary card containing exactly the details the sender should see. The lazy desk photocopies the entire internal case file -- costs, supplier references, private notes -- and stuffs it in the reply envelope. Returning a database entity straight from a handler is that photocopy: every internal field is serialised and sent, confidential columns included, and the reply breaks the day someone renames a column in the file. The fix is to write the summary card deliberately -- a dedicated response type that exposes only the fields the API promises.

Syntax or Core Structure

A @RestController returns values as the response body rather than as template names. A class-level @RequestMapping sets a base path, and method annotations like @GetMapping bind an HTTP method and a path pattern to a handler. The dispatcher matches an incoming request against the registered routes on both path and method.

@RestController
@RequestMapping("/api/products")
public class ProductController {
    @GetMapping                 public List<ProductResponse> list() { ... }
    @GetMapping("/{id}")        public ProductResponse findOne(@PathVariable Long id) { ... }
    @PostMapping                public ProductResponse create(@RequestBody CreateRequest r) { ... }
}

Routing four requests against those three registered routes shows how a match, a 404, and a 405 each arise:

Output:

method path                    outcome
-----------------------------------------------
GET    /api/products           list (200)
GET    /api/products/42        findOne id=42 (200)
DELETE /api/products/42        405 method not allowed
GET    /api/orders             404 not found
-----------------------------------------------
matched : 2
405     : 1
404     : 1

The first two requests match a route on both path and method and are handled. The DELETE /api/products/42 request matches the path pattern /api/products/{id} -- that pigeonhole exists -- but no handler is registered for DELETE on it, so the desk returns 405, not 404: the resource is real, the method is not served. The GET /api/orders request matches no registered path at all, so it is a genuine 404. Reading the two rejections correctly is the difference between looking for a missing route and looking for a missing method on a route that already exists.


Technical Depth: Reading Input, Projecting Output, and Status Codes

Binding request parameters

A handler reads input from three places: path variables identify a resource, query parameters filter or paginate, and the request body carries a payload that Jackson deserialises. Query parameters have two behaviours worth pinning down: an optional parameter with required = false binds to null when absent, while one with a defaultValue binds to that value. A required parameter with no default and no value is a 400 before your method runs.

@GetMapping
public List<ProductResponse> search(
        @RequestParam(required = false) String category,   // null if absent
        @RequestParam(defaultValue = "0") int page,        // 0 if absent
        @RequestParam int size) { ... }                    // required: 400 if absent

Output:

request                   category  page  status
-----------------------------------------------
?category=book&page=2     book      2     200
(no params)               null      0     200
?size missing (req)       -         -     400
-----------------------------------------------
bad requests (400)        : 1

With category and page supplied, both bind directly. With no parameters at all, category is null and page falls back to its default of 0 -- but note the third row: because size is required and has no default, a request omitting it never reaches the method body and returns 400. Giving optional parameters a default is what keeps an absent value from becoming a NullPointerException deeper in your code, which would surface as a 500 and be your fault rather than the client's.

Never return an entity: project to a response type

A handler should return a dedicated response type, never a persistence entity. Projecting the entity onto a record you control means only the fields you list are serialised, and the ones you omit are hidden by construction rather than by remembering to annotate them away.

public record ProductResponse(Long id, String name, BigDecimal price) {
    public static ProductResponse from(Product p) {
        return new ProductResponse(p.getId(), p.getName(), p.getPrice());
    }
}

Output:

entity fields   : 6
response fields : 3
hidden fields   : 3
hidden          : costPrice supplierRef internalNotes

The entity has six fields; the response record exposes three, so three internal fields -- cost price, supplier reference, internal notes -- are hidden by the projection. If you returned the entity directly, all six would serialise, including the three you never meant to expose, and they would keep exposing until someone noticed. The projection makes the API contract something you state deliberately rather than something that leaks by default.

Status codes

Return the status that matches the outcome. A creation is 201, not 200; a successful operation with nothing to return is 204. Set a fixed status with @ResponseStatus, or return a ResponseEntity when you need control over headers such as the Location of a newly created resource.

SituationStatus
Read succeeded200
Resource created201
Succeeded, nothing to return204
Invalid client input400
Not authenticated401
Authenticated but forbidden403
Resource does not exist404
Unhandled server fault500

Real World Example: Designing an Order Resource

A team designs the HTTP surface for orders. The operations are: list orders with paging, fetch one order, create an order, and cancel an order. Three map cleanly onto standard verbs. Cancel is the interesting one: cancelling is a state transition, not a deletion -- the order still exists afterwards, cancelled -- so it is modelled as a POST to a sub-resource, not a DELETE. The team wires the four endpoints, but the fetch-one handler returns the Order entity directly, which is where the design goes wrong. This program models the routes and the leak.

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    @GetMapping                       List<OrderResponse> list(...) { ... }   // 200
    @GetMapping("/{id}")              Order findOne(@PathVariable Long id) { ... } // 200 -- returns ENTITY
    @PostMapping                      OrderResponse create(...) { ... }       // 201
    @PostMapping("/{id}/cancel")      OrderResponse cancel(@PathVariable Long id) { ... } // 200
}

Output:

operation   method path                       status
----------------------------------------------------
list        GET    /api/orders                200
fetch one   GET    /api/orders/{id}           200
create      POST   /api/orders                201
cancel      POST   /api/orders/{id}/cancel    200
----------------------------------------------------
endpoints       : 4
entity fields   : 6
response fields : 3
leaked fields   : 3
returns entity  : yes (flaw)

The routing table is sound. List and fetch-one are GETs, create is a POST returning 201, and cancel is a POST to /api/orders/{id}/cancel returning 200 -- the sub-resource verb correctly expresses that the order is being transitioned, not removed, so a later fetch of the same id still succeeds and shows it cancelled. A client can read this table and know exactly how to drive the resource.

The defect is the fetch-one handler returning the Order entity. The entity has six fields, but the API should expose only three; returning the entity serialises all six, leaking the cost breakdown, an internal reference, and an audit trail to every client. Worse, the leak is silent -- the endpoint works, the tests that check id and total pass, and nobody notices the extra fields until a security review or, more likely, until a client starts depending on one of them and a schema change breaks them.

The limits of this model are worth stating. It counts leaked fields as a static difference between two field lists, but the real hazard is dynamic: a JPA entity often has lazy associations, and serialising one after the transaction has closed throws a lazy-initialisation error, turning the leak into an intermittent 500 that the field count never captures. It also treats the route table as the whole contract, ignoring that response shape, error format, and pagination metadata are equally part of what clients depend on. The real design flaw, though, is structural and the model names it plainly: returning an entity couples your public API to your database schema, so every column you add is exposed by default and every column you rename is a breaking change -- the projection to a response type is not a nicety but the boundary that lets the schema and the API evolve independently.


Common Mistakes

  1. Returning a JPA entity from a handler. Every field of the entity serialises, leaking internal columns and coupling the API to the database schema, and a lazy association touched after the transaction closes throws a lazy-initialisation error. Return a dedicated response record that exposes only the intended fields.
  1. Confusing 404 and 405. A 404 means the path matches no route at all; a 405 means the path matches but not for the method you used. Returning the wrong one, or reading it wrong while debugging, sends you looking for a missing route when the route exists but lacks your method.
  1. Leaving optional query parameters without a default. An absent parameter with no default binds to null, and using it unguarded becomes a NullPointerException and a 500. Give optional parameters a defaultValue so an absent value is a valid default, not a crash.
  1. Using GET for an operation that changes state. GET is assumed safe and repeatable by browsers, proxies, and crawlers, which may replay it. Anything that mutates state must use POST, PUT, PATCH, or DELETE, never GET.
  1. Modelling a state transition as a DELETE. Cancelling, archiving, or approving an order does not remove it, so DELETE is the wrong verb. Model the transition as a POST to a sub-resource such as /{id}/cancel, leaving the resource retrievable afterwards.
  1. Returning 200 for a creation. A successful create should return 201 with a Location header pointing at the new resource. Returning a bare 200 loses that information and misrepresents what happened.
  1. Putting the base path on every method instead of the class. Repeating /api/products on each handler is noisy and drifts out of sync. Set the shared prefix once with a class-level @RequestMapping and keep the method mappings short.
  1. Accepting an entity as the request body. Binding @RequestBody to a persistence entity lets a client set fields it should never control -- an id, an internal status, an audit field. Bind to a dedicated request record that contains only the fields the client is allowed to send.
  1. Relying on Jackson to hide sensitive fields with annotations. Marking individual fields to be ignored is opt-out security: the next field someone adds is exposed until they remember to annotate it. A response record is opt-in -- only what you list is serialised.

Best Practices

  • Return a dedicated response type from every handler and bind request bodies to dedicated request types, so the API contract is stated explicitly and never leaks or accepts fields by default.
  • Match the HTTP method to the intent: GET for safe reads, POST for creation and state transitions, PUT and PATCH for updates, DELETE only for genuine removal.
  • Model state transitions as POSTs to sub-resources rather than as deletions, so the resource remains retrievable in its new state.
  • Return the status that fits the outcome -- 201 with a Location for creation, 204 for a successful operation with no body -- rather than a blanket 200.
  • Give every optional query parameter a sensible default so an absent value is handled, not turned into a null-pointer 500.
  • Set the shared path prefix once with a class-level mapping and keep each handler's path to the part that distinguishes it.
  • Keep a clear boundary between the persistence model and the API model, mapping between them explicitly, so the database schema and the public contract can evolve independently.
  • Understand the difference between 404 and 405 and let the framework return them correctly, so clients get an accurate signal about whether a resource or only a method is missing.

Practice Exercises

  1. Design the endpoints for an order resource supporting list-with-paging, fetch-one, create, and cancel. Give the verb, path, and success status for each, and justify why cancel is not a DELETE.
  1. A handler declares @RequestParam(required = false) String sort and uses it without a null check. Describe the request that breaks it, the status the client sees, and the one-line change that prevents it.
  1. A request to DELETE /api/products/42 returns 405 while GET /api/products/42 returns 200. Explain what this tells you about the registered routes and what you would add to support deletion.
  1. A colleague returns the Customer entity from a fetch-one endpoint. List three concrete problems this causes and rewrite the return type as a response record exposing only id, name, and email.