Skip to content

Building a JSON API

Unlike the URL and headers which are available immediately, the request body arrives as a stream of chunks. You must collect them manually with data and end events:

function readBody(req) {
return new Promise(function(resolve, reject) {
let raw = '';
req.on('data', function(chunk) { raw += chunk; });
req.on('end', function() { resolve(raw); });
req.on('error', reject);
});
}

Once you have the raw string, parse it with JSON.parse() inside a try/catch to handle malformed input gracefully.

The server below manages a list of items in memory. It supports:

  • GET /items — list all items
  • POST /items — add an item (reads JSON body)
  • GET /items/:id — fetch one item (returns 404 if missing)
Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Open in StackBlitz to test the API with the built-in HTTP client or a tool like curl:

Terminal window
curl http://localhost:3000/items
curl -X POST http://localhost:3000/items -H 'Content-Type: application/json' -d '{"name":"TypeScript"}'
curl http://localhost:3000/items/3
curl http://localhost:3000/items/99
ScenarioStatus Code
Successful read200 OK
Resource created201 Created
Missing or invalid body field400 Bad Request
Resource not found404 Not Found
Server error500 Internal Server Error
Why must you collect request body data using `data` and `end` events rather than reading it synchronously?
What HTTP status code should a POST endpoint return when it successfully creates a new resource?
A client sends an invalid JSON body. What is the correct response status code?