Frameworks such as Express are convenient, but building one small API by hand first makes them much easier to understand and to debug.
const http = require('http');
const notes = [{ id: 1, text: 'Submit lab record' }];
const send = (res, status, data) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(data)); };
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/notes') return send(res, 200, notes);
if (req.method === 'POST' && req.url === '/notes') {
let body = '';
req.on('data', chunk => { body += chunk; });
req.on('end', () => {
try {
const { text } = JSON.parse(body);
if (!text) return send(res, 400, { error: 'text is required' });
const note = { id: notes.length + 1, text };
notes.push(note);
send(res, 201, note);
} catch { send(res, 400, { error: 'invalid JSON' }); }
});
return;
}
send(res, 404, { error: 'not found' });
});
server.listen(0, async () => {
const base = `http://127.0.0.1:${server.address().port}`;
const created = await fetch(base + '/notes', { method: 'POST', body: JSON.stringify({ text: 'Revise OS' }) });
console.log(created.status, (await created.json()).id);
const list = await (await fetch(base + '/notes')).json();
console.log(list.length, (await fetch(base + '/missing')).status);
server.close();
});201 2
2 404What to notice
- Status codes carry meaning: 200 OK, 201 Created, 400 bad input, 404 not found, 500 server error. Clients and tests depend on them.
- The body arrives in chunks. You collect it with the data event and parse it on end. Express's express.json() does exactly this for you.
- Always handle bad input. JSON.parse throws on invalid JSON; without the try/catch, one bad request would crash the server.
- Content-Type tells the client how to read the response.
When you move to Express, the same API becomes app.get('/notes', ...) and app.post('/notes', ...), and the framework handles the routing, body parsing and 404s.
Sources and further reading
Practise this as an interview question
Written by the UniCircle team, checked by an editor on 22 Oct 2026. It is not official policy of any university. Exam patterns and rules change; confirm dates and rules on the official website.
