Model answer
I’d define resources and status codes deliberately, validate input at the boundary, and centralize error responses so clients get a consistent contract. Here’s a small runnable Node.js example using the built-in HTTP module; it implements GET, POST, PUT, and DELETE for items, plus a client helper that treats non-2xx responses as errors.
const http = require('node:http');
const items = new Map();
let nextId = 1;
class HttpError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
function sendJson(res, status, data) {
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(data));
}
async function readJson(req) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > 1_000_000) throw new HttpError(413, 'Request body too large');
chunks.push(chunk);
}
try {
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
} catch {
throw new HttpError(400, 'Malformed JSON');
}
}
function validateItem(body) {
if (!body || typeof body.name !== 'string' || !body.name.trim()) {
throw new HttpError(400, 'name must be a non-empty string');
}
return { name: body.name.trim() };
}
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url, `http://${req.headers.host}`);
const match = url.pathname.match(/^\/api\/items(?:\/(\d+))?$/);
if (!match) throw new HttpError(404, 'Route not found');
const id = match[1] ? Number(match[1]) : null;
if (req.method === 'GET' && id === null) {
return sendJson(res, 200, [...items.values()]);
}
if (req.method === 'GET' && id !== null) {
const item = items.get(id);
if (!item) throw new HttpError(404, 'Item not found');
return sendJson(res, 200, item);
}
if (req.method === 'POST' && id === null) {
if (!req.headers['content-type']?.includes('application/json')) {
throw new HttpError(415, 'Expected application/json');
}
const item = { id: nextId++, ...validateItem(await readJson(req)) };
items.set(item.id, item);
return sendJson(res, 201, item);
}
if (req.method === 'PUT' && id !== null) {
if (!items.has(id)) throw new HttpError(404, 'Item not found');
if (!req.headers['content-type']?.includes('application/json')) {
throw new HttpError(415, 'Expected application/json');
}
const item = { id, ...validateItem(await readJson(req)) };
items.set(id, item);
return sendJson(res, 200, item);
}
if (req.method === 'DELETE' && id !== null) {
if (!items.has(id)) throw new HttpError(404, 'Item not found');
items.delete(id);
res.writeHead(204);
return res.end();
}
res.setHeader('allow', id === null ? 'GET, POST' : 'GET, PUT, DELETE');
throw new HttpError(405, 'Method not allowed');
} catch (error) {
const status = error instanceof HttpError ? error.status : 500;
if (status === 500) console.error(error);
sendJson(res, status, {
error: status === 500 ? 'Internal server error' : error.message
});
}
});
server.listen(3000, () => console.log('API listening on port 3000'));
// Example client helper: do not assume fetch rejects on HTTP error statuses.
async function requestJson(url, options = {}) {
const response = await fetch(url, options);
const body = response.status === 204 ? null : await response.json();
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${body?.error ?? 'Request failed'}`);
}
return body;
}
- Use
201 for creation, 200 for successful reads/updates, 204 for deletion, and appropriate 4xx/5xx statuses for failures. - In a production service, add authentication/authorization, request IDs, structured logs, rate limits, and persistent storage. Keep internal error details out of client responses.
Complexity: Map lookups and mutations are O(1) average; listing items is O(n). Request parsing uses O(B) space for a body of size B.