HTTP, the language of requests
Clients and servers talk in a text protocol called HTTP (HyperText Transfer Protocol). A raw request is literally lines of text:
GET /users/42 HTTP/1.1 Host: api.example.com Accept: application/json
Line by line:
- The request line: a method (
GET), a path (/users/42), and the protocol version. - Headers:
Name: valuepairs carrying metadata.Hostnames the server the request is meant for; during development that islocalhost:3000, wherelocalhostmeans “this very machine” and 3000 is the port from lesson 1-2.Acceptsays what format the client wants back. - Optionally a blank line and then a body with data (used when sending things, like a signup form).
The method is the verb. The four you will use constantly: GET (read), POST (create), PUT/PATCH (update), DELETE (remove).
And the response
The server answers in the same style:
HTTP/1.1 200 OK Content-Type: application/json {"id": 42, "name": "Ada"}
- The status line carries the status code:
200OK,404not found,500server crashed. Unit 3 covers the full families. - Headers again, like
Content-Typetelling the client the body is JSON. - The body: the actual content.
Frameworks will parse this text for you, but a backend engineer should be able to read it raw. Let's prove you can, by writing the parser yourself.
Code exercise · javascript
Run this parser for the request line. split(" ") cuts the string at each space.
Quiz
A client sends: POST /orders HTTP/1.1 with a JSON body describing a pizza. What is the client most likely doing?
Code exercise · javascript
Your turn. Write parseHeader(line) that turns "Content-Type: application/json" into { name: "content-type", value: "application/json" }. Header names are case-insensitive, so lowercase the name. The value may contain colons (think "Host: localhost:3000"), so split only at the FIRST colon.
Code exercise · javascript
Your turn. Now build the other direction: formatResponse(status, reason, body) must produce the raw response text, i.e. the status line "HTTP/1.1 <status> <reason>", a Content-Type header, a blank line, then the body. Join the parts with \n (real HTTP uses \r\n line endings, but \n keeps the sandbox output readable).