What a REST request and response look like

· 2 min read

#how-it-works#web

Calls to a web API travel as HTTP messages. The idea to keep: the request and the response have the same four parts, in the same order.

The short version

An HTTP/1.1 message is a start line, headers, an empty line and an optional body. In a request, the start line holds a method, a target such as /users and the protocol version. In a response, it holds the protocol version, a status code and optional text. The diagram follows a request that creates a user and the reply that comes back.

The parts of an HTTP request and response Top row, a request made of a request line, headers and a body. An arrow points down to the bottom row, a response made of a status line, headers and a body. Request Request line POST /users HTTP/1.1 Headers Host, Content-Type Body after a blank line server replies Response Status line HTTP/1.1 201 Created Headers Location Body optional
Simplified: the HTTP/1.1 text format, with the request line and the status line highlighted.

Step by step

  1. The client sends a request line: a method, a target and the protocol version.
  2. Headers follow, one per line, such as Host and Content-Type.
  3. An empty line ends the headers, and the body, if there is one, comes after it.
  4. The server answers with a status line: the protocol version, a status code and optional text.
  5. The first digit of the code groups the outcome: 2xx is success, 4xx is a client error, 5xx is a server error.
  6. A 201 Created response can carry a Location header that points to the new resource.
Method Asks for Safe Idempotent
GET a representation of the resource yes yes
POST sends data, may change state on the server no no
PUT replaces the target's representations with the request body no yes
DELETE deletes the resource no yes

Why it matters

Because PUT and DELETE are idempotent, repeating one gives the same result, while a POST may change the server's state every time it arrives, so it is the one to retry with care.

Sources