Serving JSON / REST API
Most Node.js back-ends don't send HTML — they send JSON to a front-end app, a mobile app or another service. A REST API organises that data as resources (users, products, orders) that clients read and change with standard HTTP methods.
REST in one table
For a collection of todos, a conventional REST design looks like this:
| Method | Path | Action | Success status |
|---|---|---|---|
GET |
/todos |
list all todos | 200 |
GET |
/todos/:id |
read one todo | 200 (404 if missing) |
POST |
/todos |
create a todo from the JSON body | 201 |
PUT / PATCH |
/todos/:id |
replace / partially update | 200 |
DELETE |
/todos/:id |
delete | 204 |
The URL names the thing, the method names the action. Avoid verbs in URLs like /getTodos or /deleteTodo?id=3.
Sending JSON
Two things make a JSON response: the Content-Type: application/json header and a body produced with JSON.stringify. A tiny helper keeps handlers short:
const http = require('node:http');
function sendJson(res, status, data) {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(data));
}
const server = http.createServer((req, res) => {
sendJson(res, 200, { ok: true, method: req.method, tags: ['node', 'json'] });
});
server.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}/`);
console.log(res.headers.get('content-type'));
const data = await res.json(); // parses the body for us
console.log(data);
console.log(data.tags[1]);
server.close();
});application/json; charset=utf-8
{ ok: true, method: 'GET', tags: [ 'node', 'json' ] }
json
On the client side, res.json() reads the body and parses it in one step.
Reading a JSON body safely
Clients send JSON in POST/PUT bodies. Parsing can fail, so always catch errors and answer 400 Bad Request for invalid input:
async function readJson(req) {
let raw = '';
for await (const chunk of req) raw += chunk;
if (!raw) return {};
return JSON.parse(raw); // throws SyntaxError on bad JSON
}Note: In production also limit the body size (for example reject anything over 1 MB) so a client can't exhaust your server's memory.
A complete in-memory todo API
Here is a full CRUD API in about 50 lines of plain Node. Data lives in an array, so it resets every time the server restarts — in a later lesson you'll store it in a database.
const http = require('node:http');
let todos = [{ id: 1, title: 'Learn Node', done: true }];
let nextId = 2;
const send = (res, status, data) => {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(data === undefined ? undefined : JSON.stringify(data));
};
async function readJson(req) {
let raw = '';
for await (const chunk of req) raw += chunk;
return raw ? JSON.parse(raw) : {};
}
const server = http.createServer(async (req, res) => {
const { pathname } = new URL(req.url, 'http://localhost');
const match = pathname.match(/^\/todos(?:\/(\d+))?$/);
if (!match) return send(res, 404, { error: 'Not found' });
const id = match[1] && Number(match[1]);
try {
if (req.method === 'GET' && !id) return send(res, 200, todos);
if (req.method === 'POST' && !id) {
const { title } = await readJson(req);
if (typeof title !== 'string' || !title.trim()) {
return send(res, 400, { error: 'title is required' });
}
const todo = { id: nextId++, title: title.trim(), done: false };
todos.push(todo);
return send(res, 201, todo);
}
const todo = todos.find((t) => t.id === id);
if (!todo) return send(res, 404, { error: `todo ${id} not found` });
if (req.method === 'GET') return send(res, 200, todo);
if (req.method === 'PATCH') {
Object.assign(todo, await readJson(req), { id });
return send(res, 200, todo);
}
if (req.method === 'DELETE') {
todos = todos.filter((t) => t.id !== id);
return send(res, 204);
}
send(res, 405, { error: 'Method not allowed' });
} catch (err) {
send(res, 400, { error: `Invalid JSON: ${err.message}` });
}
});
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}/todos`;
const call = async (method, path = '', body) => {
const res = await fetch(base + path, {
method,
headers: { 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await res.text();
console.log(method.padEnd(6), ('/todos' + path).padEnd(9), res.status, text);
};
await call('POST', '', { title: 'Write tests' });
await call('POST', '', { title: '' });
await call('PATCH', '/2', { done: true });
await call('GET', '/9');
await call('DELETE', '/1');
await call('GET');
server.close();
});POST /todos 201 {"id":2,"title":"Write tests","done":false}
POST /todos 400 {"error":"title is required"}
PATCH /todos/2 200 {"id":2,"title":"Write tests","done":true}
GET /todos/9 404 {"error":"todo 9 not found"}
DELETE /todos/1 204
GET /todos 200 [{"id":2,"title":"Write tests","done":true}]
Things to notice:
POSTanswers 201 Created and returns the new object, including its server-assignedid.- Invalid input gets a 400 with a JSON error message the client can show.
DELETEanswers 204 No Content with an empty body.
Designing good JSON APIs
| Practice | Example |
|---|---|
| Plural nouns for collections | /products, /products/7 |
| Consistent error shape | { "error": "message" } everywhere |
| Correct status codes | 201 on create, 404 when missing, 400 on bad input |
| Filtering via query string | /products?category=books&page=2 |
| Versioning | /api/v1/products |
| Never leak internals | don't send stack traces or password hashes |
Tip: To let a browser app on another origin call your API, add CORS headers such as
Access-Control-Allow-Origin. Frameworks offer a middleware for this.
Test yourself
Which status code should a successful POST that creates a resource return?
- 200
- 201
- 204
- 302
Which header tells the client the body is JSON?
- Accept: application/json
- Content-Type: application/json
- X-JSON: true
- Content-Encoding: json
Which URL follows REST conventions for deleting product 5?
- GET /deleteProduct?id=5
- POST /products/delete/5
- DELETE /products/5
- DELETE /product-delete