Find a course

Module 3: REST APIsLesson 6 of 1214 min

HTTP Methods and CRUD

Map create, read, update and delete to POST, GET, PUT, PATCH and DELETE, and learn which methods are safe and idempotent so retries never cause damage.

Step 1 of 15Learn

CRUD meets HTTP

Almost every app manages data with four operations, known as CRUD: Create, Read, Update and Delete. REST maps them onto HTTP methods:

OperationMethodExampleTypical success
CreatePOSTPOST /notes with the new note in the body201 Created
Read (list)GETGET /notes200 OK
Read (one)GETGET /notes/15200 OK
ReplacePUTPUT /notes/15 with the complete note200 OK or 204
Update partPATCHPATCH /notes/15 with only changed fields200 OK
DeleteDELETEDELETE /notes/15204 No Content

Notice that POST goes to the collection (/notes), because the new item doesn't have an ID yet; the server assigns one and usually returns it, along with a Location header pointing to the new resource. The other operations target a specific item.

GET is for reading only. It should never change data, which is why browsers, search crawlers and link previews feel free to make GET requests on their own. An endpoint such as GET /notes/15/delete can wipe data the moment a crawler follows the link.

There are a few other methods you'll see occasionally: HEAD is like GET but returns only headers (useful to check whether something exists or changed), and OPTIONS asks which methods are allowed, which browsers use behind the scenes for cross-origin requests.

Step 2 of 15Practice · Match the pairs

Match each task to the request a RESTful notes API would expect.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Create a new note
  2. Show all notes
  3. Change only the title of note 15
  4. Remove note 15
  5. Replace note 15 entirely with a new version

Step 3 of 15Diagram

The life of one note, request by request

The life of one note, request by requestProcess diagram: POST /notes → GET /notes/15 → PATCH /notes/15 → DELETE /notes/15 → GET /notes/15 again.POST /notesGET /notes/15PATCH /notes/15DELETE /notes/15GET /notes/15 again

Tap a shape with to see more.

POST /notes

201 Created, with a Location header pointing to /notes/15.

GET /notes/15

200 OK with the note as JSON.

PATCH /notes/15

200 OK: only the fields sent were changed.

DELETE /notes/15

204 No Content: gone, nothing to return.

GET /notes/15 again

404 Not Found: the resource no longer exists.

Step 4 of 15Learn

PUT vs. PATCH

Both PUT and PATCH update an existing resource, but they mean different things.

PUT replaces the resource with the representation you send. Suppose note 15 is:

{ "id": 15, "title": "Groceries", "body": "milk, eggs", "pinned": true }

Sending PUT /notes/15 with {"title": "Shopping"} means "note 15 is now exactly this". Strictly applied, body and pinned are gone or reset to defaults, because you didn't include them. With PUT, the client sends the complete resource.

PATCH modifies only what you send. PATCH /notes/15 with {"title": "Shopping"} changes the title and leaves body and pinned untouched.

In practice:

  • Use PATCH for typical edit forms where the user changes one or two fields. It sends less data and avoids accidentally wiping fields the client didn't know about.
  • Use PUT when the client naturally has the whole resource, such as saving a full settings document or uploading a file to a known path.

Some APIs also let PUT create a resource at a client-chosen URL, such as PUT /users/kim/avatar. Always check the documentation: real APIs vary, and some use PUT loosely to mean "update".

Step 5 of 15Practice · What would you do?

What would you do?

Note 15 is {"id": 15, "title": "Groceries", "body": "milk, eggs", "pinned": true}. A client wants to unpin it and sends PUT /notes/15 with body {"pinned": false} to an API that follows PUT semantics strictly. What is the likely result?

Step 6 of 15Compare

Same body, different method: {"pinned": false}

AspectPUT /notes/15PATCH /notes/15
MeaningReplace the whole note with thisChange only these fields
title afterMissing or reset"Groceries"
body afterMissing or reset"milk, eggs"
pinned afterfalsefalse
Client must sendEvery fieldJust the changes

Step 7 of 15Learn

Safe and idempotent methods

Networks fail. A request may time out, and the client can't tell whether the server never got it or processed it and the response got lost. Can it simply send it again? That depends on two properties.

A method is safe if it doesn't change anything on the server. GET, HEAD and OPTIONS are safe: you can call them any number of times freely.

A method is idempotent if making the same request once or many times has the same effect on the server.

  • GET is idempotent: reading twice changes nothing.
  • PUT is idempotent: setting note 15 to a given state twice leaves it in that state.
  • DELETE is idempotent: after the first delete, the note is gone; deleting again leaves it gone (the second call may return 404, but the server state is the same).
  • POST is not idempotent: sending POST /payments twice may charge the customer twice.
  • PATCH may or may not be: {"title": "Shopping"} is idempotent, but an "add 1 to the counter" patch is not.

So: retrying GET, PUT and DELETE after a timeout is safe; retrying POST is risky. Payment APIs solve this with an idempotency key: the client sends a unique ID in a header such as Idempotency-Key, and if the server sees the same key twice, it returns the original result instead of charging again.

Step 8 of 15Practice · Sort into groups

Classify each request. Is it safe to repeat automatically after a timeout (idempotent), or could repeating it cause a duplicate effect?

Tap an item, then tap its group (or drag it there).

Step 9 of 15Practice · Code challenge

Write canRetry(method) that returns true if a request with that HTTP method can be retried automatically because the method is idempotent by definition (GET, HEAD, OPTIONS, PUT, DELETE), and false otherwise (POST, PATCH or anything else). Method names may arrive in any letter case, such as "get" or "Put".

Runs in a sandbox in your browser.
  • canRetry("GET")
  • canRetry("put")
  • canRetry("Delete")
  • canRetry("POST")
  • canRetry("patch")
  • canRetry("HEAD")

Step 10 of 15Practice · Diagram

HTTP methods by safety and idempotency

Where does DELETE belong?

Tap the shape that answers the question, then press Check.

HTTP methods by safety and idempotencyTwo-by-two matrix: (empty: safe implies idempotent), GET, HEAD, OPTIONS, POST, PATCH, PUT, DELETE.(empty: safe impliesidempotent)GET, HEAD, OPTIONSPOST, PATCHPUT, DELETEIdempotent?NoYesSafe (read-only)?NoYes
(empty: safe implies idempotent)

A request that changes nothing can be repeated freely, so every safe method is also idempotent.

GET, HEAD, OPTIONS

Read-only and repeatable: retry and cache freely.

POST, PATCH

Repeating may create duplicates or apply a change twice; retry only with an idempotency key.

PUT, DELETE

Change data, but the second identical call leaves the same final state.

Step 11 of 15Note

Step 12 of 15Learn

Actions that don't fit CRUD

Real APIs have operations that aren't obviously create, read, update or delete: sending an invoice, cancelling an order, resetting a password, archiving a project. How do you express them without verbs in URLs?

Option 1: model the change as a field update. Cancelling might simply be PATCH /orders/77 with {"status": "cancelled"}. This works well when the action really is a state change and the server can enforce valid transitions.

Option 2: model the action as creating a resource. Sending an invoice can be POST /invoices/77/deliveries, creating a delivery record. Resetting a password can be POST /password-resets with the email address. This often fits better, because the "action" has its own data, such as when it happened and whether it succeeded, which you may later want to read.

Option 3: a sub-resource "action" endpoint. Many respected APIs pragmatically accept paths such as POST /orders/77/cancel. It isn't pure REST, but it's clear, and it uses POST, so it's never triggered by accident.

Whichever you pick, apply it consistently across the API, and never use GET for an operation that changes something.

Step 13 of 15Practice · What would you do?

What would you do?

An API needs a way to archive a project. Archived projects keep their data, can be restored later, and the team wants to record who archived each one and when. Which design fits best?

Step 14 of 15Practice · True or false

Sending the same DELETE request twice is idempotent even if the second call returns 404 Not Found.

Step 15 of 15Practice · Choose one

A client creates a new customer record. Which request fits REST conventions?