Building a JSON API
Reading the request body
Section titled “Reading the request body”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.
A small in-memory JSON API
Section titled “A small in-memory JSON API”The server below manages a list of items in memory. It supports:
GET /items— list all itemsPOST /items— add an item (reads JSON body)GET /items/:id— fetch one item (returns 404 if missing)
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:
curl http://localhost:3000/itemscurl -X POST http://localhost:3000/items -H 'Content-Type: application/json' -d '{"name":"TypeScript"}'curl http://localhost:3000/items/3curl http://localhost:3000/items/99Status code summary for a REST API
Section titled “Status code summary for a REST API”| Scenario | Status Code |
|---|---|
| Successful read | 200 OK |
| Resource created | 201 Created |
| Missing or invalid body field | 400 Bad Request |
| Resource not found | 404 Not Found |
| Server error | 500 Internal Server Error |