Sub topic 1
REST and CRUD: mapping operations to HTTP
This chapter explains how the four CRUD operations (create, read, update, delete) map onto HTTP methods, URLs, and status codes. Every later chapter in this tutorial builds on that mapping. You will use it to design the book API that the rest of the tutorial implements.
Prerequisites
This chapter assumes you already know the following:
- Java basics: classes, records, interfaces, and annotations.
- HTTP basics: a request has a method, a URL, headers, and an optional body. A response has a status code, headers, and an optional body.
- JSON as a data format.
- Basic relational database ideas such as tables, rows, and primary keys.
You do not need any Spring knowledge yet. No code in this chapter has to run. The chapter is about design decisions that you will implement in later chapters.
What CRUD and REST mean
CRUD names the four basic things an application does with stored data: create, read, update, and delete. Almost every data-driven application is built from these four operations.
REST (Representational State Transfer) is a style for designing HTTP APIs. A REST API treats everything it exposes as a resource, which is a thing with an identity, such as a book. Clients do not call named procedures like createBook. Instead, they send a standard HTTP method to the URL of a resource, and the method says what to do.
Three ideas matter most for this tutorial:
- Resources are nouns in URLs. The URL names the thing. The method names the action.
- Representations are exchanged. The client and server pass a representation of the resource, usually JSON, rather than the database row itself.
- Requests are stateless. Each request carries everything the server needs. The server does not remember earlier requests from the same client.
In practice, most APIs called "REST" follow these conventions without implementing every constraint in the original REST dissertation. This tutorial uses the common, pragmatic form: JSON over HTTP with resource URLs, standard methods, and meaningful status codes.
Designing resource URLs
The tutorial's API manages one resource, books. Two URL shapes cover everything:
/api/booksis the collection. It represents all books./api/books/{id}is a single item. The{id}part is a placeholder for the book's identifier, for example/api/books/42.
Follow these naming conventions:
- Use plural nouns for collections (
/books, not/book). - Do not put verbs in the path (
/api/books/delete/42is wrong). The HTTP method already says "delete". - Use lowercase and hyphens for multi-word names, such as
/api/book-reviews. - The
/apiprefix is a convention that keeps API routes apart from any web pages the same application might serve.
Mapping CRUD to HTTP methods
Each CRUD operation has a natural HTTP method.
| Operation | HTTP method | URL | Success status | Success body |
|---|---|---|---|---|
| Create | POST | `/api/books` | 201 Created | The new book, plus a `Location` header |
| Read one | GET | `/api/books/{id}` | 200 OK | The book |
| Read many | GET | `/api/books` | 200 OK | A page of books |
| Update | PUT | `/api/books/{id}` | 200 OK | The updated book |
| Delete | DELETE | `/api/books/{id}` | 204 No Content | None |
Some details in this table are choices, not rules:
- POST goes to the collection because the client does not know the new book's ID. The server assigns it and reports where the new item lives in the
Locationheader. - PUT replaces the whole resource. The client sends every field. A missing field is treated as "not set", not as "leave unchanged".
- Some teams return 204 No Content from PUT instead of the updated body. Returning the body saves the client a follow-up GET, so this tutorial returns it.
Safe and idempotent methods
Two properties of HTTP methods affect how clients, proxies, and retry logic behave.
- A method is safe if it does not change server state. GET is safe.
- A method is idempotent if repeating the same request leaves the server in the same state as sending it once. GET, PUT, and DELETE are idempotent. POST is not.
| Method | Safe | Idempotent |
|---|---|---|
| GET | Yes | Yes |
| POST | No | No |
| PUT | No | Yes |
| DELETE | No | Yes |
Idempotency matters when a network call times out and the client does not know whether the server processed it. A client can safely retry a PUT or DELETE. Retrying a POST can create a duplicate book. Production APIs that need safe POST retries often add an idempotency key, which is out of scope here.
Idempotent means the server's state is the same, not that the response is identical. A first DELETE returns 204. A second DELETE of the same ID finds nothing, so it can return 404. The book is gone either way.
PUT versus PATCH
PATCH is for partial updates, where the client sends only the fields to change. It is useful but adds questions about how to represent "set this field to null" versus "do not touch this field". This tutorial implements PUT only, which keeps the contract simple. A PUT request always carries a complete representation.
Status codes that carry meaning
A status code tells the client what happened without parsing the body. Use the class of the code first, then the specific code.
| Range | Meaning |
|---|---|
| 2xx | The request succeeded |
| 4xx | The client sent something wrong |
| 5xx | The server failed |
The codes this API uses:
| Code | Name | When the API returns it |
|---|---|---|
| 200 | OK | A successful GET or PUT |
| 201 | Created | A successful POST |
| 204 | No Content | A successful DELETE |
| 400 | Bad Request | The body is malformed or fails validation |
| 404 | Not Found | No book has the requested ID |
| 500 | Internal Server Error | An unexpected bug or failure on the server |
Two mistakes are common. The first is returning 200 with an error message in the body. Clients and monitoring tools rely on the status code, so an error that says 200 is invisible to them. The second is returning 500 for client mistakes such as a missing book. A 500 tells operators that the server is broken and should be reserved for that.
Two other codes appear in real APIs and are worth knowing now: 409 Conflict (the request clashes with current state, such as a duplicate unique value) and 422 Unprocessable Content (the body is well-formed but semantically invalid). This tutorial uses 400 for validation failures, which Spring does by default.
A request, end to end
The following examples show what the finished API will do. They are HTTP exchanges, not code you run yet.
Creating a book:
POST /api/books HTTP/1.1
Content-Type: application/json
{"title": "Refactoring", "author": "Martin Fowler"}HTTP/1.1 201 Created
Location: http://localhost:8080/api/books/1
Content-Type: application/json
{"id": 1, "title": "Refactoring", "author": "Martin Fowler"}Reading a book that does not exist:
GET /api/books/999 HTTP/1.1HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{"title": "Book not found", "status": 404, "detail": "Book 999 not found"}The error body follows the Problem Details format (RFC 7807, updated by RFC 9457), which gives every error the same fields. A later chapter implements it.
How a request moves through the application
The Spring application splits the work into layers. The controller handles HTTP, the service holds business logic, and the repository talks to the database. The diagram shows one request passing through all three.
Each layer has one job, and that is why the chapters ahead are ordered as they are:
- The controller translates HTTP into method calls and results back into status codes.
- The service contains the application's rules and decides when a missing book is an error.
- The repository reads and writes rows.
When the book does not exist, the service signals that with an exception. The exception travels back up to a central handler, which turns it into the 404 shown above. The service never needs to know about HTTP.
Common design errors
These mistakes appear often in first CRUD APIs:
- Verbs in URLs.
POST /api/createBookduplicates what the method already says and breaks the uniform interface. - Using GET to change data. GET must be safe. Browsers, caches, and crawlers assume they can call it freely.
- Using POST for everything. It works, but you lose idempotency, caching for reads, and clear intent.
- Exposing the database entity directly. The JSON then depends on the table layout, and internal fields leak. A later chapter introduces DTOs to separate them.
- Returning 200 for failures. Clients cannot tell success from error without parsing the body.
- Inconsistent error formats. Each endpoint inventing its own error body forces clients to special-case everything.
What you will build
The remaining chapters implement this design in order: project setup, database configuration, the entity, the repository, DTOs, the service, transactions, the controller, the CRUD endpoints, validation, error handling, pagination, and tests. At the end, the table in this chapter will be backed by working endpoints that you can call and test.
Exercise
A client sends the same PUT /api/books/7 request twice because the first response timed out. Does this create a duplicate book? Compare this with sending POST /api/books twice.
Show answer
No. PUT is idempotent: it replaces book 7 with the same representation both times, so the server ends in the same state as after one request. POST is not idempotent: each call asks the server to create a new resource and assign a new ID, so sending it twice can create two books with the same title and author.
Exercise
Design the HTTP method, URL, and success status code for each of these operations on a Book resource: (a) list all books, (b) add a new book, (c) remove book 12, (d) replace the title and author of book 12.
Show answer
(a) GET /api/books, 200 OK. (b) POST /api/books, 201 Created with a Location header. (c) DELETE /api/books/12, 204 No Content. (d) PUT /api/books/12 with a full body, 200 OK.
Exercise
An endpoint GET /api/books/999 finds no book and returns 200 OK with the body {"error": "not found"}. Give two reasons this is a poor design and state what it should return.
Show answer
Clients, logs, and monitoring tools judge success by the status code, so this failure looks like a success and can be cached or ignored. It also forces every client to parse the body to detect errors. It should return 404 Not Found, ideally with a consistent Problem Details body.