After learning the HTTP module, the next step is to build a real application.
One of the best beginner projects is a Todo CRUD API.
In this project, we'll build a REST API without using Express.js.
We'll only use Node.js's built-in HTTP module.
Our API will support the following operations:
- Create a Todo
- Get All Todos
- Get Todo by ID
- Update a Todo
- Delete a Todo
By the end of this article, you'll understand how HTTP servers, routing, request methods, request bodies, and responses work together.
Let's get started!
Project Structure
Create the following project structure.
todo-api/
│── server.js
│── package.json
Initialize the project.
npm init -y
No additional packages are required.
Step 1: Import the HTTP Module
Open server.js.
const http = require("http");
We'll also use the built-in URL class to parse URLs.
Step 2: Create Sample Data
Since we're not using a database yet, let's store todos in memory.
let todos = [
{
id: 1,
title: "Learn Node.js",
completed: false,
},
{
id: 2,
title: "Build HTTP Server",
completed: true,
},
];
Later, we'll replace this with MongoDB or another database.
Step 3: Create the Server
const server = http.createServer((req, res) => {
res.end("Server Running");
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Run:
node server.js
Open:
http://localhost:3000
Output:
Server Running
Step 4: Set Response Header
Since our API returns JSON, we'll set the content type.
res.setHeader("Content-Type", "application/json");
Step 5: Get All Todos (GET /todos)
Add the following route.
if (req.method === "GET" && req.url === "/todos") {
return res.end(JSON.stringify(todos));
}
Complete server:
const http = require("http");
let todos = [
{
id: 1,
title: "Learn Node.js",
completed: false,
},
];
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
if (req.method === "GET" && req.url === "/todos") {
return res.end(JSON.stringify(todos));
}
});
server.listen(3000);
Visit:
http://localhost:3000/todos
Output:
[
{
"id": 1,
"title": "Learn Node.js",
"completed": false
}
]
Step 6: Get Todo by ID (GET /todos/:id)
Suppose we visit:
http://localhost:3000/todos/2
We need to extract the ID from the URL.
Use the URL class.
const requestURL = new URL(req.url, "http://localhost:3000");
const pathname = requestURL.pathname;
Now check whether the route starts with /todos/.
if (
req.method === "GET" &&
pathname.startsWith("/todos/")
) {
const id = Number(pathname.split("/")[2]);
const todo = todos.find((todo) => todo.id === id);
if (!todo) {
res.statusCode = 404;
return res.end(
JSON.stringify({
message: "Todo Not Found",
})
);
}
return res.end(JSON.stringify(todo));
}
Visit:
GET /todos/1
Output:
{
"id": 1,
"title": "Learn Node.js",
"completed": false
}
Step 7: Read Request Body
POST, PUT, and PATCH requests send data in the request body.
Unlike Express, Node.js doesn't parse it automatically.
Create a helper function.
function getRequestBody(req) {
return new Promise((resolve, reject) => {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
resolve(JSON.parse(body));
});
req.on("error", reject);
});
}
This function collects all chunks and converts them into a JavaScript object.
Step 8: Create Todo (POST /todos)
Request:
POST /todos
Body:
{
"title": "Learn Streams"
}
Implementation:
if (req.method === "POST" && pathname === "/todos") {
const body = await getRequestBody(req);
const todo = {
id: Date.now(),
title: body.title,
completed: false,
};
todos.push(todo);
res.statusCode = 201;
return res.end(JSON.stringify(todo));
}
Response:
{
"id": 17123456789,
"title": "Learn Streams",
"completed": false
}
Step 9: Update Todo (PUT /todos/:id)
Request:
PUT /todos/1
Body:
{
"title": "Master Node.js",
"completed": true
}
Implementation:
if (
req.method === "PUT" &&
pathname.startsWith("/todos/")
) {
const id = Number(pathname.split("/")[2]);
const body = await getRequestBody(req);
const todo = todos.find((todo) => todo.id === id);
if (!todo) {
res.statusCode = 404;
return res.end(
JSON.stringify({
message: "Todo Not Found",
})
);
}
todo.title = body.title;
todo.completed = body.completed;
return res.end(JSON.stringify(todo));
}
Output:
{
"id": 1,
"title": "Master Node.js",
"completed": true
}
Step 10: Delete Todo (DELETE /todos/:id)
if (
req.method === "DELETE" &&
pathname.startsWith("/todos/")
) {
const id = Number(pathname.split("/")[2]);
const index = todos.findIndex(
(todo) => todo.id === id
);
if (index === -1) {
res.statusCode = 404;
return res.end(
JSON.stringify({
message: "Todo Not Found",
})
);
}
todos.splice(index, 1);
return res.end(
JSON.stringify({
message: "Todo Deleted Successfully",
})
);
}
Response:
{
"message": "Todo Deleted Successfully"
}
Step 11: Handle Unknown Routes
Always return a 404 for invalid routes.
res.statusCode = 404;
res.end(
JSON.stringify({
message: "Route Not Found",
})
);
Complete Application
const http = require("http");
let todos = [
{
id: 1,
title: "Learn Node.js",
completed: false,
},
{
id: 2,
title: "Learn HTTP Module",
completed: true,
},
];
function getRequestBody(req) {
return new Promise((resolve, reject) => {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
try {
resolve(JSON.parse(body));
} catch {
resolve({});
}
});
req.on("error", reject);
});
}
const server = http.createServer(async (req, res) => {
const requestURL = new URL(req.url, "http://localhost:3000");
const pathname = requestURL.pathname;
res.setHeader("Content-Type", "application/json");
// GET ALL TODOS
if (req.method === "GET" && pathname === "/todos") {
return res.end(JSON.stringify(todos));
}
// GET TODO BY ID
if (
req.method === "GET" &&
pathname.startsWith("/todos/")
) {
const id = Number(pathname.split("/")[2]);
const todo = todos.find((todo) => todo.id === id);
if (!todo) {
res.statusCode = 404;
return res.end(
JSON.stringify({
message: "Todo Not Found",
})
);
}
return res.end(JSON.stringify(todo));
}
// CREATE TODO
if (req.method === "POST" && pathname === "/todos") {
const body = await getRequestBody(req);
const todo = {
id: Date.now(),
title: body.title,
completed: false,
};
todos.push(todo);
res.statusCode = 201;
return res.end(JSON.stringify(todo));
}
// UPDATE TODO
if (
req.method === "PUT" &&
pathname.startsWith("/todos/")
) {
const id = Number(pathname.split("/")[2]);
const body = await getRequestBody(req);
const todo = todos.find((todo) => todo.id === id);
if (!todo) {
res.statusCode = 404;
return res.end(
JSON.stringify({
message: "Todo Not Found",
})
);
}
todo.title = body.title;
todo.completed = body.completed;
return res.end(JSON.stringify(todo));
}
// DELETE TODO
if (
req.method === "DELETE" &&
pathname.startsWith("/todos/")
) {
const id = Number(pathname.split("/")[2]);
const index = todos.findIndex(
(todo) => todo.id === id
);
if (index === -1) {
res.statusCode = 404;
return res.end(
JSON.stringify({
message: "Todo Not Found",
})
);
}
todos.splice(index, 1);
return res.end(
JSON.stringify({
message: "Todo Deleted Successfully",
})
);
}
res.statusCode = 404;
res.end(
JSON.stringify({
message: "Route Not Found",
})
);
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
Testing the API
You can test the API using:
- Postman
- Thunder Client (VS Code)
- Insomnia
- cURL
GET All Todos
GET /todos
GET Todo by ID
GET /todos/1
Create Todo
POST /todos
Body:
{
"title": "Learn EventEmitter"
}
Update Todo
PUT /todos/1
Body:
{
"title": "Learn Streams",
"completed": true
}
Delete Todo
DELETE /todos/1
How This API Works
Client Request
│
▼
HTTP Server
│
▼
Check HTTP Method
│
▼
Check Route
│
▼
Perform CRUD Operation
│
▼
Return JSON Response
This is the basic architecture of almost every REST API.
Best Practices
When building APIs with the HTTP module:
- Use meaningful route names.
- Return proper HTTP status codes.
- Always set
Content-Typetoapplication/jsonfor JSON responses. - Validate request data before creating or updating resources.
- Handle invalid routes with a
404response. - Keep routing logic organized as the application grows.
Common Beginner Mistakes
Here are some common mistakes developers make:
- Forgetting to call
JSON.stringify()before sending JSON. - Not handling request body parsing correctly.
- Forgetting to set the
Content-Typeheader. - Sending multiple responses for a single request.
- Not checking whether a requested resource exists before updating or deleting it.
Final Thoughts
Building a CRUD API using only the HTTP module is one of the best ways to understand how Node.js servers work internally. While frameworks like Express.js simplify routing and request handling, they ultimately rely on the same core concepts you've learned here.
In this article, you learned:
- How to create an HTTP server
- How to implement routing
- How to parse request bodies
- How to build CRUD endpoints
- How to retrieve all todos
- How to retrieve a todo by ID
- How to return proper JSON responses
- How to use appropriate HTTP status codes
Once you're comfortable with these fundamentals, you'll find learning Express.js much easier because you'll understand what it's abstracting behind the scenes.
Happy Coding! 🚀