REST
REST is a style for designing web APIs where the URL names a thing and the HTTP method says what to do with it. GET /orders/42 reads an order, DELETE /orders/42 removes it.
Detailed Explanation
REST stands for Representational State Transfer. The name is heavy; the idea is light. Your system has resources — orders, customers, invoices. Each resource gets a stable URL. The client manipulates a resource by sending a representation of it, usually JSON, using the HTTP method that matches the intent.
It exists as a reaction to RPC-over-HTTP. Earlier Java services leaned on SOAP: an XML envelope posted to a single endpoint, with the operation name buried inside the body, described by a WSDL file, and consumed through generated stubs. Every call was a POST, so no proxy or cache could tell a read from a write. REST pushed that information back into the parts of HTTP that already carried it.
The practical rules are short. Use nouns in paths, not verbs: /orders/42/cancel is RPC wearing a REST costume, while POST /orders/42/cancellations or PATCH /orders/42 with a status field is resource-shaped. Use plural collection names. Nest only one level deep. Let the method carry the verb.
Statelessness is the constraint people skip and regret. Each request must carry everything the server needs, so no request depends on server memory of the previous one. In Java terms: prefer a bearer token in the Authorization header over an HttpSession. The moment you store conversation state in a session, your instances stop being interchangeable and you need sticky sessions or a shared session store.
In a Spring Boot 3 application you write REST with @RestController. Spring MVC maps the request to a method, Jackson turns the JSON body into your parameter object and your return value back into JSON, and a ResponseEntity gives you control over the status code and headers when the default 200 is wrong. Bean Validation (@Valid with jakarta.validation annotations) rejects bad input before your method body runs.
Richardson's maturity model is the usual interview framing. Level 0 is one endpoint for everything. Level 1 introduces separate resources. Level 2 uses HTTP methods and status codes correctly, which is where nearly all real APIs live and is a perfectly defensible place to stop. Level 3 adds hypermedia, where responses carry links to the next available actions; Spring HATEOAS implements it, and most teams decide the extra payload is not worth the client complexity.
REST costs you round trips. A screen needing a customer, their last five orders and each order's line items can turn into a dozen sequential calls, and mobile clients feel every one. The usual repairs are an ?include= or ?fields= parameter, a purpose-built composite endpoint, or moving that particular screen to GraphQL. It also costs you a versioning obligation: once an external client parses your JSON, renaming a field is a breaking change, so you add fields rather than rename them, and you version the path (/v1/orders) when you cannot avoid a break.
Code Examples
package com.example.orders;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.util.List;
// @RestController = @Controller + @ResponseBody: every return value is serialised
// into the response body by Jackson instead of being treated as a view name.
@RestController
@RequestMapping("/v1/orders") // shared prefix for every method below
public class OrderController {
private final OrderService service; // injected, and must be thread-safe: one controller serves all requests
public OrderController(OrderService service) { // constructor injection, no annotation needed
this.service = service;
}
// Records are ideal for request and response payloads: immutable and concise.
public record CreateOrder(@NotBlank String sku, @Min(1) int quantity) {}
public record OrderView(long id, String sku, int quantity, String status) {}
@GetMapping("/{id}") // GET /v1/orders/42
public OrderView get(@PathVariable long id) {
// Throwing here lets one @ExceptionHandler map "not found" to 404 for the whole app.
return service.findById(id).orElseThrow(() -> new OrderNotFoundException(id));
}
@GetMapping // GET /v1/orders?status=SHIPPED&page=0
public List<OrderView> list(@RequestParam(required = false) String status,
@RequestParam(defaultValue = "0") int page) {
// Filtering and paging belong in the query string, not in the path.
return service.search(status, page);
}
@PostMapping
public ResponseEntity<OrderView> create(@Valid @RequestBody CreateOrder body) {
// @Valid runs the constraint annotations above; a violation becomes 400 before this line.
OrderView created = service.create(body);
// 201 plus a Location header pointing at the new resource is the correct answer to a create.
return ResponseEntity.created(URI.create("/v1/orders/" + created.id())).body(created);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable long id) {
service.delete(id);
return ResponseEntity.noContent().build(); // 204: succeeded, nothing to send back
}
}curl -X POST https://api.example.com/v1/orders \
-H 'Content-Type: application/json' \
-d '{"sku":"KB-88","quantity":2}'
# HTTP/1.1 201 Created
# Location: /v1/orders/42
curl https://api.example.com/v1/orders/42 # 200 with the JSON body
curl -X DELETE https://api.example.com/v1/orders/42 # 204, empty bodyCommon Gotchas
Verbs in the path
`POST /getOrderById` and `POST /deleteOrder` work, but they discard everything HTTP gives you for free. Caches cannot cache the read, proxies cannot retry it safely, and a new engineer has to read your code to learn which endpoints mutate data.
Returning your JPA entities directly
a Hibernate entity serialised by Jackson drags in lazy associations, triggering extra queries mid-serialisation or a `LazyInitializationException` once the transaction has closed. It also welds your database schema to your public API, so a column rename becomes a client-breaking change. Map to a record first.
`PUT` replaces, `PATCH` modifies
a `PUT` with three fields on a resource that has ten is specified to blank the other seven. If you mean "change the status and leave everything else alone", that is `PATCH`.