Advanced level · Module 2: Node.js for Tools and Servers · Lesson 3 of 4
Building an HTTP API with Node.js
Create a small JSON API with node:http or a minimal framework, with routing, status codes and headers.
In this lesson you will
- Handle HTTP requests and send JSON responses with correct status codes
- Route requests by method and path
Key concepts
http.createServerroutingstatus codesJSON request bodies
The lesson
http.createServer((req, res) => { … }) receives every request. Route on req.method and the URL path, set a status code and Content-Type: application/json, and send JSON.stringify(data) as the body.
Read JSON request bodies by collecting the request stream and parsing it, with a size limit and try/catch. Frameworks such as Express do this for you, but knowing the underlying steps helps you debug them.
Return meaningful status codes: 200 for reads, 201 for created resources, 400 for invalid input, 404 for unknown routes and 500 only for unexpected server errors — never leak stack traces in responses.
Step by step
- Create a server that answers GET /health.
- Add GET /summary returning the payments summary.
- Add POST /payments with a JSON body.
- Return 404 for unknown routes.
Practice activity
Expose the payments summary and an endpoint to add payments through a small JSON API.
Expected result: Endpoints return correct JSON and status codes, checked with curl or a REST client.
Check your understanding
-
Which status code should an unknown route return?
Show answer
404 Not Found.
-
Why limit the size of request bodies?
Show answer
To protect the server from very large or malicious requests.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.