Node.js ยท Chapter 16 of 43

Building JSON APIs

Most modern web APIs exchange data as JSON. Node.js makes this easy with the built-in `JSON.stringify()` and `JSON.parse()` methods.

A JSON API typically sets the `Content-Type: application/json` header and sends a JSON-formatted response body.

Sending JSON

Convert JavaScript objects to a JSON string with `JSON.stringify()` before sending them in a response body.

Receiving JSON

When receiving JSON in a request body, collect the raw data chunks and parse them with `JSON.parse()`.

Example 1 (javascript)
const http = require('http');
http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ message: 'Hello API' }));
}).listen(3000);
Output
{"message":"Hello API"}

The server responds with a JSON string and the correct content type header.

Example 2 (javascript)
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
  const data = JSON.parse(body);
  console.log(data);
});
Output
{ name: 'Ada' }

Incoming request data arrives in chunks that must be joined then parsed as JSON.

Key points

  • JSON.stringify() converts objects to JSON text.
  • JSON.parse() converts JSON text back to objects.
  • Set 'Content-Type: application/json' on JSON responses.
  • Raw request bodies arrive as data chunks that must be collected.
๐Ÿ’ก Note: Frameworks like Express provide `express.json()` middleware to automate this parsing.

๐Ÿ“ Quick Quiz

1. Which method converts a JS object into a JSON string?

2. What header should a JSON API response include?

3. How does raw request body data arrive in Node?