HTTP Methods
BookNook needs to list books, add a book, change a book's shelf, and remove a lost book. You could invent URLs like /getBook and /deleteBook, but HTTP already gives every request a verb. Use the verbs well and callers, caches and proxies all understand your API without reading a word of documentation.
The rule
The URL is the noun; the method is the verb.
The five methods you will use every day:
| Method | Meaning | Body? | Safe | Idempotent |
|---|---|---|---|---|
GET |
Read a resource | No | Yes | Yes |
POST |
Create inside a collection, or trigger an action | Yes | No | No |
PUT |
Replace a resource completely | Yes | No | Yes |
PATCH |
Change part of a resource | Yes | No | Not guaranteed |
DELETE |
Remove a resource | Usually no | No | Yes |
Two properties matter more than the names:
- Safe: the request does not change anything on the server.
GETmust be safe, so crawlers and caches can call it freely. - Idempotent: sending the same request twice leaves the server in the same state as sending it once. Deleting book 42 twice still ends with book 42 gone. Posting the same new loan twice creates two loans.
GET /v1/books/42 read book 42
PUT /v1/books/42 replace book 42 with the body
PATCH /v1/books/42 change only the fields in the body
DELETE /v1/books/42 remove book 42
POST /v1/books add a new book to the collectionTwo supporting methods appear in the background: HEAD is a GET without the body (handy to check if something exists), and OPTIONS asks which methods a URL allows. Browsers send OPTIONS on their own for cross-origin checks, as you will see in the CORS lesson.
The shortcut
Say the request as a sentence: "[verb] the [noun]." If the sentence sounds wrong, the method is wrong.
"Mark book 42 as damaged"
Only one field changes, so "patch book 42":
PATCH /v1/books/42with{"condition": "damaged"}.
The trap is GET /v1/books/42/delete. A link checker or a browser prefetch following that URL would delete a book, because everyone assumes GET is safe.
Drills
Answer fast — trust the rule.
Which method should change only a book's shelf field?
Which of these methods is NOT idempotent?
A client sends PUT /v1/books/42 with only {"shelf": "B3"}. By the meaning of PUT, what should book 42 become?
Why is GET /v1/loans/901/cancel a bad design?
Remember
- The URL is the noun; the method is the verb.
- Shortcut: say "[verb] the [noun]" out loud and check it sounds right.
- Trap: changing data with GET, and using PUT for a partial update.
