A small API is easier to understand when you can send it requests and inspect exactly what it returns. This Node.js example stores tasks in memory. You can list them, create one, read it by ID, and delete it using ordinary HTTP requests.
The server uses Node’s built-in HTTP module. There is no framework, account, database, or package installation. Keeping those pieces out of the first exercise makes the request method, URL, status, and JSON body easier to follow.
Table of Contents
The four operations
| Request | What it does | Success status |
|---|---|---|
| GET /tasks | List every task | 200 |
| POST /tasks | Create a task from a JSON title | 201 |
| GET /tasks/1 | Read one task | 200 |
| DELETE /tasks/1 | Remove one task | 204, with no body |
Create the server
Use Node.js 22 or later. Save this file as server.mjs inside node-task-api. The .mjs extension enables JavaScript modules without a package file.
import { createServer as httpServer } from 'node:http';
import { pathToFileURL } from 'node:url';
class HttpError extends Error {
constructor(status, message) { super(message); this.status = status; }
}
function readJson(request) {
return new Promise((resolve, reject) => {
let bytes = 0;
const chunks = [];
request.on('data', chunk => {
bytes += chunk.length;
if (bytes > 16384) {
reject(new HttpError(413, 'Body exceeds 16 KiB.'));
} else { chunks.push(chunk); }
});
request.on('end', () => {
if (bytes > 16384) return;
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); }
catch { reject(new HttpError(400, 'Body must be valid JSON.')); }
});
request.on('error', reject);
request.on('aborted', () => reject(new HttpError(400, 'Request interrupted.')));
});
}
export function createTaskServer() {
const tasks = new Map();
let nextId = 1;
const server = httpServer(async (request, response) => {
function send(status, body, headers = {}) {
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store', ...headers });
response.end(status === 204 ? undefined : JSON.stringify(body));
}
try {
const path = new URL(request.url, 'http://localhost').pathname;
if (path === '/tasks' && request.method === 'GET') {
return send(200, [...tasks.values()]);
}
if (path === '/tasks' && request.method === 'POST') {
const type = (request.headers['content-type'] ?? '').split(';')[0].trim();
if (type !== 'application/json') throw new HttpError(415, 'Use application/json.');
const body = await readJson(request);
if (!body || Array.isArray(body) || typeof body.title !== 'string'
|| !body.title.trim() || body.title.trim().length > 120) {
throw new HttpError(422, 'Title must contain 1 to 120 characters.');
}
const task = { id: nextId++, title: body.title.trim() };
tasks.set(task.id, task);
return send(201, task, { Location: `/tasks/${task.id}` });
}
const match = /^\/tasks\/([1-9]\d*)$/.exec(path);
if (match) {
const id = Number(match[1]);
if (!Number.isSafeInteger(id) || !tasks.has(id)) throw new HttpError(404, 'Task not found.');
if (request.method === 'GET') return send(200, tasks.get(id));
if (request.method === 'DELETE') { tasks.delete(id); return send(204); }
return send(405, { error: 'Method not allowed.' }, { Allow: 'GET, DELETE' });
}
if (path === '/tasks') return send(405, { error: 'Method not allowed.' }, { Allow: 'GET, POST' });
throw new HttpError(404, 'Route not found.');
} catch (error) {
send(error instanceof HttpError ? error.status : 500,
{ error: error instanceof HttpError ? error.message : 'Unexpected server error.' });
}
});
server.requestTimeout = 15000;
server.headersTimeout = 10000;
return server;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const port = Number(process.env.PORT ?? 3000);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
console.error('PORT must be an integer from 1 to 65535.');
process.exitCode = 1;
} else {
const server = createTaskServer();
server.on('error', error => { console.error(error.message); process.exitCode = 1; });
server.listen(port, '127.0.0.1', () => console.log(`Task API: http://127.0.0.1:${port}/tasks`));
}
}
Start it locally
Run node server.mjs. Leave that terminal open and use a second terminal for the requests below. The server listens at http://127.0.0.1:3000 on your own computer. It is intentionally bound to the loopback address.
If port 3000 is busy, stop the other local process you recognize or select a different port. For example, in macOS or Linux use PORT=3001 node server.mjs and adjust the request URLs. In PowerShell, set $env:PORT = "3001" before running Node. Stop this server with Ctrl+C.
Create, read, and delete a task
These curl commands use shell quoting suitable for macOS and Linux. On Windows, use curl.exe with quoting appropriate to your shell or an HTTP client that lets you set a JSON request body.
curl -i http://127.0.0.1:3000/tasks
curl -i -X POST http://127.0.0.1:3000/tasks -H 'Content-Type: application/json' -d '{"title":"Read the guide"}'
curl -i http://127.0.0.1:3000/tasks/1
curl -i -X DELETE http://127.0.0.1:3000/tasks/1
curl -i http://127.0.0.1:3000/tasks/1
The first request returns an empty array. The POST returns status 201, a Location header pointing to /tasks/1, and {"id":1,"title":"Read the guide"}. Reading that URL returns the task. Deleting it returns 204 with an empty body. The final read returns 404 because the resource has been removed.
The ID counter keeps increasing within one server run. Restarting the server clears the Map and starts the counter again. This is useful for a repeatable exercise, but it is not persistence.
Try requests the server should reject
Send a body containing only an opening brace to see a 400 parsing error. Send {"title":" "} for a 422 validation error. Omit the application/json content type to see 415. A body over 16 KiB receives 413. An unsupported method on a known resource receives 405 and an Allow header.
These checks answer different questions. JSON parsing decides whether the body is syntactically valid. Validation checks whether it contains a usable task title. Neither step proves the sender has permission to create a task; this local exercise has no user accounts.
Understand the boundaries
The body limit counts bytes while data arrives, before attempting to parse the complete body. Titles are trimmed and limited to 120 JavaScript string code units. The response helper returns JSON errors with useful status codes, while unexpected internal errors get a plain message rather than a stack trace.
A browser address bar sends GET requests. It cannot demonstrate POST or DELETE by changing the URL. Use an HTTP client for those operations. This server also does not enable cross-origin browser access; a separate frontend needs a deliberate same-origin arrangement or a restricted CORS policy.
Keep this API local. Before adapting it for a public service, decide how authentication, authorization, persistent storage, concurrency, request limits, logging, HTTPS, and deployment will work. The example demonstrates a small HTTP resource API, not every constraint of REST or a production-ready backend.
Download all the example files
The ZIP contains this original CampCodes example, a README, and an MIT license. No account, package installation, or paid service is needed.
References and verification
Node.js HTTP documentation covers the request and response primitives. This AI-assisted guide was rewritten on October 22, 2026. Automated HTTP checks ran on Node.js 24.9.0: create/read/delete, response headers, missing resources, invalid JSON, invalid titles, unsupported media types and methods, and the body size limit. No external API was contacted.
