Sub topic 6
Methods: GET, POST, and friends
This chapter assumes you can read a basic HTTP request and response (request line, headers, blank line, body) and that you know what a URL path and query string are. It covers what HTTP methods mean, which properties they promise, and the errors that come from ignoring those promises.
What a method is
The method is the first word of the request line. It tells the server what kind of action the client wants to perform on the resource named by the path.
GET /index.html HTTP/1.1
Host: example.com
Accept: text/html
The method does not change how the message is formatted. It changes what the client, the server, and every cache and proxy in between are allowed to assume. Those assumptions come from three properties defined in the HTTP specification (RFC 9110).
- Safe: the request is meant only to read. The client does not ask for any change of server state.
- Idempotent: sending the same request once or ten times leaves the server in the same state. The responses can differ.
- Cacheable: a response to this method may be stored and reused.
A server can break these promises in code, but the rest of the web will still act as if they hold. Browsers prefetch links, crawlers follow every link, and proxies retry failed requests. A "delete" action behind a GET link will eventually be triggered by one of them.
The common methods
| Method | Typical purpose | Safe | Idempotent | Request body | Cacheable |
|---|---|---|---|---|---|
| GET | Read a resource | Yes | Yes | Not used | Yes |
| HEAD | Read only the headers | Yes | Yes | Not used | Yes |
| OPTIONS | Ask what is allowed | Yes | Yes | Rare | No |
| POST | Submit data for processing | No | No | Yes | Rarely |
| PUT | Replace a resource | No | Yes | Yes | No |
| PATCH | Partially modify a resource | No | Not guaranteed | Yes | No |
| DELETE | Remove a resource | No | Yes | Rare | No |
GET
GET retrieves a representation of a resource. All the input is in the URL, so a GET request can be bookmarked, linked, cached, and repeated. Data goes in the query string:
GET /search?q=http+methods&page=2 HTTP/1.1
Host: example.com
Do not put secrets such as passwords or tokens in a query string. URLs appear in browser history, server logs, and the Referer header sent to other sites.
HEAD
HEAD is GET without the response body. The server sends the same status line and headers it would send for GET, including Content-Length, but no body. It is useful for checking whether a resource exists, how large it is, or when it last changed.
curl -I https://example.com/The -I flag makes curl send a HEAD request and print the headers.
POST
POST sends data to the server for processing. The meaning depends on the resource that receives it: creating a record, submitting a form, starting a job, or running a search with a large input. POST is neither safe nor idempotent, so repeating it may repeat the effect.
POST /orders HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 31
{"item":"book","quantity":2}The Content-Type header tells the server how to parse the body. Here the body is 28 bytes, so Content-Length must match the real size, or the server will wait for more bytes or cut the message short. Most tools compute this header for you. Check it yourself only when you write raw requests.
A successful creation usually returns 201 Created with a Location header pointing to the new resource.
PUT
PUT replaces the resource at the given URL with the body you send. Because the client names the exact target, repeating the request produces the same final state. That makes PUT idempotent.
PUT /users/42 HTTP/1.1
Host: example.com
Content-Type: application/json
{"name":"Ada","email":"[email protected]"}PUT means a full replacement. If the stored user has a phone field and your body omits it, a strict PUT implementation removes it.
PATCH
PATCH applies a partial change, such as updating only the email address. Whether it is idempotent depends on the patch format. "Set email to X" is idempotent. "Add 1 to the counter" is not.
DELETE
DELETE asks the server to remove the resource. It is idempotent in terms of server state: after the first successful call the resource is gone, and later calls leave it gone. The response may differ, for example 204 No Content the first time and 404 Not Found afterwards.
OPTIONS
OPTIONS asks which methods and features a resource supports. The server answers with an Allow header. Browsers also send OPTIONS automatically as a "preflight" request before some cross-origin requests. That mechanism is covered in the chapter on the same-origin policy and CORS.
How methods flow through the system
Idempotency and retries
Idempotency matters when a request fails halfway. Suppose a client sends a request and the connection drops before the response arrives. The client does not know whether the server processed it.
- For GET, PUT, and DELETE, retrying is safe. The end state is the same either way.
- For POST, retrying may create a duplicate order or charge a card twice.
HTTP libraries and proxies may automatically retry idempotent methods but are expected not to retry POST on their own. When you must make a POST safe to retry, a common approach is an idempotency key. The client generates a unique value and sends it in a header, often named Idempotency-Key. The server stores the result under that key and returns the stored result if the same key arrives again. This header is a convention used by some APIs, not part of core HTTP, so check the API's documentation.
Forms and the browser
HTML forms can only use two methods: GET and POST.
<form action="/search" method="get">
<input name="q">
<button>Search</button>
</form>With method="get", the browser puts the fields in the query string. With method="post", it sends them in the body, by default as application/x-www-form-urlencoded. To use PUT or DELETE from a page, JavaScript must send the request with fetch:
const response = await fetch("/users/42", {
method: "DELETE",
});
console.log(response.status);Some frameworks fake other methods by adding a hidden form field such as _method=DELETE and rewriting the method on the server. This is a framework feature, not HTTP.
After a browser handles a POST form, it is common to answer with a 303 See Other redirect to a GET page. This is the Post/Redirect/Get pattern. It prevents the browser's "resubmit the form?" prompt when the user reloads, because reloading repeats the final GET rather than the POST.
Handling methods on a server
A server routes on the combination of method and path. This Node.js example answers differently for each method and rejects the rest.
import { createServer } from "node:http";
const items = new Map();
const server = createServer((req, res) => {
const url = new URL(req.url, "http://localhost");
if (url.pathname !== "/items") {
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Not found\n");
return;
}
if (req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify([...items.values()]));
} else if (req.method === "POST") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
const id = String(items.size + 1);
items.set(id, { id, text: body });
res.writeHead(201, { Location: `/items/${id}` });
res.end();
});
} else {
res.writeHead(405, { Allow: "GET, POST" });
res.end();
}
});
server.listen(3000);Test it with curl:
curl -i -X POST --data "buy milk" http://localhost:3000/items
curl -i http://localhost:3000/items
curl -i -X DELETE http://localhost:3000/itemsThe first call returns 201 Created. The second returns the stored list. The third returns 405 Method Not Allowed with an Allow header listing the accepted methods.
Common errors
- Changing state with GET. A link such as
/delete?id=7can be triggered by prefetching, crawlers, or an attacker's image tag. Use POST or DELETE for changes. - Using POST for everything. It works, but you lose caching, safe retries, and clear semantics.
- Treating PUT as a partial update. A strict PUT replaces the whole resource. Use PATCH for partial changes.
- Sending a body with GET. The specification gives it no defined meaning, and some servers and proxies drop it. Put the input in the query string, or use POST if it is too large.
- Returning 200 for unsupported methods. Return
405 Method Not Allowedwith anAllowheader. Use501 Not Implementedonly when the server does not recognize the method at all. - Method names are case-sensitive.
getis notGET. Servers typically reject the lowercase form.
Exercise
A client sends PUT /users/42 with a full user record, and the connection drops before the response arrives. Is it safe to retry, and why? Would your answer change for POST /users?
Show answer
Yes, retrying PUT is safe because PUT is idempotent. Sending the same full replacement twice leaves user 42 in the same state. POST /users is not idempotent, so a retry could create a second user. For POST, use an idempotency key or check for the earlier result before retrying.
Exercise
A page has a link <a href="/cart/clear">Empty cart</a> that empties the user's cart when the server receives GET /cart/clear. Name two things that could trigger it unintentionally and describe a better design.
Show answer
A browser prefetching the link, a crawler following it, or a malicious page embedding it as an image can all trigger it. A better design makes it a POST (or DELETE sent with fetch) request, because those methods are not safe and are not fired by prefetching or crawling.