🎯 What you will learn

REST maps CRUD operations to standard HTTP verbs. Spring Boot makes this mapping explicit and type-safe. By the end of this lesson you will:

  • Map GET, POST, PUT, DELETE to Java methods using shortcut annotations
  • Extract path segments with @PathVariable and query strings with @RequestParam
  • Deserialise a JSON request body with @RequestBody
  • Control the HTTP status code and headers independently using ResponseEntity
  • Return 200, 201, 204, and 404 correctly for different operations
  • Set a common URL prefix for a controller with @RequestMapping
💼 Interview reality: "What is the difference between @PathVariable and @RequestParam?" and "What status code should a POST return?" appear in virtually every Spring Boot backend interview. Knowing REST semantics — not just annotations — separates senior from junior candidates.

🌍 Real-world scenario

🌍
NairaSwift (Lagos, Nigeria)
Full CRUD for cross-border transfers

Samuel needs four endpoints — list, get-one, create, delete — for the transfers resource. Each maps cleanly to a standard HTTP verb, returns JSON, and uses @PathVariable / @RequestBody to bind data.

🗺️ Block 1 — Full CRUD controller

All four HTTP verbs live in one controller class. @RequestMapping at class level sets the base path; individual method annotations append to it.

curl -s -u samuel:pass123 http://localhost:8765/api/transfers
TransferController.javaLesson 20 · GET, POST, DELETE mappings
verified output
[ { "id": 1001, "fromAccount": "NS-100001", "toAccount": "NS-100002", "amountNgn": 25000.0, "currency": "NGN", "status": "COMPLETED", "createdAt": "2026-04-26T18:37:23.205336" }, { "id": 1002, "fromAccount": "NS-100003", "toAccount": "NS-100004", "amountNgn": 150000.0, "currency": "NGN", "status": "COMPLETED", "createdAt": "2026-04-26T20:07:23.205359" } ]

ResponseEntity explained: ResponseEntity.ok(body) → 200, ResponseEntity.notFound().build() → 404, ResponseEntity.status(201).body(x) → 201. It decouples HTTP semantics from your business logic.

🔍 Block 2 — GET by ID + 404 handling

@PathVariable binds a URI template variable to a method parameter. When the resource is not found, returning ResponseEntity.notFound().build() sends a proper HTTP 404 instead of throwing an exception.

curl -s -u samuel:pass123 http://localhost:8765/api/transfers/1001
TransferController.javaLesson 20 · GET by id + 404 path
verified output
{ "id": 1001, "fromAccount": "NS-100001", "toAccount": "NS-100002", "amountNgn": 25000.0, "currency": "NGN", "status": "COMPLETED", "createdAt": "2026-04-26T18:37:23.205336" }

✉️ Block 3 — POST create transfer

@RequestBody tells Jackson to deserialise the HTTP request body JSON into a Java object. The response should be 201 Created with the persisted resource in the body — not 200 OK.

curl -s -u samuel:pass123 -X POST http://localhost:8765/api/transfers -H "Content-Type: application/json" -d '{"fromAccount":"NS-100005","toAccount":"NS-100006","amountNgn":75000,"currency":"NGN"}'
TransferController.javaLesson 20 · POST body, 201 Created
verified output
{ "id": 1003, "fromAccount": "NS-100005", "toAccount": "NS-100006", "amountNgn": 75000.0, "currency": "NGN", "status": "PENDING", "createdAt": "2026-04-26T20:37:42.925523" }

Content-Type matters: Without -H "Content-Type: application/json" Spring Boot will reject the body with 415 Unsupported Media Type. Always set it explicitly when sending a JSON body.

📋 HTTP verb → Spring annotation mapping

HTTP VerbSpring AnnotationTypical StatusUse case
GET@GetMapping200 OKRead one or many
POST@PostMapping201 CreatedCreate new resource
PUT@PutMapping200 OKReplace entire resource
PATCH@PatchMapping200 OKPartial update
DELETE@DeleteMapping204 No ContentRemove resource

🎤 Interview Q&A

EasyWhat is the difference between @RequestParam and @PathVariable?
+

@PathVariable extracts from the URL path template (/transfers/{id}), while @RequestParam reads query-string parameters (/transfers?status=PENDING). Use @PathVariable for resource identity and @RequestParam for filtering, sorting, or pagination.

EasyWhy return ResponseEntity instead of the object directly?
+

ResponseEntity gives you control over the HTTP status code and headers. Returning the object directly always sends 200 OK, even if you intended 201 or 404. For RESTful APIs following HTTP semantics correctly, ResponseEntity is the right choice.

MediumHow do you add custom response headers in Spring MVC?
+

Return ResponseEntity and call .header("X-Trace-Id", traceId) on the builder, or inject HttpServletResponse and call response.setHeader(). Example: ResponseEntity.ok().header("X-Request-Id", uuid).body(data).

MediumWhat is the difference between @PutMapping and @PatchMapping?
+

PUT replaces the entire resource — send all fields. PATCH partially updates — send only changed fields. Spring Boot supports both via @PutMapping / @PatchMapping. For partial updates in Java, use a DTO with nullable fields or Optional wrappers to distinguish "not sent" from "set to null".

HardHow does Spring's DispatcherServlet route an incoming HTTP request to the correct controller method?
+

The DispatcherServlet consults a list of HandlerMappings (RequestMappingHandlerMapping being the most common). It matches the request URL, HTTP method, and consumes/produces content-type to find the best HandlerMethod. Then HandlerAdapters convert arguments (@PathVariable, @RequestBody etc.) before invoking the method. The return value is processed by HttpMessageConverter (Jackson for JSON) and written to the response.

📝 Quiz — 5 questions

Question 1 of 5
Which annotation maps a method to HTTP GET?
Question 2 of 5
How do you extract {id} from /api/transfers/42?
Question 3 of 5
What HTTP status code should a successful resource creation return?
Question 4 of 5
What does ResponseEntity.noContent().build() return?
Question 5 of 5
What annotation marks the base URL for all methods in a controller?
0
/ 5
Quiz complete!

Next: Dependency Injection and Beans →

⚠️ Common mistakes

Using @RequestParam for path segments
/transfers/{id} requires @PathVariable Long id, not @RequestParam. @RequestParam is for ?id=42 query-string parameters.
Returning 200 for created resources
Always use ResponseEntity.status(201) for POST creation; returning the object directly gives 200 OK, which is semantically incorrect per REST conventions.
Not setting Content-Type on POST curl
Without -H "Content-Type: application/json" Spring Boot rejects the body with 415 Unsupported Media Type. Always set it when sending a JSON body.
Multiple @RequestMapping without distinct paths
Two methods with identical path+method cause AmbiguousHandlerMappingException at startup. Each combination of path + HTTP verb must be unique within a controller.

✅ Key takeaways

  • @GetMapping / @PostMapping / @PutMapping / @DeleteMapping map HTTP verbs
  • @PathVariable extracts URI segments; @RequestBody deserialises JSON
  • ResponseEntity controls status code, headers, and body independently
  • 200 OK for reads, 201 Created for POST, 204 No Content for DELETE
  • @RequestMapping at class level sets a common prefix for all routes
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

From routes to a full payments API

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →