← Learning Hub
Intermediate

A Full CRUD API with ResponseEntity

Let's build Create, Read, Update and Delete for products, with the right HTTP status codes. ResponseEntity lets you choose the status.

Most APIs are CRUD: create, read, update and delete records. Using the right HTTP methods and status codes makes your API predictable for any client - web, mobile or another server.

Example
@RestController
@RequestMapping("/api/products")
public class ProductController {

    record Product(long id, String name, int price) {}
    record ProductRequest(String name, int price) {}

    private final Map<Long, Product> store = new ConcurrentHashMap<>();
    private final AtomicLong nextId = new AtomicLong(1);

    @GetMapping
    public Collection<Product> all() {
        return store.values();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Product> one(@PathVariable long id) {
        Product p = store.get(id);
        return p == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(p);
    }

    @PostMapping
    public ResponseEntity<Product> create(@RequestBody ProductRequest req) {
        Product p = new Product(nextId.getAndIncrement(), req.name(), req.price());
        store.put(p.id(), p);
        return ResponseEntity.created(URI.create("/api/products/" + p.id())).body(p);   // 201
    }

    @PutMapping("/{id}")
    public ResponseEntity<Product> update(@PathVariable long id, @RequestBody ProductRequest req) {
        if (!store.containsKey(id)) return ResponseEntity.notFound().build();
        Product p = new Product(id, req.name(), req.price());
        store.put(id, p);
        return ResponseEntity.ok(p);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable long id) {
        return store.remove(id) == null ? ResponseEntity.notFound().build()
                                        : ResponseEntity.noContent().build();     // 204
    }
}

Calling it

Example
curl -X POST http://localhost:8080/api/products \
     -H "Content-Type: application/json" \
     -d '{"name":"Kettle","price":1299}'
# 201  {"id":1,"name":"Kettle","price":1299}

curl -X PUT http://localhost:8080/api/products/1 \
     -H "Content-Type: application/json" -d '{"name":"Kettle","price":1199}'
# 200  {"id":1,"name":"Kettle","price":1199}

curl -i http://localhost:8080/api/products/9      # -i shows the status line
# HTTP/1.1 404

curl -X DELETE http://localhost:8080/api/products/1
# 204 (no body)
  • @RequestBody turns the request's JSON into a Java object (here a record)
  • Imports: org.springframework.http.ResponseEntity, java.net.URI, java.util.*, java.util.concurrent.*, java.util.concurrent.atomic.AtomicLong
  • ConcurrentHashMap and AtomicLong are safe when many requests arrive at once
Data here lives in memory and disappears on restart. Lesson 8 saves it in a database with Spring Data JPA.
Key points
  • Map POST, GET, PUT/PATCH, DELETE to CRUD.
  • ResponseEntity sets status codes.
  • @RequestBody reads JSON into objects.

📝 Test yourself

1. Which status should a successful POST that creates something return?
2. What does @RequestBody do?
3. Fill in the method that builds a 404 reply:
return ResponseEntity.().build();