Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Building an API

Building an HTTP Server from Scratch

Build a JSON API with Node's built-in http module: request and response objects, reading the body safely, sending JSON, status codes, and why frameworks exist.

Before you reach for Express, Fastify or Laravel, it pays to build one tiny API with nothing but the language's standard library. You will see exactly what a framework does for you, and when something goes wrong in production you will know where to look. This course uses Node.js because its built-in node:http module is small, and because every example can run in your browser on the site's Node runner. The ideas carry over to any language and any framework.

In this lesson you create a server, read requests, send JSON responses and handle the one tricky part of raw HTTP servers: reading a request body.

The smallest server

http.createServer takes a function that Node calls once per request, with a request object (req) and a response object (res):

JavaScript
import http from 'node:http';

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ hello: 'world' }));
});

server.listen(3000, () => console.log('Listening on http://localhost:3000'));

Locally you would pick a port such as 3000. In the runnable examples on this page the server listens on port 0, which asks the operating system for any free port, and then calls itself. That keeps every example self-contained.

Object Useful members
req method, url, headers, and the body as a readable stream
res writeHead(status, headers), setHeader, write, end, statusCode

req.url holds the path and query string (/books?limit=5), so parse it with the URL class rather than splitting by hand. req.headers is an object with lowercase keys.

Sending JSON properly

Every JSON response needs the right status, the Content-Type header and a serialised body. Wrap that in a helper so you do not repeat it:

JavaScript
function sendJson(res, status, data, headers = {}) {
  const body = JSON.stringify(data);
  res.writeHead(status, {
    'Content-Type': 'application/json; charset=utf-8',
    'Content-Length': Buffer.byteLength(body),
    ...headers,
  });
  res.end(body);
}

Buffer.byteLength counts bytes, not characters, which matters as soon as a response contains an accent or an emoji. A 204 or 304 response must have no body, so use res.writeHead(204).end() for those.

Reading the request body

A request body is not available all at once. It arrives as a stream of chunks. To read JSON you collect the chunks, join them and parse:

  1. Gather chunks (they are Buffers).
  2. Stop early if the body grows beyond a limit, or a client can exhaust your memory with a gigabyte upload.
  3. Check the Content-Type (415 if it is not JSON).
  4. Parse inside try/catch and answer 400 for broken JSON.
flowchart TD
    A["Request arrives"] --> B{"Content-Type is application/json?"}
    B -- No --> C["415"]
    B -- Yes --> D["Read chunks, count bytes"]
    D --> E{"Over limit?"}
    E -- Yes --> F["413"]
    E -- No --> G{"Valid JSON?"}
    G -- No --> H["400"]
    G -- Yes --> I["Handler gets the object"]

Body parsing is a small pipeline with three possible failures.

The next example puts those pieces into a readJson function that throws errors carrying a status code, and a server that echoes the parsed body.

Node.js Reading a JSON body safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the server has four different failure answers (400, 404, 413, 415) before the actual feature is even reached. This is why even small APIs benefit from a body-parsing helper, and why frameworks ship one.

Routing by hand

With only req.method and the path, a first router is a chain of if statements, as in the example above. It works for three routes and becomes unreadable at thirty. The next lesson, Building a Router, replaces it with a table of patterns and path parameters.

Starting and stopping cleanly

A server is a long-running process, so it should shut down politely. When the platform asks it to stop (a deploy, Ctrl+C), it should stop accepting new connections and let in-flight requests finish.

Node.js Graceful shutdown

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In a real deployment you wire this to process.on('SIGTERM', ...) and add a timeout so a hung request cannot block shutdown forever.

What frameworks add

Everything in this lesson is also in Express, Fastify, Koa, Laravel, Django REST framework or Spring. Frameworks add a router, body parsers, validation, middleware, error handling and conventions. Knowing the raw version means you recognise those parts as ordinary code, not magic.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the server in the examples listen on port 0?

    Port 0 means "choose any free port", which keeps examples self-contained and avoids clashes.
  2. 2. Why should you limit the size of a request body?

    Without a limit, one request can use as much memory as the client cares to send. Answer 413 when the limit is exceeded.
  3. 3. A client sends a body with Content-Type text/plain to an endpoint that only accepts JSON. What is the best status?

    415 means the request body type is not supported.
  4. 4. Why use Buffer.byteLength for Content-Length instead of string.length?

    Characters such as รฉ or emoji take more than one byte in UTF-8.

Summary

  • http.createServer gives you req and res; parse req.url with URL.
  • Send JSON with the right status, Content-Type and byte-accurate Content-Length.
  • Read bodies as streams, with a size limit, a content-type check and try/catch around JSON.parse.
  • Map failures to 400, 413, 415 and 404, and keep internal errors generic.
  • Shut down gracefully so in-flight requests complete.

Next: Building a Router