Practice: REST controllers
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most controller bugs are small: a wrong method, a wrong status code, an entity in the body. This page builds a coupon API from a spec, fixes a weak draft and predicts curl answers.
From a short API description to endpoints
The coupon API: list all coupons; read one by code (404 if missing); create (201 with Location, 409 for a duplicate code); patch (200 or 404); delete (204 or 404). The example builds all five.
Example 1 · The coupon API built from the spec
Runs in: the rest-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.coupon;
public record CouponResponse(String code, int percentOff, boolean active) {}
package com.shoplite.lab.coupon;
public record CreateCouponRequest(String code, Integer percentOff, Boolean active) {}
package com.shoplite.lab.coupon;
public record PatchCouponRequest(Integer percentOff, Boolean active) {}
package com.shoplite.lab.coupon;
import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Service;
// Temporary in-memory store for the lab@Servicepublic class CouponService {
private final Map<String, CouponResponse> coupons = new ConcurrentHashMap<>(Map.of( "FEST10", new CouponResponse("FEST10", 10, true), "DIWALI25", new CouponResponse("DIWALI25", 25, false)));
public List<CouponResponse> findAll() { return coupons.values().stream() .sorted(Comparator.comparing(CouponResponse::code)) .toList(); }
public Optional<CouponResponse> find(String code) { return Optional.ofNullable(coupons.get(code)); }
// Empty when the code is already taken public Optional<CouponResponse> create(CreateCouponRequest request) { CouponResponse coupon = new CouponResponse(request.code(), request.percentOff(), request.active() == null || request.active()); CouponResponse before = coupons.putIfAbsent(coupon.code(), coupon); return before == null ? Optional.of(coupon) : Optional.empty(); }
public Optional<CouponResponse> patch(String code, PatchCouponRequest request) { return Optional.ofNullable(coupons.computeIfPresent(code, (key, old) -> new CouponResponse(code, request.percentOff() != null ? request.percentOff() : old.percentOff(), request.active() != null ? request.active() : old.active()))); }
public boolean delete(String code) { return coupons.remove(code) != null; }}
package com.shoplite.lab.coupon;
import java.net.URI;import java.util.List;
import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PatchMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController@RequestMapping(path = "/lab/coupons", produces = MediaType.APPLICATION_JSON_VALUE)public class CouponController {
private final CouponService couponService;
public CouponController(CouponService couponService) { this.couponService = couponService; }
@GetMapping public List<CouponResponse> list() { return couponService.findAll(); }
@GetMapping("/{code}") public ResponseEntity<CouponResponse> get(@PathVariable String code) { return ResponseEntity.of(couponService.find(code)); }
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<CouponResponse> create(@RequestBody CreateCouponRequest request) { return couponService.create(request) .map(created -> { URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{code}").buildAndExpand(created.code()).toUri(); return ResponseEntity.created(location).body(created); }) .orElseGet(() -> ResponseEntity.status(HttpStatus.CONFLICT).build()); // code taken }
@PatchMapping(path = "/{code}", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<CouponResponse> patch(@PathVariable String code, @RequestBody PatchCouponRequest request) { return ResponseEntity.of(couponService.patch(code, request)); }
@DeleteMapping("/{code}") public ResponseEntity<Void> delete(@PathVariable String code) { return couponService.delete(code) ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build(); }}$ curl http://localhost:8080/lab/coupons
[{"code":"DIWALI25","percentOff":25,"active":false},{"code":"FEST10","percentOff":10,"active":true}]
$ curl -i -X POST http://localhost:8080/lab/coupons --json '{"code":"NEW50","percentOff":50}'
HTTP/1.1 201
Location: http://localhost:8080/lab/coupons/NEW50
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:04:11 GMT
{"code":"NEW50","percentOff":50,"active":true}
$ curl -i -X POST http://localhost:8080/lab/coupons --json '{"code":"FEST10","percentOff":15}'
HTTP/1.1 409
Content-Length: 0
Date: Fri, 16 Oct 2026 06:04:11 GMT
$ curl -X PATCH http://localhost:8080/lab/coupons/DIWALI25 --json '{"active":true}'
{"code":"DIWALI25","percentOff":25,"active":true}
$ curl -i -X DELETE http://localhost:8080/lab/coupons/NEW50
HTTP/1.1 204
Date: Fri, 16 Oct 2026 06:04:11 GMT
$ curl -i http://localhost:8080/lab/coupons/NEW50
HTTP/1.1 404
Content-Length: 0
Date: Fri, 16 Oct 2026 06:04:12 GMTWhat this code does
- Every spec row has one method, and every outcome its own code: 201 with Location, 409 for a taken code, 200 for the patch, 204 for the delete, then 404 for the deleted coupon.
putIfAbsentmakes "a code exists only once" safe even when two requests arrive together; the service reports a clash with an emptyOptional, and the controller turns it into 409.- The 409 has no body yet. The Exception handling module replaces these empty error answers with Problem Details bodies in one place.
The full spec for the lab's coupons:
GET /lab/coupons→ 200, all coupons sorted by code (a small list, so a bare array);GET /lab/coupons/{code}→ 200 or 404POST /lab/couponswithcode,percentOff,active?→ 201 + Location, or 409 when the code existsPATCH /lab/coupons/{code}withpercentOff?,active?→ 200 or 404DELETE /lab/coupons/{code}→ 204 or 404
A specification (spec) is the table of what an API promises: for each row a method, a URL, a body and the status codes. Turning it into code is four passes. First the records: one request record per kind of body, one response record. Then the mapping annotations and paths, with a class-level base path. Then the status of each outcome: ResponseEntity.of for found or 404, created(uri) for 201, noContent() for 204. Last, a curl or test call for every row. The service holds the data and the rules (a code can exist only once); the controller only maps outcomes to HTTP.
Fixing wrong status codes, mappings and DTOs
A weak draft of the coupon controller fails nearly every usual check. The example lists its six findings, with the fix for each.
Example 2 · OldCouponController.java: a draft with six findings
Runs in: the rest-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.coupon;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;
// A first draft with six review findings (lab only)@RestController@RequestMapping("/lab/old-coupons")public class OldCouponController {
private final CouponService couponService;
public OldCouponController(CouponService couponService) { this.couponService = couponService; }
@GetMapping("/getAll") public List<CouponResponse> getAll() { return couponService.findAll(); }
@GetMapping("/{code}") public CouponResponse get(@PathVariable String code) { return couponService.find(code).orElse(null); }
@PostMapping("/create") public CouponResponse create(@RequestBody CreateCouponRequest request) { return couponService.create(request).orElse(null); }
@PutMapping("/{code}") public CouponResponse changeDiscount(@PathVariable String code, @RequestParam int percentOff) { return couponService.patch(code, new PatchCouponRequest(percentOff, null)).orElse(null); }
@GetMapping("/delete/{code}") public String delete(@PathVariable String code) { couponService.delete(code); return "deleted"; }}$ curl -i http://localhost:8080/lab/old-coupons/XMAS5
HTTP/1.1 200
Content-Length: 0
Date: Fri, 16 Oct 2026 06:04:12 GMT
$ curl -i -X POST http://localhost:8080/lab/old-coupons/create --json '{"code":"FEST10","percentOff":15}'
HTTP/1.1 200
Content-Length: 0
Date: Fri, 16 Oct 2026 06:04:12 GMT
$ curl -i http://localhost:8080/lab/old-coupons/delete/XMAS5
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 7
Date: Fri, 16 Oct 2026 06:04:13 GMT
deletedWhat this code does
- Findings: (1) verbs in URLs (
/getAll,/create,/delete/...); (2) GET deletes; (3) a missing coupon is 200 with an empty body; (4) a duplicate code is 200 with an empty body; (5) create answers 200 without Location; (6) the discount change is a PUT that takes a query parameter instead of a PATCH with a JSON body. - The run proves the silent bugs: XMAS5 does not exist, yet every answer is 200, and "deleted" is printed for a coupon that was never there.
- Example 1 is the fixed version: same service, honest mappings and codes.
A review reads each method of a controller and asks the same questions. Is the URL a noun with the id in the path, without verbs such as /create or /getAll? Does the HTTP method match the operation? Is every outcome its own status code, never 200 for a failure? Does the body travel as JSON in a request record, not as query parameters?
The draft below passes none of these checks. Its worst bugs are the silent ones: a missing coupon answers 200 with an empty body, a duplicate code answers 200 too, and a GET deletes data, so a browser preview or a crawler can delete coupons. Fix in the order that protects data first: change the deleting GET into DELETE, then make each outcome honest (404, 409, 201 + Location, 204), then clean up the URLs and bodies.
Predicting the curl response
Predicting a response before running the request shows the gaps in your understanding. The example sends requests to a fresh lab and shows the real answers.
Example 3 · Predict, then run: requests to a fresh lab
Runs in: the rest-lab practice project (Spring Boot 4.1)
curl -i http://localhost:8080/api/v1/products/9curl -i http://localhost:8080/api/v1/products/7curl -i -X DELETE http://localhost:8080/api/v1/productscurl -i "http://localhost:8080/api/v1/products?categoryId=5&maxPrice=400"curl -i -X POST http://localhost:8080/api/v1/products --json '{"sku":"BK-ATOMIC","name":"Atomic Habits","categoryId":5,"price":399.00,"stock":1.5}'curl -i -X PUT http://localhost:8080/api/v1/products/9 -H "Content-Type: text/plain" -d 'x'(Date and transfer headers removed)
GET /api/v1/products/9
HTTP/1.1 200
Content-Type: application/json
{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":499.00,"stock":30,"isActive":true}
GET /api/v1/products/7
HTTP/1.1 404
DELETE /api/v1/products
HTTP/1.1 405
Allow: GET, POST
Content-Type: application/json
{"timestamp":"2026-10-16T06:04:13.901Z","status":405,"error":"Method Not Allowed","path":"/api/v1/products"}
GET /api/v1/products?categoryId=5&maxPrice=400
HTTP/1.1 200
Content-Type: application/json
{"content":[],"page":0,"size":20,"totalElements":0,"totalPages":0}
POST with "stock":1.5
HTTP/1.1 400
PUT /api/v1/products/9 with text/plain
HTTP/1.1 415
Accept: application/jsonWhat this code does
- Product 7 is not one of the lab's seed products, so 404. Books up to Rs 400 is an empty page (Clean Code costs 499), and an empty filter result is still 200.
- The DELETE stops at the method step (405), the PUT at the body-type step (415), and the POST at the JSON step:
1.5for a whole number is refused by the strict Jackson setting (400). None of them reaches the service. - This run shows
Allow: GET, POST; an earlier one showedPOST, GET. The order is not fixed.
Spring handles a request in a fixed order, and each step can stop it with its own status:
- Path: no mapping matches → 404 with the default error JSON
- Method: the path exists, the method does not → 405 with
Allow - Body type and conversion: wrong
Content-Type→ 415; path or query text that does not fit the type → 400; JSON that cannot become the record → 400 - Your method: the service answers, and your code picks 200, 201, 204, 404 or 409
Walk the list top to bottom for each request. The first step that fails decides the answer, and the service is never called. Remember the quieter rules too: unknown query parameters are ignored, an empty filter result is 200, and path values are case-sensitive.
Order of execution
Order the checks
Put Spring's checks in the order it runs them. The first failing step decides the answer.
Interview drill: the three classic comparisons
Three comparisons come up in almost every Spring interview. Answer each with a definition, one example and one consequence. The code below shows the three signatures.
@PutMapping("/{id}") ProductResponse replace(@PathVariable long id, @RequestBody UpdateProductRequest r)@PatchMapping("/{id}") ProductResponse patch(@PathVariable long id, @RequestBody PatchProductRequest r)@GetMapping PageResponse<ProductResponse> list(@RequestParam(defaultValue = "0") int page)The three answers:
- PUT vs PATCH: PUT sends the whole resource and replaces it; PATCH sends only the fields to change. PUT is idempotent; PATCH is not guaranteed to be.
- @PathVariable vs @RequestParam: the path names the resource (
/products/3); the query filters, sorts or pages a list (?categoryId=2&page=0), and is often optional. - @Controller vs @RestController:
@RestControlleradds@ResponseBody, so return values become the body (JSON); a plain@Controllerreturns view names for HTML pages.
Follow-ups usually go one step deeper: "what happens if a PUT leaves a field out?", "what does Spring answer for /products/abc?", "why does a @Controller method give 404?". The lessons of this module have the answers with real output.
Finish up
Mark complete & continue
Next: Mini project: ShopLite category endpoints