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()`.
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello API' }));
}).listen(3000);{"message":"Hello API"}The server responds with a JSON string and the correct content type header.
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const data = JSON.parse(body);
console.log(data);
});{ 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.
