Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 3

Methods, Status Codes and Idempotency

Choose the right HTTP method for an operation, read any status code from its class, and know which requests are safe to send again.

Contentsand lesson path

What you will learn

  • Choose the HTTP method for an operation and interpret status code classes, stating which methods are safe and which are idempotent.

Prerequisites: Python Foundations

01. Why it matters

The method of a request is a promise about what it may do, and the status code of the response is the server's verdict on what happened. Browsers, caches, proxies, crawlers and retry logic act on both without ever reading your documentation. A crawler follows any GET link it finds. An HTTP client may resend a request after a dropped connection if the method allows it. A cache may answer a GET from a stored copy.

Getting these right keeps a system predictable. Getting them wrong produces bugs that are hard to trace: an email sent twice because a request was retried, data deleted because a browser prefetched a link, or a client that keeps retrying a request that can never succeed.

This lesson covers the methods you will use every day, the two properties that matter most (safe and idempotent), how to read any status code from its first digit, and what all of this means when a call times out.

02. The methods you will use

RFC 9110 defines the core methods, and PATCH comes from RFC 5789. For a JSON API that manages notes, a typical design looks like this:

One collection, seven methods
GET     /notes?tag=http   list notes, filtered by a query parameter
GET     /notes/42         read note 42
HEAD    /notes/42         like GET, but headers only
POST    /notes            create a note; the server assigns its id
PUT     /notes/42         create or replace note 42 with the body sent
PATCH   /notes/42         change some fields of note 42
DELETE  /notes/42         remove note 42
OPTIONS /notes            ask which methods are allowed
  • GET asks for the current representation of a resource. Filters, sorting and paging belong in the query string. A body on a GET has no defined meaning, and many servers and proxies ignore or reject it.
  • HEAD is GET without the body: useful to check that something exists, how large it is or when it last changed.
  • POST asks the target resource to process the enclosed data by its own rules: add an item to a collection, submit a form, start a job, or send a prompt to a model. It is the general-purpose method for anything that is neither a plain read nor a replacement.
  • PUT stores the enclosed representation at exactly this URL, replacing whatever was there. The client decides the URL.
  • PATCH applies a partial change described in the body, for example {"title": "New title"}.
  • DELETE removes the resource at this URL.
  • OPTIONS asks what the server allows. Browsers send it on their own, as a CORS preflight, before some cross-origin requests.

03. Safe and idempotent

Two properties defined in RFC 9110 decide how other software may treat a request.

A method is safe when the client asks for no change on the server; it is a read. GET, HEAD, OPTIONS and TRACE are safe. The server may still write a log line or bump a counter. What matters is that the client did not ask for a change and cannot be held responsible for one. Because safe requests are harmless by definition, browsers prefetch them, crawlers follow them and caches store their responses.

A method is idempotent when sending the same request several times has the same intended effect on the server as sending it once. Every safe method is idempotent, and so are PUT and DELETE: replacing note 42 with the same body twice leaves the same note, and deleting it twice leaves it deleted. POST is not idempotent, because each request may create another item or trigger another action. PATCH is not guaranteed to be: setting a title is harmless to repeat, but "append a tag" or "add 1 to the counter" is not.

Idempotency is about the state left on the server, not about receiving identical responses. A repeated request may get a different status code or body while the method is still idempotent.

Safe and idempotent methods (RFC 9110; PATCH from RFC 5789)
Method    Safe   Idempotent
GET       yes    yes
HEAD      yes    yes
OPTIONS   yes    yes
PUT       no     yes
DELETE    no     yes
POST      no     no
PATCH     no     not guaranteed

These are promises your own server has to keep. If a GET handler deletes data or sends email, every prefetching browser, link checker and automatic retry becomes a way to trigger it by accident.

04. Reading status codes by class

The first digit of a status code gives its class, and the class alone tells your code what kind of next step to take. RFC 9110 says a client that meets a code it does not recognise should treat it like the x00 code of its class, so an unknown 4xx is handled like 400.

  • 1xx Informational: an interim answer before the final one, such as 100 Continue or 103 Early Hints. HTTP libraries deal with these for you.
  • 2xx Success: 200 OK; 201 Created, usually with a Location header pointing at the new resource; 204 No Content, success with no body.
  • 3xx Redirection: the client must do something more to finish. 301 and 308 mean the resource moved permanently, 302 and 307 that it is elsewhere for now, and 307 and 308 also require the method and body to be kept. 304 Not Modified answers a conditional GET: the copy you cached is still current.
  • 4xx Client error: the request itself is the problem, so sending it again unchanged usually fails again. The exceptions are about timing, not content: 408 Request Timeout and 429 Too Many Requests can succeed when retried later, and a 409 may clear once the conflicting state changes. Common ones: 400 malformed, 401 missing or invalid credentials, 403 identified but not allowed, 404 not found, 405 method not allowed (with an Allow header), 409 conflicts with the current state, 415 body format not supported, 422 well-formed but failed validation, 429 too many requests.
  • 5xx Server error: the server failed to handle a request that may have been fine. 500 is a generic failure; 502 and 504 mean a gateway or proxy got a bad answer, or no answer in time, from the server behind it; 503 means the service is temporarily unavailable.

429 and 503 often carry a Retry-After header with a number of seconds or a date; wait at least that long before trying again. The reason phrase after the number may differ between servers (RFC 9110 calls 422 "Unprocessable Content", while many servers still print the older "Unprocessable Entity"), so only the number is reliable.

Python · from status code to next step
def next_step(status: int) -> str:
    """Map a final status code to what the client should do next."""
    if 200 <= status < 300:
        return 'use the response'
    if status == 304:
        return 'use the cached copy you already have'
    if 300 <= status < 400:
        return 'follow the Location header'
    if status in (408, 429):
        return 'wait (honour Retry-After if present), then retry'
    if 400 <= status < 500:
        return 'fix the request or credentials; resending it unchanged fails again'
    if status in (502, 503, 504):
        return 'likely temporary: retry later, if the request is safe to repeat'
    return 'server error: log it and report it'


for code in (201, 304, 404, 429, 503, 500):
    print(code, '->', next_step(code))
Output
201 -> use the response
304 -> use the cached copy you already have
404 -> fix the request or credentials; resending it unchanged fails again
429 -> wait (honour Retry-After if present), then retry
503 -> likely temporary: retry later, if the request is safe to repeat
500 -> server error: log it and report it

The checks run from specific to general: 304 and the retryable codes are tested before the class ranges that contain them. Real clients add detail, such as following only a limited number of redirects, but the shape stays the same.

05. Idempotency, timeouts and retries

Networks fail between sending a request and receiving the response. When a call times out, you cannot tell whether the server never received the request, processed it and the answer was lost, or is still working on it. Idempotency decides what you may do next.

  • For safe and idempotent requests, a retry is harmless: reading twice or deleting twice leaves the same state. RFC 9110 allows clients and proxies to retry these automatically after a connection failure.
  • For POST, a blind retry can duplicate the effect: two orders, two emails, two support tickets. Two common designs make such operations safe to repeat. The client can generate the id itself and use PUT /orders/<id>, so a repeat replaces instead of duplicating. Or the client sends a unique key with the POST, often in an Idempotency-Key header; the server stores the outcome of the first request under that key and returns it again for any repeat. Payment APIs commonly work this way.
  • Some POSTs do no lasting harm when repeated. A request that asks a language model to generate text creates nothing you keep, so retrying it after a 429 or 503 costs time and tokens but corrupts no data. The same blind retry on a POST that sends a message or charges a card would not be acceptable.

Before you add a retry anywhere, ask two questions: is the failure likely to be temporary, and would doing the operation twice be harmless? Retry only when both answers are yes.

A POST that can be retried safely: the same key on every attempt
POST /v1/payments HTTP/1.1
Host: api.example.com
Content-Type: application/json
Idempotency-Key: 6f1c2a9e-8d4b-4c1e-9a7f-2b5d3e8c0a14

{"amount": 1500, "currency": "EUR", "order": "A-1042"}

The header is still an IETF draft, not an RFC. Its current text writes the key as a quoted string (Idempotency-Key: "6f1c2a9e-…"), while many APIs, Stripe among them, take the bare value shown above, so follow the documentation of the API you call.

06. Check your understanding

Practice check · 3 questions

Methods and status codes in practice

Apply the definitions to three situations from real APIs.

Q1. A client sends DELETE /notes/42 twice. The first response is 204 No Content and the second is 404 Not Found. Is the server treating DELETE as idempotent?
Q2. An admin dashboard links to GET /reports/send-weekly, which emails a report to every customer. What is the main problem?
Q3. Your request carries a valid, unexpired token, and the API answers 403 Forbidden. What does that most likely mean?
Practice only: not graded, not saved, not evidence.

07. Apply it

Take five operations from an API you use or are building, for example: list items, create an item, rename it, archive it, and start an expensive export. For each one, write down:

  1. the method and URL you would use;
  2. whether the request is safe, and whether it is idempotent;
  3. the success status code;
  4. two error status codes your client should handle differently, such as 404 (no point retrying) and 503 (may succeed later).

Mark every POST that would be harmful to repeat, and note how you would make it safe to retry: a client-chosen id with PUT, or an idempotency key.

08. Review prompt

Without looking back, sort GET, HEAD, POST, PUT, PATCH and DELETE into three groups: safe, idempotent but not safe, and neither. Then say what a client should do next after receiving 201, 304, 401, 404, 429 and 503, and explain why a timeout on a POST is harder to handle than a timeout on a GET.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check