Backend Development
ConceptBeginner 20 min· Foundations · 2 of 20

HTTP in depth: methods, status codes and headers

HTTP is the language clients and servers speak. Learn the anatomy of a request and response, the main methods, the status codes you must know and the headers that matter, and try it yourself with curl.

HTTP (HyperText Transfer Protocol) is the set of rules a client and a server follow to talk. It is plain text, it is request and response, and it is the base of every web API you will build.

A client sends a request. The server sends back one response. Each message is small and independent: the server does not remember the previous one (that is why we call HTTP stateless).

Anatomy of a request

A raw HTTP request
POST /orders HTTP/1.1
Host: api.brewandbean.example
Content-Type: application/json
Accept: application/json
Authorization: Bearer eyJhbGciOi...

{"customer_name": "Asha", "phone": "9876543210", "items": [{"item_id": "espresso", "qty": 2}]}

Line 1 is the request line: method, path, version. Then headers, a blank line, then the optional body.

The parts of a request

PartWhat it isExample
MethodThe action wantedPOST
URL / pathWhich resource/orders, /orders/42
Query stringOptional filters after ?/menu?category=coffee
HeadersMetadata about the requestContent-Type: application/json
BodyThe data sent (not on GET)A JSON order

Anatomy of a response

A raw HTTP response
HTTP/1.1 201 Created
Content-Type: application/json
Location: /orders/42

{"id": 42, "status": "received", "total": 240}

The status line has the code and its reason phrase. Then headers, a blank line and the body.

Methods

The method says what you want to do with the resource. Two properties matter:

- Safe: it does not change anything on the server (it only reads). - Idempotent: doing it once or ten times leaves the server in the same state. This matters when a network drops and the client retries.

The main methods

MethodMeaningSafeIdempotentBodyExample
GETRead a resourceYesYesNoGET /menu
POSTCreate something or run an actionNoNoYesPOST /orders
PUTReplace a resource completelyNoYesYesPUT /menu/espresso
PATCHChange part of a resourceNoNot guaranteedYesPATCH /orders/42/status
DELETERemove a resourceNoYesUsually noDELETE /orders/42
HEADLike GET but only headersYesYesNoCheck if a file exists
OPTIONSAsk what is allowedYesYesNoBrowser CORS preflight

Never change data with GET

Browsers, search engines and link previews fetch GET URLs freely and may repeat them. A URL like GET /orders/42/cancel can be triggered by a prefetch or a crawler. Use POST, PATCH or DELETE for anything that changes data.

Why idempotency matters: if POST /orders times out and the app retries, the customer may get two coffees. PUT /menu/espresso with the same body twice is harmless. For payments and orders, APIs often accept an idempotency key header so a retried request is recognised as the same one.

Status codes

The status code is a three-digit number telling the client what happened. The first digit is the family. Always return an accurate code: clients and tools rely on it.

Families

RangeMeaning
1xxInformational (rarely seen)
2xxSuccess
3xxRedirection
4xxThe client made a mistake
5xxThe server failed

Codes you must know

CodeNameUse it when
200OKA successful GET, PATCH or PUT with a body
201CreatedA new resource was made (POST); add a Location header
204No ContentSuccess with nothing to return (often DELETE)
301 / 308Moved permanentlyThe URL changed for good
304Not ModifiedThe cached copy is still valid
400Bad RequestThe request is malformed or invalid
401UnauthorizedNot logged in or bad credentials (really means unauthenticated)
403ForbiddenLogged in but not allowed
404Not FoundThe resource does not exist
405Method Not AllowedThe path exists but not for this method
409ConflictClashes with current state (duplicate email)
422Unprocessable ContentWell-formed but fails validation (FastAPI uses this)
429Too Many RequestsRate limit exceeded
500Internal Server ErrorAn unexpected bug on the server
502 / 503 / 504Bad gateway / Unavailable / Gateway timeoutA server behind a proxy failed, is overloaded or timed out

401 versus 403

401 means "I don't know who you are": send credentials. 403 means "I know who you are, and the answer is no". A customer trying to view another customer's order gets 403 (or 404, if you want to hide that it exists).

Headers

Headers are Name: value pairs that carry information about the message, not the data itself. Names are case-insensitive. These are the ones you will use constantly.

Important headers

HeaderDirectionPurpose
Content-TypeBothFormat of the body, e.g. application/json
AcceptRequestFormat the client wants back
AuthorizationRequestCredentials, e.g. Bearer <token>
Cookie / Set-CookieRequest / ResponseSend and set cookies
LocationResponseWhere the new or moved resource is
Cache-ControlResponseHow long and by whom it may be cached
ETagResponseA version tag for conditional requests
Access-Control-Allow-OriginResponseCORS: which web origins may call this API
User-AgentRequestWhich client is calling
Retry-AfterResponseHow long to wait after 429 or 503

Content-Type is the one beginners forget. If you send JSON but leave out Content-Type: application/json, many frameworks will not parse the body and you will see empty data or a 415 or 422 error.

Try it yourself with curl

curl is a command-line HTTP client, included with Windows 10 and 11, macOS and Linux. We will call a free public test API, JSONPlaceholder, which accepts requests and returns fake data. On Windows PowerShell, type curl.exe (plain curl is an alias for something else); in Git Bash, curl works.

Terminal
curl -i https://jsonplaceholder.typicode.com/posts/1

-i prints the response headers as well as the body.

Roughly what you will see
HTTP/2 200
content-type: application/json; charset=utf-8
cache-control: max-age=43200
...

{
  "userId": 1,
  "id": 1,
  "title": "...",
  "body": "..."
}
Terminal: send a POST with JSON
curl -i -X POST https://jsonplaceholder.typicode.com/posts \
  -H "Content-Type: application/json" \
  -d '{"title": "coffee", "body": "cold brew", "userId": 1}'

Expect 201 Created and a JSON body with a new id. In Windows PowerShell, use curl.exe and write it on one line with the JSON in single quotes escaped as "{\"title\": \"coffee\"}", or use Git Bash.

Terminal: see a 404
curl -i https://jsonplaceholder.typicode.com/posts/99999

Returns 404 Not Found with an empty JSON object.

Other things worth knowing

Quick notes

TopicWhat to remember
HTTPSHTTP over TLS encryption. Always use it in production so passwords and tokens are not readable on the network.
CookiesSmall values the server sets (Set-Cookie) and the browser sends back automatically; used for sessions.
CORSA browser rule: a page from one origin may call another origin only if the server's Access-Control-Allow-Origin header allows it. It is not a server-side security feature; tools like curl ignore it.
HTTP versionsHTTP/1.1 is text based; HTTP/2 and HTTP/3 are faster on the wire but the methods, codes and headers are the same.
TimeoutsA request can hang. Clients and servers should set timeouts.

You can watch real HTTP in the browser: open DevTools (F12), choose the Network tab, reload a page and click any request to see its method, status, headers and body.

How this comes up in interviews

Common questions: the difference between PUT and PATCH (replace versus partial update); what idempotent means and which methods have it; 401 versus 403; when to return 201 versus 200; what CORS is and why the browser blocks a request; what happens on GET versus POST regarding caching and bodies. Give a short definition and one example each.

Prompt · Explain a response I got
I called [METHOD] [URL] and received status [CODE] with this response body:

---
[paste body and relevant headers]
---

Explain in plain English what the status code means, the most likely causes in my situation ([framework, e.g. FastAPI]) and what I should check first. Do not guess; list causes in order of likelihood.

What to expect: A good answer separates client mistakes (4xx) from server bugs (5xx) and suggests concrete checks such as the Content-Type header, the URL spelling or the server logs.

Try it: Choose the status code

For Brew & Bean, pick the best status code for each case:

1. A customer places a valid order. 2. GET /orders/9999 and no such order exists. 3. POST /orders with qty: -3. 4. Staff calls PATCH /orders/5/status but is not logged in. 5. A customer tries to read someone else's order. 6. The database is down. 7. A customer's cancel request succeeds and there is nothing to return.

Try it: Inspect real traffic

Open any website, press F12, go to the Network tab and reload. Find one request with a JSON response. Write down its method, status code, the Content-Type response header and whether it has a Cache-Control header.

Key takeaways

  1. A request has a method, path, headers and optional body; a response has a status code, headers and optional body.
  2. GET reads and must not change data; POST creates or triggers actions; PUT replaces; PATCH partially updates; DELETE removes.
  3. Idempotent methods (GET, PUT, DELETE) are safe to retry; POST is not unless you add an idempotency key.
  4. Return accurate status codes: 2xx success, 4xx client error, 5xx server error. Know 200, 201, 204, 400, 401, 403, 404, 409, 422, 429 and 500.
  5. 401 means unauthenticated; 403 means authenticated but not allowed.
  6. Set Content-Type: application/json when sending JSON, and use curl or the browser Network tab to inspect real traffic.

Check yourself

Finishing the quiz marks the lesson as done.

1. A client retries a request after a network timeout. Which method is dangerous to retry blindly because it may create a duplicate?

2. A logged-in customer requests another customer's order. Which status fits best?

3. What is the difference between PUT and PATCH?

4. You POST JSON but the server sees an empty body. What is the most likely missing piece?

5. Which family of status codes means the server itself failed?

6. A browser blocks your frontend's call to your API with a CORS error, but curl works. Why?

Saved on this device. Create a free account to keep it on every device.

Practise this with Sam

A real mock interview, out loud, with an honest scorecard. Free to start.

Start free