Skip to the content

Lesson 194 of 296

HTTP methods, status codes and headers

What you will learn

  • The structure of HTTP requests and responses
  • HTTP methods and their properties: safe and idempotent
  • Status codes and when to use each
  • Important headers
  • PUT vs PATCH, 401 vs 403, and other trick questions
On this page

Requests and responses

HTTP (Lesson 1) is text-based request and response:

POST /api/orders HTTP/1.1
Host: shop.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOi...
Idempotency-Key: 7c1d9e0a-...

{"productId":"mug-01","quantity":2}
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/orders/ord_123

{"id":"ord_123","status":"pending"}

A request has a method, a path, headers and an optional body. A response has a status code, headers and an optional body.

Methods

MethodPurposeSafeIdempotentBody
GETRead a resourceYesYesNo
HEADLike GET but headers onlyYesYesNo
OPTIONSAsk what is allowed (used by CORS preflight, Lesson 199)YesYesNo
POSTCreate, or perform an actionNoNoYes
PUTReplace a resource completely (or create at a known URL)NoYesYes
PATCHPartly update a resourceNoNot guaranteedYes
DELETEDelete a resourceNoYesUsually no
  • Safe means it does not change anything on the server (read-only). Browsers and crawlers may call safe methods freely, so never change data in a GET (a crawler following links could delete records).
  • Idempotent means doing it once or many times has the same effect on the server. Deleting order 5 twice leaves it deleted; PUT with the same body twice gives the same result. POST "create order" twice creates two orders. Idempotency matters for safe retries (Lesson 195).

PUT vs PATCH (very common): PUT sends the whole resource and replaces it; missing fields are removed or reset. PATCH sends only the fields to change. Most APIs use PATCH for edits.

Status codes

RangeMeaning
1xxInformational (rare; 101 Switching Protocols is used for WebSockets)
2xxSuccess
3xxRedirection or "use your cache"
4xxClient error: the request was wrong
5xxServer error: the server failed

The codes you must know:

CodeNameUse
200OKSuccessful GET, PUT or PATCH with a body
201CreatedA POST created a resource; include a Location header
202AcceptedAccepted for later processing (a background job)
204No ContentSuccess with no body (often DELETE)
301 / 308Moved Permanently / Permanent RedirectURL changed forever (308 keeps the method and body)
302 / 307Found / Temporary RedirectTemporary move (307 keeps the method and body)
304Not ModifiedYour cached copy is still valid (Lesson 198)
400Bad RequestMalformed request (invalid JSON, missing fields)
401UnauthorizedNot authenticated: no valid login or token
403ForbiddenAuthenticated but not allowed
404Not FoundThe resource does not exist (also used to hide resources the user may not see)
405Method Not Allowede.g. DELETE on an endpoint that does not support it
409ConflictConflicts with current state: duplicate email, version conflict
410GoneExisted but permanently removed
412Precondition FailedAn If-Match check failed (optimistic locking, Lesson 225)
413Content Too LargeBody too big (upload limits)
415Unsupported Media TypeWrong Content-Type
422Unprocessable ContentValid JSON but fails validation rules
429Too Many RequestsRate limited; include Retry-After (Lesson 238)
500Internal Server ErrorAn unexpected bug
502Bad GatewayA proxy got a bad response from the upstream server
503Service UnavailableOverloaded or under maintenance; temporary
504Gateway TimeoutA proxy timed out waiting for the upstream server

401 vs 403 (asked constantly): 401 means "who are you? log in"; 403 means "I know who you are, and you cannot do this". The name "Unauthorized" for 401 is historically confusing: it really means unauthenticated.

400 vs 422: many APIs use 400 for all invalid input; others use 400 for malformed requests and 422 for well-formed input that breaks validation rules. Either is fine if consistent.

Should "not allowed to see it" be 403 or 404? Returning 404 for another tenant's record avoids revealing that it exists (Lesson 203).

Important headers

HeaderPurpose
Content-TypeFormat of the body: application/json, text/html; charset=utf-8, multipart/form-data
AcceptFormats the client wants back
AuthorizationCredentials: Bearer <token> or Basic ...
Cookie / Set-CookieCookies sent by the browser / set by the server
Cache-Control, ETag, If-None-MatchCaching (Lesson 198)
LocationURL of a created resource or a redirect target
Retry-AfterWhen to retry after 429 or 503
Origin, Access-Control-Allow-OriginCORS (Lesson 199)
User-AgentThe client software
X-Request-Id (or the traceparent standard)An ID to trace one request through logs and services
Idempotency-KeyMakes POST retries safe (Lesson 195)

Header names are case-insensitive.

How to say it in an interview

"GET, HEAD and OPTIONS are safe and idempotent; PUT and DELETE are idempotent but not safe; POST is neither, and PATCH is not guaranteed to be idempotent. PUT replaces a whole resource while PATCH changes some fields. I return 201 with a Location header for creation, 204 for empty success, 400 or 422 for invalid input, 401 when not authenticated, 403 when authenticated but not allowed, 404 also to hide other tenants' records, 409 for conflicts, 429 with Retry-After for rate limits, and 5xx only for server failures. Key headers include Content-Type, Authorization, Cache-Control and ETag, Location and a request ID for tracing."

Key words

WordMeaning
MethodThe action of a request (GET, POST...)
Safe methodDoes not change server state
IdempotentSame effect whether done once or many times
Status codeA three-digit result code
HeaderA name and value giving extra information about a request or response
401 vs 403Not authenticated vs not allowed

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.