Thuta Learning
API Tutorial
IntermediateWeb DevelopmentIntermediate

HTTP Methods (GET/POST/PUT/DELETE)

API TutorialLesson 1040 min

What you'll walk away with

  • Match GET, POST, PUT, PATCH and DELETE to what you want to do with a resource
  • Explain what safe and idempotent mean and which methods are which
  • Show the difference between PUT (replace) and PATCH (partial change) from the responses
  • Return 405 with an Allow header for unsupported methods and answer OPTIONS

Explain it simply

HTTP methods in plain language

HTTP methods are the verbs of an API. The URL says what you are talking about, such as a note or a list of users, and the method says what you want to do with it: read it, create it, replace it, change it or remove it. The same URL with a different method is a different action.

Think of a library desk. The title of the book (the URL) is the same, but 'show me', 'add a new book', 'swap this copy', 'fix the cover' and 'remove it from the catalogue' are different requests. More importantly, saying some of them twice gives the same result and saying others twice does not, and that is the central idea of this lesson.

Problem → Why → Solution

The problem: a GET link that cancels an order

Suppose the 'Cancel order' button in an email is an ordinary link to /orders/7/cancel. It works, and then one day orders vanish without any customer clicking anything. Email security scanners, link-preview bots in chat apps and browsers that prefetch links all fetch that URL with GET, and every one of them cancels an order.

get-that-changes-state.js
// BROKEN: a state-changing action hidden behind GET (Express-style handler)
app.get("/orders/:id/cancel", (req, res) => {
  orders.cancel(req.params.id);
  res.send("Order cancelled");
});

// Anything that merely FETCHES this URL cancels the order:
//   <a href="/orders/7/cancel">Cancel</a> in an email, a link-preview bot,
//   a security scanner, or a browser that prefetches links.

Everyone assumes GET is safe

HTTP defines GET as read-only, and caches, crawlers, prefetchers and proxies call it freely on that assumption. Break the assumption and tools that know nothing about your API become hazards. Keep changes inside POST, PUT, PATCH or DELETE, so the method itself tells everyone what happens if the request is repeated.

Core concept: a method says what happens, and what a repeat does

Every method carries two properties. Safe means it does not change server state; it only reads (GET, HEAD, OPTIONS). Idempotent means sending the same request once or many times leaves the server in the same final state (GET, HEAD, OPTIONS, PUT, DELETE). Idempotent does not mean the response is the same: a second DELETE may return 404 instead of 204, yet the resource is gone either way.

POST is the general-purpose method: it creates a new resource in a collection or asks the server to run an action. The server picks the id, so every call produces something new, which makes POST neither safe nor idempotent. Good practice is to answer 201 Created with the new URL in a Location header. Because a retry after a timeout can create two orders, payment-style APIs use an Idempotency-Key header.

PUT replaces the whole resource at a known URL: the body you send becomes the new representation, so fields you leave out can vanish (and a PUT may create the resource with 201 if it did not exist). PATCH changes only the fields you send. The HTTP spec does not promise that PATCH is idempotent: setting {"done": true} again changes nothing, but 'add one' changes the result every time. DELETE removes the resource, usually answering 204 No Content.

MethodTypical useSafe / idempotent
GETRead a resourceSafe, idempotent
HEADLike GET, headers onlySafe, idempotent
POSTCreate or run an actionNeither
PUTReplace the whole resourceIdempotent
PATCHChange some fieldsNot guaranteed
DELETERemove the resourceIdempotent
OPTIONSAsk what is allowedSafe, idempotent
A verb on a noun
  1. Pick the resource: a URL like /notes/1
  2. Pick the verb: what should happen to it
  3. Safe? Only GET, HEAD, OPTIONS
  4. Repeatable? PUT, DELETE yes; POST no
  5. Unsupported verb: 405 + Allow

Whenever you think about retrying, first ask what happens if this method is sent twice.

General pattern

text
POST   /things        create a thing        -> 201 Created + Location
GET    /things        list things           -> 200 OK
GET    /things/{id}   read one              -> 200 OK, or 404
PUT    /things/{id}   replace the whole one -> 200 OK (201 if it was new)
PATCH  /things/{id}   change some fields    -> 200 OK
DELETE /things/{id}   remove it             -> 204 No Content
other  any method not allowed here          -> 405 + Allow header

The collection URL handles create and list, the item URL handles read, replace, change and remove, and every combination you do not support answers 405.

Worked example: try every method on a notes API

The script below starts a server that keeps notes in memory and sends it a series of methods. Read the output like this: two POSTs create two notes, ids 1 and 2. Two PUTs with the same body give the same answer. Then a PUT without done resets done to false, because PUT replaces. A PATCH changes only done.

Next, DELETE sent twice answers 204 and then 404, but note 2 is gone in both cases. A DELETE on the collection answers 405 with an Allow header, and OPTIONS answers with Allow and no body.

notes-methods.mjs
import http from "node:http";

const notes = new Map(); // id -> { id, title, done }
let nextId = 1;

const server = http.createServer(async (req, res) => {
  const send = (status, body, headers = {}) => {
    if (body === undefined) {
      res.writeHead(status, headers); // 204 has no body, so no Content-Type either
      return res.end();
    }
    res.writeHead(status, { "Content-Type": "application/json", ...headers });
    res.end(JSON.stringify(body));
  };

  let raw = "";
  for await (const chunk of req) raw += chunk;
  const body = raw ? JSON.parse(raw) : {};

  const [, collection, rawId] = req.url.split("/"); // "/notes/1" -> ["", "notes", "1"]
  const id = rawId === undefined ? null : Number(rawId);
  if (collection !== "notes" || Number.isNaN(id)) {
    return send(404, { error: "not_found" });
  }

  const allow = id === null
    ? ["GET", "POST", "OPTIONS"]
    : ["GET", "PUT", "PATCH", "DELETE", "OPTIONS"];
  if (!allow.includes(req.method)) {
    return send(405, { error: "method_not_allowed" }, { Allow: allow.join(", ") });
  }
  if (req.method === "OPTIONS") return send(204, undefined, { Allow: allow.join(", ") });

  if (id === null) {
    if (req.method === "GET") return send(200, [...notes.values()]);
    // POST: the server, not the client, picks the new id
    const note = { id: nextId++, title: body.title, done: false };
    notes.set(note.id, note);
    return send(201, note, { Location: `/notes/${note.id}` });
  }

  const existing = notes.get(id);
  if (req.method === "PUT") { // replaces the whole resource, creating it if needed
    notes.set(id, { id, title: body.title, done: body.done ?? false });
    return send(existing ? 200 : 201, notes.get(id));
  }
  if (!existing) return send(404, { error: "not_found" });
  if (req.method === "GET") return send(200, existing);
  if (req.method === "PATCH") { // changes only the fields that were sent
    Object.assign(existing, body, { id });
    return send(200, existing);
  }
  notes.delete(id); // DELETE
  send(204);
});

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

async function call(method, path, payload) {
  const res = await fetch(base + path, {
    method,
    headers: payload ? { "Content-Type": "application/json" } : {},
    body: payload ? JSON.stringify(payload) : undefined,
  });
  const text = await res.text();
  const allow = res.headers.get("allow");
  const parts = [method.padEnd(7), path.padEnd(9), res.status];
  if (text) parts.push(text);
  if (allow) parts.push(`[Allow: ${allow}]`);
  console.log(parts.join(" "));
}

await call("POST", "/notes", { title: "Buy milk" });
await call("POST", "/notes", { title: "Buy milk" });
await call("PUT", "/notes/1", { title: "Buy oat milk", done: true });
await call("PUT", "/notes/1", { title: "Buy oat milk", done: true });
await call("PUT", "/notes/1", { title: "Buy oat milk" });
await call("PATCH", "/notes/1", { done: true });
await call("DELETE", "/notes/2");
await call("DELETE", "/notes/2");
await call("DELETE", "/notes");
await call("OPTIONS", "/notes/1");
await call("GET", "/notes");
server.close();

Code breakdown

  1. 405 with Allowreturn send(405, { error: "method_not_allowed" }, { Allow: allow.join(", ") });

    Each URL has a list of allowed methods. A method outside the list gets 405, and the Allow header names the ones that do work. This differs from 404: the URL is fine, the method is not.

  2. POST createsreturn send(201, note, { Location: `/notes/${note.id}` });

    POST creates a new note and the server picks the id. The response is 201 Created, and the Location header gives the new URL. That is why two identical POSTs produce two notes.

  3. PUT replacesnotes.set(id, { id, title: body.title, done: body.done ?? false });

    PUT replaces the note with exactly what the body contains. If done is missing from the body it resets to false. Sending the same PUT again leaves the same final state, which is what idempotent means.

  4. PATCH mergesObject.assign(existing, body, { id });

    PATCH merges only the fields that were sent into the existing note. Putting { id } last stops a client from changing the id even if it sends one.

  5. DELETE has no bodysend(204);

    204 No Content means success with no body, so the send helper omits Content-Type too. The second DELETE gets 404 because the note is already gone, yet the server state does not change.

  6. OPTIONS answers Allowif (req.method === "OPTIONS") return send(204, undefined, { Allow: allow.join(", ") });

    OPTIONS asks which methods this URL allows, and the server answers with an Allow header and no body. Browsers send OPTIONS automatically before certain cross-origin requests.

You should see
POST    /notes    201 {"id":1,"title":"Buy milk","done":false}
POST    /notes    201 {"id":2,"title":"Buy milk","done":false}
PUT     /notes/1  200 {"id":1,"title":"Buy oat milk","done":true}
PUT     /notes/1  200 {"id":1,"title":"Buy oat milk","done":true}
PUT     /notes/1  200 {"id":1,"title":"Buy oat milk","done":false}
PATCH   /notes/1  200 {"id":1,"title":"Buy oat milk","done":true}
DELETE  /notes/2  204
DELETE  /notes/2  404 {"error":"not_found"}
DELETE  /notes    405 {"error":"method_not_allowed"} [Allow: GET, POST, OPTIONS]
OPTIONS /notes/1  204 [Allow: GET, PUT, PATCH, DELETE, OPTIONS]
GET     /notes    200 [{"id":1,"title":"Buy oat milk","done":true}]

Idempotency: why retries matter

When the network fails and no response arrives, the client cannot know whether the request reached the server. With PUT or DELETE it simply sends it again and nothing breaks. With POST, a resend can create two orders or charge twice. The fix is for the client to attach a unique Idempotency-Key to each logical request, and for the server to replay the first answer whenever it sees the same key.

idempotency-key.mjs
import http from "node:http";

const orders = [];
const saved = new Map(); // Idempotency-Key -> the answer already given

const server = http.createServer((req, res) => {
  const key = req.headers["idempotency-key"];
  res.writeHead(201, { "Content-Type": "application/json" });
  if (key && saved.has(key)) return res.end(saved.get(key)); // replay, create nothing

  const order = { id: orders.length + 1 };
  orders.push(order);
  const answer = JSON.stringify(order);
  if (key) saved.set(key, answer);
  res.end(answer);
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

// A client that retries a POST three times, as if the first replies were lost.
async function checkout(headers) {
  const res = await fetch(`${base}/orders`, { method: "POST", headers });
  return res.text();
}

for (let attempt = 0; attempt < 3; attempt++) await checkout({});
console.log("without a key:", orders.length, "orders created");

orders.length = 0;
for (let attempt = 0; attempt < 3; attempt++) {
  await checkout({ "Idempotency-Key": "checkout-42" });
}
console.log("with a key   :", orders.length, "order created");
server.close();

Without a key, all three retries create a new order, so there are three. With a key, only the first creates an order and the other two receive the saved answer, so there is one. Idempotency-Key is common in payment APIs, but check each API's documentation to see whether it is supported.

PUT or PATCH?

AspectPUTPATCH
What you sendThe full representationOnly the fields to change
Missing fieldsRemoved or resetLeft untouched
Sent againIdempotentDepends on the operation: set is fine, increment is not

To change only a name on a profile, PATCH is the better fit. Sending just a name with PUT can wipe the other fields, such as email and phone. If you use PUT, GET the resource first, edit the fields, and send back the complete representation.

405, OPTIONS and the browser

HTTP says a 405 Method Not Allowed should come with an Allow header so the client learns what it can use. 404 means the URL does not exist; 405 means the URL exists but not for this method. You can send OPTIONS yourself with curl, and browsers send it automatically as a preflight before some cross-origin requests.

This is why an API that works in curl but fails in the browser often has a server that does not answer OPTIONS. The details come in the later lesson on CORS.

In real projects

HTTP methods in real projects

Most REST APIs tie CRUD to methods: POST for Create, GET for Read, PUT or PATCH for Update, DELETE for Delete. OpenAPI documents also list the methods under each path. Choosing methods correctly means a developer can often guess your API without reading the documentation.

  • Payment and order APIs pair POST with an Idempotency-Key, so a network retry does not charge twice.
  • Some HTTP clients and proxies automatically retry requests defined as idempotent after a connection drop, but not POST; they rely on you choosing the method correctly.
  • When you refresh a page that came from a POST form, the browser asks whether to resubmit, because repeating a POST could do harm; GET triggers no such question.
  • Crawlers, CDNs and caches work with GET, so expressing reads as GET makes them faster and cheaper to serve.

Common mistakes

Common mistakes with HTTP methods

Using GET to change state

A GET link such as /orders/7/cancel gets triggered by a crawler, preview bot or prefetch just for loading it. Every change belongs in POST, PUT, PATCH or DELETE.

Using PUT for a partial update

Sending one field in a PUT body can make the other fields vanish or fall back to defaults. For a partial change pick PATCH, and use PUT only when replacing.

Retrying a POST blindly

An automatic retry of a POST after a timeout, or a user clicking 'try again', can create duplicate orders. Use an Idempotency-Key or detect duplicates on the server.

Sending a GET with a body

HTTP gives a body on a GET no defined meaning, and some proxies, caches and servers drop it or reject the request. Put search and filter criteria in the query string.

Best practices

Best practices

  • Keep URLs as nouns and put the action in the method: DELETE /notes/2 is good, GET /deleteNote?id=2 is not.
  • Answer POST with 201 and Location, DELETE with 204, and unsupported methods with 405 and Allow.
  • Support Idempotency-Key for POSTs that clients will retry.
  • Design PATCH operations to be idempotent where you can: prefer 'set' over 'add one'.

Mini challenge

Mini challenge: see idempotency with a counter API

Write a server with a /counter resource. POST /counter/increment adds 1, PUT /counter sets { value }, DELETE /counter resets to 0 and answers 204, and GET /counter reads it. Send the requests twice each and watch which ones change the outcome.

  • A non-POST request to /counter/increment answers 405 with Allow: POST
  • Methods other than GET, PUT and DELETE on /counter answer 405 with Allow: GET, PUT, DELETE
  • DELETE answers 204 with no body
  • Send POST twice, PUT twice, DELETE twice, then GET and PATCH once, and print one line each
counter-api.mjs
import http from "node:http";

// TODO: a counter variable and a server on port 0

// TODO: POST /counter/increment adds 1 and answers { value }
//       any other method on that URL -> 405 with an Allow header

// TODO: /counter supports GET (read), PUT (set { value }) and DELETE (reset, 204)
//       every other method -> 405 with Allow: GET, PUT, DELETE

// TODO: a call(method, path, payload) helper that prints method, path, status, body

// TODO: run: POST twice, PUT {value: 10} twice, DELETE twice, GET, then PATCH
//       and notice which repeated requests changed the outcome

Expected: The two POSTs print {"value":1} then {"value":2}, the two PUTs print {"value":10} both times, the two DELETEs print 204 both times, GET prints {"value":0}, and PATCH prints 405 with Allow: GET, PUT, DELETE.

Show hint

Switch on req.method for /counter and let the default case be the 405. Collect the request body with a for await loop to read the PUT payload, and do not write a body for 204.

Show solution
counter-api.mjs
import http from "node:http";

let counter = 0;

const server = http.createServer(async (req, res) => {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  const send = (status, body, headers = {}) => {
    const type = body === undefined ? {} : { "Content-Type": "application/json" };
    res.writeHead(status, { ...type, ...headers });
    res.end(body === undefined ? undefined : JSON.stringify(body));
  };

  if (req.url === "/counter/increment") {
    if (req.method !== "POST") return send(405, { error: "use POST" }, { Allow: "POST" });
    counter += 1;
    return send(200, { value: counter });
  }
  if (req.url !== "/counter") return send(404, { error: "not_found" });

  switch (req.method) {
    case "GET":
      return send(200, { value: counter });
    case "PUT":
      counter = JSON.parse(raw).value;
      return send(200, { value: counter });
    case "DELETE":
      counter = 0;
      return send(204);
    default:
      return send(405, { error: "method_not_allowed" }, { Allow: "GET, PUT, DELETE" });
  }
});

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

async function call(method, path, payload) {
  const res = await fetch(base + path, {
    method,
    headers: payload ? { "Content-Type": "application/json" } : {},
    body: payload ? JSON.stringify(payload) : undefined,
  });
  const allow = res.headers.get("allow");
  const text = await res.text();
  const parts = [`${method} ${path}`.padEnd(24), res.status];
  if (text) parts.push(text);
  if (allow) parts.push(`Allow: ${allow}`);
  console.log(parts.join(" "));
}

await call("POST", "/counter/increment");
await call("POST", "/counter/increment");
await call("PUT", "/counter", { value: 10 });
await call("PUT", "/counter", { value: 10 });
await call("DELETE", "/counter");
await call("DELETE", "/counter");
await call("GET", "/counter");
await call("PATCH", "/counter", { value: 1 });
server.close();

Quick quiz 1 / 3

A client sends PUT /notes/1 twice with the same body, and DELETE /notes/2 twice. Which statement is true?

Quick quiz 2 / 3

A user changes only their display name in a profile. Which request fits best?

Quick quiz 3 / 3

A server does not support DELETE on the collection, DELETE /notes. Which response is correct?

What to remember

  • A method says what to do with the URL: GET reads, POST creates, PUT replaces, PATCH changes part, DELETE removes.
  • Safe methods (GET, HEAD, OPTIONS) change nothing, idempotent methods (PUT, DELETE and the safe ones) can be repeated, and POST cannot.
  • Idempotent means the same final state, not the same response: a second DELETE may answer 404.
  • Answer unsupported methods with 405 and an Allow header, and use an Idempotency-Key for POST retries.

RFC 9110 — HTTP Semantics — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

HTTP Methods (GET/POST/PUT/DELETE) | Thuta Learning