Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 39 ยท Web APIs and AJAX Basics

HTTP for AJAX Developers

The HTTP basics every AJAX developer needs: methods, URLs, status codes, headers, bodies, idempotency and caching, with Request and Response demos.

Every AJAX call is an HTTP message, and every server reply is another one. When something goes wrong (a 404, a missing header, a body the server can't read), the fix usually comes from understanding those messages. This lesson gives you the vocabulary. You don't need to memorize the whole protocol, only the parts you will use daily.

HTTP is a request and response protocol. The client sends one request, the server sends one response, and each message is plain structured text (or bytes) made of a first line, headers and an optional body. Browsers and fetch() build these messages for you, but you control the important parts.

Anatomy of a request and a response

flowchart TB
    subgraph REQ["Request"]
        direction TB
        R1["Start line: POST /api/comments HTTP/1.1"]
        R2["Headers: Host, Content-Type, Accept ..."]
        R3["Body: optional, e.g. JSON"]
        R1 --- R2 --- R3
    end
    subgraph RES["Response"]
        direction TB
        S1["Status line: HTTP/1.1 201 Created"]
        S2["Headers: Content-Type, Location, Cache-Control ..."]
        S3["Body: optional, e.g. JSON"]
        S1 --- S2 --- S3
    end
    REQ --> RES

A request and its response have the same three parts: a first line, headers and an optional body.

In fetch() terms:

  • The method and URL form the request's first line.
  • The headers option sets the headers; the body option sets the body.
  • On the way back, response.status and response.statusText are the status line, response.headers the headers, and response.json() or response.text() read the body.

Methods say what you want to do

The method (also called the verb) tells the server what kind of action the request represents.

Method Typical use Has a request body? Safe? Idempotent?
GET Read a resource No Yes Yes
POST Create something, or run an action Yes No No
PUT Replace a resource completely Yes No Yes
PATCH Change part of a resource Yes No Usually not guaranteed
DELETE Remove a resource Rarely No Yes
HEAD Like GET, but headers only No Yes Yes
OPTIONS Ask what is allowed (used by CORS preflight) No Yes Yes

Two words in that table matter a lot:

  • A method is safe when it should not change anything on the server. Browsers, caches and crawlers rely on GET being safe; that is why a "delete" link must never be a plain GET.
  • A method is idempotent when sending the same request many times has the same effect as sending it once. Deleting the same record twice leaves the record gone either way. Sending the same POST twice usually creates two records. This is why retrying a failed POST needs care, a topic the retries lesson returns to.

You can read more about how requests are built in Sending Data: POST, PUT, PATCH, DELETE.

URLs and their parts

A URL tells the browser where to send the request. Instead of cutting it apart with string tricks, use the built-in URL class:

JS The parts of a URL

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two details to remember. The fragment (#top) is never sent to the server; it stays in the browser. And the origin (scheme, host and port) is what the browser's same-origin rules look at.

Status codes tell you what happened

The three-digit status code is the server's summary of the result. They group into five families by the first digit.

Range Meaning Common examples
1xx Informational 101 Switching Protocols (WebSocket upgrade)
2xx Success 200 OK, 201 Created, 204 No Content
3xx Redirect 301 Moved Permanently, 302 Found, 304 Not Modified
4xx The client made a mistake 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Content, 429 Too Many Requests
5xx The server failed 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout

A few worth understanding well:

  • 201 Created often comes with a Location header pointing at the new resource.
  • 204 No Content means success with an empty body. Calling response.json() on it throws, so check for it.
  • 401 means "I don't know who you are" (missing or bad credentials), while 403 means "I know who you are, and you may not do this."
  • 422 is popular for validation errors: the request was well-formed but the data was not acceptable.
  • 429 means you are sending too many requests; wait and retry.

The 4xx and 5xx split is useful in code: a 4xx usually means retrying the same request is pointless, while a 5xx may be temporary.

Headers carry the metadata

Headers are name and value pairs sent with both requests and responses. Names are case-insensitive. A few appear constantly in AJAX work:

Header Direction Purpose
Content-Type Both The format of the body, such as application/json
Accept Request The formats the client can handle
Authorization Request Credentials, such as Bearer <token>
Cache-Control Both Caching rules, such as max-age=60 or no-store
Location Response Where a new or moved resource lives
Set-Cookie / Cookie Response / Request Cookie handling
Retry-After Response How long to wait before trying again (with 429 and 503)
Access-Control-Allow-Origin Response CORS permission

The browser adds many headers on its own (Host, User-Agent, Origin, Cookie) and does not let your code override some of them. Headers are covered in depth in Headers, Auth and CORS Basics.

Building and inspecting messages without a network

You can create Request and Response objects directly, with no network involved. That is the best way to see what the protocol looks like.

JS A Request and a Response, side by side

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Header lookups with headers.get() ignore case, so "content-type" and "Content-Type" find the same header.

A tiny status code router

To feel how status codes drive your code, here is a mock server function that returns different statuses, and a client that reacts to each family. This is the decision tree you will write in real projects.

JS Reacting to status codes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Caching basics

Browsers can store responses and reuse them. For AJAX this matters in two ways: it makes repeated reads fast, and it can make you look at stale data. The server controls this with response headers:

  • Cache-Control: max-age=60: the response can be reused for 60 seconds without asking the server.
  • Cache-Control: no-store: never keep a copy (used for private or sensitive data).
  • ETag and Last-Modified: validators. The browser asks "has this changed?" and the server can answer 304 Not Modified with no body, saving bandwidth.

GET responses are cacheable by default rules; POST responses mostly are not. If your JSON seems stuck on old values, open the Network panel and check for a cache hit (see Debugging Network Requests). The details of ETags and conditional requests come in Caching and Polling.

Rule of thumb. Use GET for reading, POST for creating or running an action, PUT or PATCH for updating, and DELETE for removing. Pick the status code that matches the outcome instead of always returning 200.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method is both safe and idempotent?

    GET only reads, so it changes nothing (safe), and repeating it has the same effect (idempotent). DELETE is idempotent but not safe, and POST is neither.
  2. 2. A server answers 401. What does it most likely mean?

    401 means the client has not authenticated properly. A missing resource is 404, a crash is 5xx and permission problems for a known user are 403.
  3. 3. You call response.json() on a 204 No Content reply. What happens?

    An empty body is not valid JSON, so parsing fails with a SyntaxError. Check for 204 (or an empty body) before parsing.
  4. 4. Which part of a URL is never sent to the server?

    The fragment stays in the browser. The path and query string are part of the request line.
  5. 5. Which status family usually means the client should fix the request rather than retry it unchanged?

    4xx codes describe a problem with the request itself. 5xx codes are server-side failures that may be temporary.

Summary

  • An HTTP message has a first line, headers and an optional body; fetch() exposes all three.
  • Methods describe intent: GET reads, POST creates or acts, PUT replaces, PATCH changes part, DELETE removes.
  • Safe methods change nothing; idempotent methods can be repeated with the same result, which matters for retries.
  • Status codes come in families: 2xx success, 3xx redirect, 4xx client mistake, 5xx server failure.
  • Headers such as Content-Type, Accept, Authorization and Cache-Control carry the metadata; names are case-insensitive.
  • Caching headers control reuse and revalidation; new Request() and new Response() let you inspect messages with no network.

Next: Web APIs and REST in Practice โ€” how servers organize their endpoints into resources.