Skills101

AdvancedWeb Development · Lesson 16 of 19 · Updated ·

HTTP for Web Developers — Methods, Status Codes, Headers and Good API Design

Every click on a website, every fetch call and every API request is an HTTP message. When something breaks — "the form says error", "the data doesn't update" — the answer is usually in the HTTP request or response, visible in the DevTools Network tab. This lesson teaches you to read and design those messages. The Node.js examples start a real local server, call it, print what happened and stop.

1. The shape of a request and a response

HTTP (HyperText Transfer Protocol) is a request–response protocol: the client sends a request, the server sends back exactly one response.

An HTTP request has a method and path (POST /api/enquiries), headers such as Content-Type and Authorization, a blank line and an optional JSON body; the response has a status line (201 Created), headers and a body

A request has:

  1. a method — what you want to do (GET, POST, …)
  2. a path (and optional query string) — which resource (/api/courses?level=beginner)
  3. headers — extra information as Name: value lines
  4. an optional body — the data you send (usually JSON)

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

const http = require("http");

const server = http.createServer((req, res) => {
  let body = "";
  req.on("data", (chunk) => (body += chunk));
  req.on("end", () => {
    console.log("server got:", req.method, req.url, req.headers["content-type"], body);
    res.writeHead(201, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ id: 7, status: "received" }));
  });
});

server.listen(0, async () => {
  const port = server.address().port;           // 0 = any free port
  const res = await fetch(`http://localhost:${port}/api/enquiries`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "Asha", course: "Java" }),
  });
  console.log("client got:", res.status, res.statusText, res.headers.get("content-type"));
  console.log(await res.json());
  server.close();
});
server got: POST /api/enquiries application/json {"name":"Asha","course":"Java"}
client got: 201 Created application/json
{ id: 7, status: 'received' }

2. Methods and what they promise

MethodMeaningBody?SafeIdempotent
GETread a resourcenoyesyes
POSTcreate something / run an actionyesnono
PUTreplace a resource completelyyesnoyes
PATCHchange part of a resourceyesnonot guaranteed
DELETEremove a resourceusually nonoyes

Two words interviewers love:

  • Safe — the request does not change data on the server. GET must be safe: browsers, crawlers and caches send GETs freely. Never delete or update anything on a GET.
  • Idempotent — sending the same request once or ten times leaves the server in the same state.

Why idempotency matters: on a weak mobile network, a request can time out even though the server processed it. Clients and proxies may safely retry idempotent requests. Retrying a POST /orders could create two orders — which is why payment APIs ask you to send an idempotency key so the server can spot repeats.

// Simulate the server's state after repeating the same request 3 times
let course = { id: 7, title: "SQL", price: 499 };
const orders = [];

for (let i = 0; i < 3; i++) course = { id: 7, title: "SQL", price: 399 };   // PUT: replace
for (let i = 0; i < 3; i++) orders.push({ course: 7 });                     // POST: create

console.log("after 3 PUTs:", course.price);
console.log("after 3 POSTs:", orders.length, "orders");
after 3 PUTs: 399
after 3 POSTs: 3 orders

3. Status codes

The first digit gives the family:

Status code families: 1xx informational, 2xx success (200, 201, 204), 3xx redirection (301, 302, 304), 4xx client error (400, 401, 403, 404, 409, 422, 429), 5xx server error (500, 502, 503)

CodeNameUse it when
200OKa normal successful response with a body
201Createda POST created something (often with a Location header)
204No Contentsuccess, nothing to send back (typical for DELETE)
301 / 302Moved Permanently / Foundredirect to another URL
304Not Modifiedthe client's cached copy is still fresh (section 5)
400Bad Requestthe request is malformed (broken JSON, missing field)
401Unauthorizednot logged in — no valid credentials
403Forbiddenlogged in, but not allowed
404Not Foundthe resource does not exist
409Conflictclashes with current state (email already registered)
422Unprocessable Contentwell-formed, but fails validation
429Too Many Requestsrate limit reached
500Internal Server Errora bug or crash on the server
502 / 503Bad Gateway / Service Unavailablean upstream server failed, or the server is overloaded or down

401 vs 403 is a classic question: 401 = "who are you?"; 403 = "I know who you are, and you can't do this".

Rule of thumb: 4xx means the client should change something; 5xx means the server has a problem. Returning 200 with { "error": "…" } breaks this and confuses every tool that reads status codes.

4. Headers worth knowing

HeaderDirectionExamplePurpose
Content-Typebothapplication/jsonformat of the body
Acceptrequestapplication/jsonformats the client wants back
AuthorizationrequestBearer eyJhbGci…credentials (tokens)
Cookie / Set-Cookierequest / responsesid=abc123sessions (next lessons)
Cache-Controlresponsemax-age=3600how long the response may be cached
ETag / If-None-Matchresponse / request"v42"version check for caching
Locationresponse/api/orders/91URL of a new resource, or redirect target
Access-Control-Allow-Originresponsehttps://skills101.inCORS: which other sites' pages may read the response

Header names are case-insensitive: content-type and Content-Type are the same header.

5. Caching with ETag and 304

Downloading the same course list again and again wastes data — a real cost for users on mobile plans. With an ETag (a version label for the response), the browser can ask "has it changed?", and the server can reply 304 Not Modified with no body.

const http = require("http");
const courses = JSON.stringify([{ id: 1, title: "DSA" }, { id: 2, title: "SQL" }]);
const etag = '"v42"';

const server = http.createServer((req, res) => {
  if (req.headers["if-none-match"] === etag) {
    res.writeHead(304, { ETag: etag });
    return res.end();
  }
  res.writeHead(200, { "Content-Type": "application/json", ETag: etag });
  res.end(courses);
});

server.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/api/courses`;
  const first = await fetch(url);
  const text = await first.text();
  console.log("first:", first.status, first.headers.get("etag"), text.length, "bytes");
  const second = await fetch(url, { headers: { "If-None-Match": first.headers.get("etag") } });
  console.log("second:", second.status, (await second.text()).length, "bytes");
  server.close();
});
first: 200 "v42" 47 bytes
second: 304 0 bytes

Browsers do this automatically for normal page loads; you only need to send the ETag (most frameworks can do it for you).

6. Designing a clean REST API

Building on the REST rules from the Express lesson:

GoodAvoid
GET /api/coursesGET /api/getCourses
GET /api/courses/7/lessonsGET /api/lessonsOfCourse?id=7
POST /api/courses/7/enrolmentsGET /api/enrol?course=7 (a GET that changes data!)
GET /api/courses?level=beginner&page=2&limit=20returning 10,000 rows at once
/api/v1/courseschanging response fields without warning

Good habits:

  • Nouns in paths, methods as verbs, plural collections.
  • Filtering, sorting and pagination through the query string; always cap the page size.
  • Consistent errors: the right status code plus a body like { "error": "phone is required", "field": "phone" }.
  • Version the API (/v1/) once outside apps depend on it, so breaking changes go to /v2/.
  • HTTPS everywhere: HTTP sends everything, including passwords and tokens, as readable text.

Common mistakes

  • Changing data in a GET handler (a crawler following links could delete records).
  • Returning 200 for errors, or 500 for a user's typing mistake.
  • Mixing up 401 and 403.
  • Forgetting Content-Type: application/json when sending JSON, so the server cannot parse the body.
  • Retrying a non-idempotent POST automatically and creating duplicates.

Quick recap

  • Request = method + path + headers + optional body; response = status + headers + optional body.
  • GET (safe), PUT and DELETE are idempotent; POST is not, so retries can duplicate.
  • 2xx success · 3xx redirect/cache · 4xx client's fault · 5xx server's fault; 401 = not logged in, 403 = not allowed.
  • Key headers: Content-Type, Authorization, Cookie, Cache-Control, ETag.
  • ETag + If-None-Match → 304 saves bandwidth; design APIs with nouns, pagination, versioning and consistent errors.

Practice what you learned

📝 Quiz: HTTP Methods, Status Codes and Headers5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →