Sub topic 1
REST and HTTP in brief: resources, methods, status codes
Prerequisites
This chapter assumes you have:
- Java fundamentals, including classes, interfaces and records.
- Basic familiarity with HTTP messages: a request has a method, a URL, headers and an optional body. A response has a status code, headers and an optional body.
- Some experience with Maven or Gradle.
- A working idea of dependency injection, where a framework passes the objects a class needs into its constructor.
You don't need to have written a Spring application yet. This chapter has no framework setup. It covers the HTTP rules that every controller in the rest of the tutorial follows.
Why HTTP semantics come first
A Spring controller method is a Java method that Spring MVC calls when an HTTP request arrives. The annotations you write decide which requests reach which method. What the method returns decides which status code, headers and body the client sees. If you get the HTTP meaning wrong, the code still compiles and runs. Clients, caches and proxies then misbehave, because they act on the method and status code and not on your intentions.
So the first step is to learn what HTTP guarantees for each method and status code. The Spring annotations in later chapters are a thin layer on top of these rules.
Resources and URLs
REST (Representational State Transfer) is a style for designing APIs on top of HTTP. Its central idea is the resource: a thing your API exposes, such as a book, an order or a user. Each resource has an identifier, which is a URL. Clients never receive the resource itself. They receive a representation of it, most often a JSON document.
Two URL shapes cover most APIs:
- A collection, such as
/api/books, is the set of all books. - A single resource, such as
/api/books/42, is one book inside that collection.
Follow these conventions:
- Use plural nouns for collections (
/books, not/book). - Keep verbs out of the path.
/api/books/42plus theDELETEmethod is clearer than/api/deleteBook?id=42. - Use path segments to express containment, such as
/api/authors/7/books. Avoid nesting deeper than two levels. Beyond that, expose the inner resource at its own top-level path. - Use the query string for optional filtering, sorting and paging, such as
/api/books?title=dune. Don't use it to identify the resource.
The method carries the action. The URL names the thing the action applies to.
HTTP methods and their guarantees
Each method has formal properties that matter for retries and caching.
- A method is safe if it is meant only to read. Clients and caches may call it freely.
- A method is idempotent if making the same request several times leaves the server in the same state as making it once. This matters when a network call times out and the client must decide whether to retry.
| Method | Typical meaning on a collection or resource | Safe | Idempotent | Has request body |
|---|---|---|---|---|
| GET | Read a resource or list a collection | Yes | Yes | No |
| HEAD | Same as GET, but headers only | Yes | Yes | No |
| POST | Create a resource, or run a non-idempotent action | No | No | Yes |
| PUT | Replace a resource completely | No | Yes | Yes |
| PATCH | Change part of a resource | No | Not guaranteed | Yes |
| DELETE | Remove a resource | No | Yes | Usually no |
| OPTIONS | Describe which methods the server supports | Yes | Yes | No |
Some details trip people up:
- POST is not idempotent. Sending
POST /api/bookstwice normally creates two books. If a client retries after a timeout, it may create a duplicate. APIs that need safe retries often accept an idempotency key header, but that goes beyond the basics here. - PUT replaces. If you
PUTa book without itsauthorfield, a strict implementation treats the author as absent. It does not keep the old value. UsePATCHfor partial updates. - PATCH may or may not be idempotent. "Set the title to Dune" is idempotent. "Append a tag" is not. It depends on the patch semantics you define.
- DELETE is idempotent in effect, not in response. The first
DELETE /api/books/42may return204, and the second may return404. The server state is the same after both: book 42 does not exist. - GET must not change state. Crawlers, prefetching browsers and caches all assume that GET is safe. A
GET /api/books/42/deleteendpoint is a bug waiting to happen.
A request and response on the wire
Here is the full exchange for creating a book. The request:
POST /api/books HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Accept: application/json
{"title": "Dune", "author": "Frank Herbert"}The response:
HTTP/1.1 201 Created
Location: http://localhost:8080/api/books/42
Content-Type: application/json
{"id": 42, "title": "Dune", "author": "Frank Herbert"}Four parts of this exchange recur throughout the tutorial:
Content-Typedescribes the body being sent. The server uses it to choose how to read the request body.Acceptlists the formats the client is willing to receive.201 Createdtells the client that a new resource now exists.Locationgives the URL of the new resource, so the client doesn't have to guess it.
The diagram shows the same exchange as a sequence of steps.
Status codes
The status code is a three-digit number, and its first digit gives the class:
| Class | Meaning | Who is responsible |
|---|---|---|
| 2xx | Success | Nobody |
| 3xx | Redirection or "use your cached copy" | Depends |
| 4xx | The request is wrong | The client |
| 5xx | The server failed on a valid request | The server |
You will use a small set of codes most of the time.
| Code | Name | Use it when |
|---|---|---|
| 200 | OK | A GET or update succeeded and the response has a body |
| 201 | Created | A POST created a resource. Include a `Location` header |
| 204 | No Content | The operation succeeded and there is nothing to return, such as after DELETE |
| 400 | Bad Request | The request is malformed or fails validation |
| 401 | Unauthorized | The caller is not authenticated |
| 403 | Forbidden | The caller is authenticated but not allowed |
| 404 | Not Found | The resource does not exist |
| 405 | Method Not Allowed | The URL exists but not for this method |
| 409 | Conflict | The request clashes with current state, such as a duplicate unique value |
| 415 | Unsupported Media Type | The request `Content-Type` is not one the endpoint reads |
| 500 | Internal Server Error | An unexpected failure on the server |
Some pairs get mixed up:
- 401 versus 403. Despite its name, 401 means "I don't know who you are." 403 means "I know who you are, and you can't do this."
- 400 versus 404. For
GET /api/books/abcwhere the id must be numeric,400is correct, because the request itself is malformed. ForGET /api/books/9999where the id is valid but absent, use404. - 200 versus 204. If a client expects a body, a
204with no body will break its parser. Pick one convention per operation and keep to it. - 404 versus 405. Spring returns
405if you mapGET /api/books/{id}and the client sendsPUTto the same URL. That is correct behavior and not a bug in your mapping. - Don't send 200 with an error in the body. Clients, monitoring and retry logic all read the status code first.
A rough decision path for a typical write operation looks like this:
How this maps to Spring MVC
You will build all of this in the following chapters. This small controller shows how the method and status rules appear in code. It stores books in memory so it runs without a database. It assumes a Spring Boot web project, which the next chapter sets up.
package com.example.library;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/books")
public class PreviewBookController {
public record Book(long id, String title) {}
public record NewBook(String title) {}
private final Map<Long, Book> books = new ConcurrentHashMap<>();
private final AtomicLong ids = new AtomicLong();
@GetMapping
public List<Book> list() {
return List.copyOf(books.values());
}
@PostMapping
public ResponseEntity<Book> create(@RequestBody NewBook request) {
Book book = new Book(ids.incrementAndGet(), request.title());
books.put(book.id(), book);
return ResponseEntity.created(URI.create("/api/books/" + book.id())).body(book);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable long id) {
books.remove(id);
}
}Each HTTP rule from this chapter appears in the code:
@GetMappingreads and changes nothing, so it is safe.@PostMappingcreates a resource and returns201with aLocationheader.@DeleteMappingremoves the book and returns204. Calling it twice does the same thing both times, so it is idempotent. Becausebooks.removeignores a missing key, the second call also returns204. Some APIs return404instead. Both choices are defensible, but choose one on purpose.
With the application running, you can test it from a terminal:
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Dune"}'The -i flag prints the status line and headers, so you can check the 201 and the Location header.
Common mistakes
- Using POST for everything. It works, but it throws away caching for reads and safe retries for updates.
- Putting actions in URLs (
/api/books/42/delete). Use the method instead. For real actions that don't fit CRUD, such as "cancel an order", a sub-resource likePOST /api/orders/7/cancellationis acceptable. - Returning 200 for every outcome. Monitoring tools count 5xx and 4xx responses. If everything is 200, your dashboards go blind.
- Leaking internals in 500 responses. A stack trace in the body helps attackers and doesn't help clients. Return a short, consistent error body instead. The ProblemDetail chapter covers this.
- Treating PUT as "update any fields". PUT replaces the whole resource. Use PATCH for partial changes.
Exercise
A client sends DELETE /api/books/42 and the server returns 204. The client's connection drops before it sees the response, so it sends the same DELETE again. Is that safe? What status might the second call return, and does that change the server state?
Show answer
It is safe, because DELETE is idempotent. After the first call, book 42 is gone, and a second DELETE leaves the state unchanged. The second response may be 404 (the book no longer exists) or 204 if the API chooses to treat a missing resource as already deleted. Either way, the server state is identical to what it was after the first call.
Exercise
Choose a status code for each case: (a) POST creates an order, (b) a request has a valid token but the user lacks permission, (c) a request body is missing a required field, (d) PUT is sent to a URL that only supports GET.
Show answer
(a) 201 Created with a Location header. (b) 403 Forbidden, because the caller is authenticated but not allowed. (c) 400 Bad Request. (d) 405 Method Not Allowed.