Request & Response — API

A request is made of a first line (method, path), headers, a blank line, then the body. A response has the same shape, but its first line holds the status…

You send a new book from the admin form. The body is correct JSON, and the title is clearly there. Yet the server answers with the status 500 (an error in the server), because to the server's code, the body isn't there at all. Nothing is misspelled. What's missing is one line outside the body. To find it, you first need to know what a request holds.

Every conversation with an API is two messages: a request from the client and a response from the server. Both have the same shape: a first line, headers, a blank line, then the body. Think of sending a parcel by courier. The label on the outside of the box (in HTTP: the headers) says what's inside and where it goes. The box (in HTTP: the body) holds the goods. The courier comes back with a receipt that has one stamp (in HTTP: the status code): delivered, address not found, or refused because the packaging was wrong.

What a request holds

This is the request from a Bookshop admin who adds a new book:

POST /books HTTP/1.1
Host: api.bookshop.test
Content-Type: application/json
Accept: application/json

{"title": "The Dancer", "author_id": 4, "price": 95000, "stock": 8}

Data can travel in four places in a request, and each place has its own job:

Place Example Its job
path /books/4 points at which thing
query ?author_id=2 options for a list
header Content-Type: application/json notes about the request itself
body {"title": "..."} the data being sent (POST, PUT, PATCH)

Headers: the label on the box

The server reads Content-Type first, before it opens the body. Without application/json the server doesn't know the body is JSON, so the body isn't parsed (turned from text into data the code can use). In Express, express.json(), the part of Express that parses the body, only reads bodies whose Content-Type is JSON. Any other body is skipped. In Express 5, req.body (the request body in the code) stays undefined. As a result const { title, price } = req.body throws the error TypeError, and the client gets a 500. Express 4 sets req.body to {}, so validation (checking the data) says title is missing. A stricter server answers 415 Unsupported Media Type (the body's format isn't supported) right away. Either way the data you sent isn't read.

There is a trap in fetch (the JavaScript function that sends a request). If the body is text and you don't write the header, fetch sends Content-Type: text/plain;charset=UTF-8 (plain text). So write the header yourself:

fetch("https://api.bookshop.test/books", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "The Dancer", author_id: 4, price: 95000, stock: 8 }),
});

JSON.stringify(...) turns an object into JSON text. Because the body is text, you have to write the Content-Type header yourself.

Status codes: an answer in three digits

The first digit of a status code names its group (xx stands for any two digits). 2xx worked, 3xx usually moved elsewhere (a redirect), 4xx the request is at fault (the client), 5xx the server is at fault.

Status Name When, in the Bookshop API
200 OK GET /books/1 worked
201 Created POST /books made a new book
204 No Content DELETE /books/2 worked, no body
400 Bad Request the body isn't valid JSON, or a required field is missing
404 Not Found GET /books/99
405 Method Not Allowed PUT /books
415 Unsupported Media Type a body sent without Content-Type: application/json
422 Unprocessable Content the JSON reads fine, but a value makes no sense, such as "price": -5000
500 Internal Server Error a bug in the server

200 means it worked. 404 means Not Found: what was asked for doesn't exist. The line between 400 and 422 isn't fixed. Many APIs use 400 for every bad input. Some other APIs (for example Laravel, a PHP framework) use 422 for all data that fails validation. Bookshop uses 400 for a body that can't be read or lacks a required field, and 422 for a value that makes no sense. Pick one rule, then use it consistently.

A consistent body shape

Client code is easiest to write when every endpoint answers in the same shape. In Bookshop, a successful answer holds the data itself, and a failed one always looks like {"error": "..."}. Many other APIs wrap a successful answer as {"data": ..., "message": "..."}: the data goes in data, and the message in message. This exercise uses that wrapped shape. Either shape is fine, as long as one shape is used on every endpoint.

Exercise: POST /register

This is the endpoint that adds a book in Bookshop:

app.post("/books", (req, res) => {
  const { title, price } = req.body;
  if (!title) {
    return res.status(400).json({ error: "title is required" });
  }
  res.status(201).json({ id: 4, title, price });
});

In the exercise, the code has the same shape: the endpoint POST /register, with the fields name and email. If there is no name, answer 400 with {"error": "Name is required"}. When it's complete, answer 201 with {"data": {"name": ..., "email": ...}, "message": "Registered!"}.

⚠️ Statuses that lie, bodies that go unread

TL;DR: A request is made of a first line (method, path), headers, a blank line, then the body. A response has the same shape, but its first line holds the status code. The path points at a thing, the query shapes a list, headers carry notes, and the body carries data. The header Content-Type: application/json is required when sending a JSON body. Without that header the server doesn't parse the body (doesn't read it as data), or it answers 415 right away. Watch out: fetch (the function that sends a request) without the header sends text/plain (plain text). Statuses: 2xx worked (200 OK, 201 Created, 204 No Content), 4xx the request is at fault (400 Bad Request, 404 Not Found, 405, 415, 422), 5xx the server is at fault. In the code, send errors with res.status(...) and then return (stop the function), and use one body shape on every endpoint.

⚡ Four places data can ride

Meaning: Data can travel in four places in a request. The path points at a thing (/books/4). The query (the part after ?) shapes a list (?author_id=2). Headers carry notes about the request itself. The body carries the data sent with POST, PUT or PATCH.

⚡ Content-Type decides whether the body is read

Write:

fetch("https://api.bookshop.test/books", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "The Dancer", author_id: 4, price: 95000, stock: 8 }),
});
Guess first: the code above writes the Content-Type header. If that header isn't written, does the server still read the body as JSON?

No. fetch without the header sends Content-Type: text/plain;charset=UTF-8 (plain text), so the server doesn't parse the body (doesn't read it as data). In Express 5, req.body stays undefined, and a stricter server answers 415 (format not supported) right away.

Meaning: fetch sends a request from JavaScript, and JSON.stringify turns an object into JSON text. Content-Type names the format of the body being sent. For JSON, write application/json yourself.

⚡ Status: an answer in three digits

Meaning: The first digit of a status code names its group. 2xx worked (200 OK, 201 Created, 204 No Content). 4xx the request is at fault (400 Bad Request, 404 Not Found). 5xx the server is at fault. So bad input from the client gets a 4xx, while 500 means your server has a bug.

⚡ Send the error, then return

Write:

app.post("/books", (req, res) => {
  const { title, price } = req.body;
  if (!title) {
    return res.status(400).json({ error: "title is required" });
  }
  res.status(201).json({ id: 4, title, price });
});

Meaning: If the body has no title, this endpoint answers 400, and return stops the function there. Without return, the lines below run too and send a second answer (201). In the exercise's tester that second answer overwrites the first, so the status 400 turns into 201.

What you will learn