What a REST request and response look like
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.
Step by step
- The client sends a request line: a method, a target and the protocol version.
- Headers follow, one per line, such as
HostandContent-Type. - An empty line ends the headers, and the body, if there is one, comes after it.
- The server answers with a status line: the protocol version, a status code and optional text.
- The first digit of the code groups the outcome: 2xx is success, 4xx is a client error, 5xx is a server error.
- A
201 Createdresponse can carry aLocationheader 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
- MDN: HTTP messages — the four parts, the request line and status line formats, headers, the example
201 Createdresponse withLocation, HTTP/2 pseudo-headers - MDN: HTTP request methods — what GET, POST, PUT and DELETE ask for, and which are safe and idempotent
- MDN: HTTP response status codes — the code classes and the meaning of 201 Created