@GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite staff must list, read, add, change and remove products from an app. Each action needs its own HTTP method and URL, and the server must refuse every wrong combination.
Mapping list, get, create, replace, update and delete
A mapping annotation ties one HTTP method and one path to one Java method. The five are @GetMapping, @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping; each is a short form of @RequestMapping(method = ...).
A product screen needs six actions: list, read one, create, replace, change some fields and delete. The example gives each action its own annotation, path and Java method.
Example 1 · Product.java, request records and ProductService.java
Runs in: the rest-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.product;
import java.math.BigDecimal;
public record Product(long id, String sku, String name, long categoryId, String categoryName, BigDecimal price, int stock, boolean isActive) {}
package com.shoplite.lab.product;
import java.math.BigDecimal;
public record CreateProductRequest(String sku, String name, Long categoryId, BigDecimal price, Integer stock, Boolean isActive) {}
package com.shoplite.lab.product;
import java.math.BigDecimal;
public record UpdateProductRequest(String sku, String name, Long categoryId, BigDecimal price, Integer stock, Boolean isActive) {}
package com.shoplite.lab.product;
import java.math.BigDecimal;
public record PatchProductRequest(String sku, String name, Long categoryId, BigDecimal price, Integer stock, Boolean isActive) {}
package com.shoplite.lab.product;
import java.math.BigDecimal;import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
@Servicepublic class ProductService {
private static final Map<Long, String> CATEGORY_NAMES = Map.of( 1L, "Electronics", 2L, "Mobiles", 3L, "Laptops", 4L, "Accessories", 5L, "Books", 6L, "Fashion", 7L, "Home & Kitchen");
private final Map<Long, Product> products = new ConcurrentHashMap<>(); private final AtomicLong nextId = new AtomicLong(16); // seed ids end at 15
public ProductService() { add(new Product(1, "MOB-RN13", "Redmi Note 13 5G", 2, "Mobiles", new BigDecimal("17999.00"), 40, true)); add(new Product(2, "MOB-GM35", "Samsung Galaxy M35", 2, "Mobiles", new BigDecimal("19999.00"), 25, true)); add(new Product(3, "MOB-IP15", "iPhone 15 128GB", 2, "Mobiles", new BigDecimal("69900.00"), 8, true)); add(new Product(6, "ACC-AD141", "boAt Airdopes 141", 4, "Accessories", new BigDecimal("1299.00"), 120, true)); add(new Product(9, "BK-CLEAN", "Clean Code", 5, "Books", new BigDecimal("499.00"), 30, true)); }
public List<Product> findAll() { return products.values().stream() .sorted(Comparator.comparingLong(Product::id)) .toList(); }
public Optional<Product> findById(long id) { return Optional.ofNullable(products.get(id)); }
public Product create(CreateProductRequest request) { long id = nextId.getAndIncrement(); int stock = request.stock() == null ? 0 : request.stock(); boolean active = request.isActive() == null || request.isActive(); Product product = new Product(id, request.sku(), request.name(), request.categoryId(), CATEGORY_NAMES.get(request.categoryId()), request.price(), stock, active); return add(product); }
public Optional<Product> replace(long id, UpdateProductRequest request) { Product updated = products.computeIfPresent(id, (key, old) -> new Product(id, request.sku(), request.name(), request.categoryId(), CATEGORY_NAMES.get(request.categoryId()), request.price(), request.stock(), request.isActive())); return Optional.ofNullable(updated); }
public Optional<Product> patch(long id, PatchProductRequest request) { Product updated = products.computeIfPresent(id, (key, old) -> { long categoryId = request.categoryId() != null ? request.categoryId() : old.categoryId(); return new Product(id, request.sku() != null ? request.sku() : old.sku(), request.name() != null ? request.name() : old.name(), categoryId, CATEGORY_NAMES.get(categoryId), request.price() != null ? request.price() : old.price(), request.stock() != null ? request.stock() : old.stock(), request.isActive() != null ? request.isActive() : old.isActive()); }); return Optional.ofNullable(updated); }
public boolean delete(long id) { return products.remove(id) != null; }
private Product add(Product product) { products.put(product.id(), product); return product; }}(no output: these classes are used by the controller in Example 2)
What this code does
Producthas exactly the fields of the ShopLite contract. For now the stored record is also what the API returns; the Request and response DTOs lesson separates the two.ProductServicekeeps five seed products with their real ids (1, 2, 3, 6, 9) in aConcurrentHashMap, and new ids start at 16 like the database.ConcurrentHashMapandAtomicLongstay correct when many requests arrive at once; the In-memory repository lesson explains why.replaceandpatchusecomputeIfPresent: it changes the entry only if the id exists and returnsnullotherwise, which becomes an emptyOptional.
Example 2 · src/main/java/com/shoplite/lab/product/ProductController.java
Runs in: the rest-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.product;
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.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseStatus;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping(path = "/api/v1/products", produces = MediaType.APPLICATION_JSON_VALUE)public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) { this.productService = productService; }
@GetMapping public List<Product> list() { return productService.findAll(); }
@GetMapping("/{id}") public ResponseEntity<Product> get(@PathVariable long id) { return ResponseEntity.of(productService.findById(id)); }
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.CREATED) public Product create(@RequestBody CreateProductRequest request) { return productService.create(request); }
@PutMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Product> replace(@PathVariable long id, @RequestBody UpdateProductRequest request) { return ResponseEntity.of(productService.replace(id, request)); }
@PatchMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Product> patch(@PathVariable long id, @RequestBody PatchProductRequest request) { return ResponseEntity.of(productService.patch(id, request)); }
@DeleteMapping("/{id}") public ResponseEntity<Void> delete(@PathVariable long id) { if (productService.delete(id)) { return ResponseEntity.noContent().build(); } return ResponseEntity.notFound().build(); }}(no output: Example 3 calls each mapping with curl)
What this code does
- Six methods, six mappings, one base path. The comment next to each mapping shows the request it answers.
@ResponseStatus(HttpStatus.CREATED)makes a create answer 201 instead of 200.ResponseEntity.of(optional)answers 200 with the product, or 404 when theOptionalis empty. The ResponseEntity lesson covers both.- The controller only translates HTTP into service calls. It never touches the map of products itself.
Example 3 · Calling list, get, create and delete
Runs in: the rest-lab practice project (Spring Boot 4.1)
curl http://localhost:8080/api/v1/productscurl http://localhost:8080/api/v1/products/3curl -i http://localhost:8080/api/v1/products/99curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'curl -i -X DELETE http://localhost:8080/api/v1/products/16curl -i -X DELETE http://localhost:8080/api/v1/products/16$ curl http://localhost:8080/api/v1/products
[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true},{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true},{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Accessories","price":1299.00,"stock":120,"isActive":true},{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":499.00,"stock":30,"isActive":true}]
$ curl http://localhost:8080/api/v1/products/3
{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true}
$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404
Content-Length: 0
Date: Fri, 16 Oct 2026 04:46:15 GMT
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
HTTP/1.1 201
Content-Type: application/json
Content-Length: 150
Date: Fri, 16 Oct 2026 04:46:16 GMT
{"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}
$ curl -i -X DELETE http://localhost:8080/api/v1/products/16
HTTP/1.1 204
Date: Fri, 16 Oct 2026 04:46:16 GMT
$ curl -i -X DELETE http://localhost:8080/api/v1/products/16
HTTP/1.1 404
Content-Length: 0
Date: Fri, 16 Oct 2026 04:46:16 GMTWhat this code does
- GET lists and reads; product 99 does not exist, so the answer is 404 with an empty body for now (the Exception handling module adds the contract's Problem Details body).
- POST creates product 16 and answers 201 with the new product, including
categoryNameand the defaultedisActive: true. - The first DELETE answers 204 (done, no body); the second finds nothing and answers 404.
Together with the class base path, the annotations give a resource its six standard operations:
GET /api/v1/productslists andGET /api/v1/products/{id}reads onePOST /api/v1/productscreates, and the server picks the new idPUT /api/v1/products/{id}replaces andPATCH /api/v1/products/{id}changes some fieldsDELETE /api/v1/products/{id}deletes
{id} is a path variable: @PathVariable long id receives the number from the URL. @RequestBody turns the JSON body into a record. Both have their own lessons next. The controller only maps HTTP to Java; the data lives in a ProductService, a temporary in-memory store that a later module moves to MySQL.
Find the bug
Find the mapping bug
Each snippet has one wrong mapping line. Tap it, then check the fix.
Delete a product by its id.
Round 1 of 3Ambiguous mapping. Cannot map 'productController' method .... Each method + path pair must be unique.PUT replaces, PATCH changes some fields
PUT sends the complete new version of a resource, every field, and the server replaces what it had. PATCH sends only the fields to change, and the server keeps the rest.
A price change should not force the client to send all six product fields again. The example shows a PUT with every field, a PATCH with one field, and a PUT that forgets fields.
Example 4 · PUT, PATCH and a PUT with missing fields
Runs in: the rest-lab practice project (Spring Boot 4.1)
curl -X PUT http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"sku":"ACC-AD141","name":"boAt Airdopes 141 ANC","categoryId":4,"price":1499.00,"stock":100,"isActive":true}'curl -X PATCH http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"price":1199.00}'curl -i -X PUT http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"price":999.00}'$ curl -X PUT http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"sku":"ACC-AD141","name":"boAt Airdopes 141 ANC","categoryId":4,"price":1499.00,"stock":100,"isActive":true}'
{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141 ANC","categoryId":4,"categoryName":"Accessories","price":1499.00,"stock":100,"isActive":true}
$ curl -X PATCH http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"price":1199.00}'
{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141 ANC","categoryId":4,"categoryName":"Accessories","price":1199.00,"stock":100,"isActive":true}
$ curl -i -X PUT http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"price":999.00}'
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:46:17 GMT
Connection: close
{"timestamp":"2026-10-16T04:46:17.241Z","status":500,"error":"Internal Server Error","path":"/api/v1/products/6"}
Server log:
2026-10-16T10:16:17.217+05:30 ERROR 3052 --- [rest-lab] [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.NullPointerException: Cannot invoke "java.lang.Long.longValue()" because the return value of "com.shoplite.lab.product.UpdateProductRequest.categoryId()" is null] with root causeWhat this code does
- PUT sent all six fields and replaced product 6: new name, price and stock. PATCH sent only
price, so the name and stock from the PUT stayed. - The last PUT sent only
price. The service tried to unbox the missingcategoryIdand failed, so the client got a 500 and the log shows theNullPointerException. Product 6 is unchanged, because the exception happened before the map was updated. - A 500 is the wrong answer for a client mistake. The Validation module checks the body first and answers 400 with the missing fields.
The ShopLite contract has both for products: PUT needs all six fields, PATCH takes any non-empty subset. So there are two request records with the same fields. UpdateProductRequest (PUT) will mark every field required in the Validation module. PatchProductRequest keeps them optional, and the service treats a field that was left out (null) as "keep the old value".
A PUT that leaves fields out is a client bug. Right now it ends in a 500, because the service unboxes a null Long. The Validation module turns it into a clear 400 that names the missing fields.
405 Method Not Allowed
405 Method Not Allowed means the path exists, but not with the HTTP method the client used. Spring adds an Allow header that lists the methods that do work.
A client sends DELETE to the product list URL, which only allows GET and POST. The example shows what comes back.
Example 5 · Wrong method: 405 with the Allow header
Runs in: the rest-lab practice project (Spring Boot 4.1)
curl -i -X DELETE http://localhost:8080/api/v1/productscurl -i -X POST http://localhost:8080/api/v1/products/3 -H "Content-Type: application/json" -d '{}'$ curl -i -X DELETE http://localhost:8080/api/v1/products
HTTP/1.1 405
Allow: POST, GET
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:46:17 GMT
{"timestamp":"2026-10-16T04:46:17.819Z","status":405,"error":"Method Not Allowed","path":"/api/v1/products"}
$ curl -i -X POST http://localhost:8080/api/v1/products/3 -H "Content-Type: application/json" -d '{}'
HTTP/1.1 405
Allow: PATCH, PUT, DELETE, GET
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:46:18 GMT
{"timestamp":"2026-10-16T04:46:18.115Z","status":405,"error":"Method Not Allowed","path":"/api/v1/products/3"}
Server log:
2026-10-16T10:16:17.818+05:30 WARN 3052 --- [rest-lab] [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'DELETE' is not supported]
2026-10-16T10:16:18.113+05:30 WARN 3052 --- [rest-lab] [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' is not supported]What this code does
- The collection URL has GET and POST methods, so
DELETEgets 405 andAllow: POST, GET. The item URL has PATCH, PUT, DELETE and GET, so aPOSTthere is refused the same way. - The
Allowheader tells the client what would work; the order of the names does not matter. - The log names the exception once per request. It is a
WARN, not anERROR, because the client made the mistake, not the server.
A 405 is different from a 404. A 404 says "no such URL"; a 405 says "right URL, wrong method". It usually means the client used the wrong method or the wrong URL: a delete sent to the collection, or a create sent to an item URL.
Spring Boot also writes one WARN line per 405 in the server log with the exception name, HttpRequestMethodNotSupportedException. Read the log when a client reports an error you cannot see.
Predict the output
Predict the status
The product controller has GET and POST on the list URL. What does each request get?
Round 1 of 2
DELETE /api/v1/products (no id)
consumes and produces: 415 and 406
consumes lists the request Content-Type values a method accepts, and produces lists the response types it can send. A body of another type gets 415, and an Accept header the server cannot satisfy gets 406.
The create endpoint should accept only JSON bodies. The example sends a plain-text body, and then asks for XML.
Example 6 · Wrong body type (415) and wrong Accept (406)
Runs in: the rest-lab practice project (Spring Boot 4.1)
curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: text/plain" -d 'Zebronics Keyboard'curl -i -X POST http://localhost:8080/api/v1/products -d 'sku=ACC-KB100'curl -i -H "Accept: application/xml" http://localhost:8080/api/v1/products/3$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: text/plain" -d 'Zebronics Keyboard'
HTTP/1.1 415
Accept: application/json
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:46:18 GMT
{"timestamp":"2026-10-16T04:46:18.315Z","status":415,"error":"Unsupported Media Type","path":"/api/v1/products"}
$ curl -i -X POST http://localhost:8080/api/v1/products -d 'sku=ACC-KB100'
HTTP/1.1 415
Accept: application/json
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:46:18 GMT
{"timestamp":"2026-10-16T04:46:18.438Z","status":415,"error":"Unsupported Media Type","path":"/api/v1/products"}
$ curl -i -H "Accept: application/xml" http://localhost:8080/api/v1/products/3
HTTP/1.1 406
Accept: application/json
Content-Length: 0
Date: Fri, 16 Oct 2026 04:46:18 GMT
Server log:
WARN ... Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'text/plain' is not supported]
WARN ... Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'application/x-www-form-urlencoded' is not supported]
WARN ... Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: No acceptable representation]What this code does
- A
text/plainbody and a body with noContent-Typeat all both get 415.curl -dwithout-Hsendsapplication/x-www-form-urlencoded, the type of an HTML form, which is the most common cause of a 415 while testing. - The 415 response carries
Accept: application/json: the typeconsumesasks for. Fix the request with-H "Content-Type: application/json", or use--json, which sets it for you. - Asking for XML gets 406, because
produceson the class allows only JSON.
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) accepts only JSON bodies, and produces = MediaType.APPLICATION_JSON_VALUE on the class says every method answers in JSON. @RequestBody alone already refuses bodies Jackson cannot read, but consumes makes the rule visible on the method and stops a wrong type before any reading starts. The ShopLite contract requires application/json bodies, so every write method says so.
A body with another type, such as text/plain or the form data that curl -d sends by default, gets 415 Unsupported Media Type, with an Accept header naming the type the server wants. A client whose Accept header asks only for a type the server cannot produce, such as application/xml, gets 406 Not Acceptable.
Safe and idempotent methods, and retries
An idempotent method leaves the same final state whether it runs once or many times: GET, PUT and DELETE are. POST is not, and PATCH is not guaranteed to be. A safe method (GET, HEAD, OPTIONS) never changes data.
A request times out on a slow mobile network, and the app cannot know whether the server got it. Can it just send the request again? The run below sends each write twice.
curl -s -X POST http://localhost:8080/api/v1/products --json '{"sku":"BK-ATOMIC","name":"Atomic Habits","categoryId":5,"price":399.00,"stock":50}' # twicecurl -s -X PUT http://localhost:8080/api/v1/products/9 --json '{"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"price":449.00,"stock":30,"isActive":true}' # twicecurl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://localhost:8080/api/v1/products/17 # twice{"id":17,"sku":"BK-ATOMIC","name":"Atomic Habits","categoryId":5,"categoryName":"Books","price":399.00,"stock":50,"isActive":true}
{"id":18,"sku":"BK-ATOMIC","name":"Atomic Habits","categoryId":5,"categoryName":"Books","price":399.00,"stock":50,"isActive":true}
{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":449.00,"stock":30,"isActive":true}
{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":449.00,"stock":30,"isActive":true}
204
404The answer depends on the method. A safe or idempotent request can simply be sent again. A repeated POST creates a second order or a second product, and a repeated "add 5 to stock" PATCH adds 10.
So never change data in a GET handler, and keep PUT a real replacement.
Next step
Check your understanding
12 quick questions