Hey, you’re back! 🙌 Chapter 1 was all about what Node.js is—now it’s time to build something real. By the end of this, you’ll have a working REST API that serves data, handles requests, and makes you feel like a coding wizard. No magic wand required—just JavaScript.
Let’s get this bread.
Express.js: Your API’s New BFF
Node.js is powerful, but writing a server from scratch? That’s like building a car to drive to the grocery store. Express.js is the Tesla of backend frameworks—minimal setup, maximum speed.
Why Express?
- Simplifies routing (mapping URLs to code).
- Adds middleware (think: plugins for your server).
- Used by Netflix, Uber, and X(Twitter) (no big deal).
REST APIs in 60 Seconds ⏳
A REST API lets apps talk to each other over HTTP. Imagine your React app asking your Node.js server: “Hey, can I get some data?” and the server replying “Sure, here’s a JSON file!”
Key concepts:
-
Endpoints: URLs like
/api/users
or/api/posts
. -
HTTP Methods:
GET
(read),POST
(create),PUT
(update),DELETE
(…you get it). - CRUD: Create, Read, Update, Delete (the four commandments of APIs).
Let’s Build a To-Do API (Because Why Not?)
We’re building a simple API to track tasks. Even Zuckerberg started with “Hello, World.”
Step 1: Set Up the Project
- Create a folder and initialize npm:
mkdir todo-api && cd todo-api
npm init -y # -y = "Yes to everything, I’m lazy"
- Install Express:
npm install express
Step 2: The Bare Minimum Server
Create server.js
:
// server.js
const express = require('express');
const app = express();
// Let Express parse JSON (so you can send data in POST requests)
app.use(express.json());
// Basic route
app.get('/', (req, res) => {
res.send('Your API is alive! 🎉');
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server dancing on http://localhost:${PORT}`);
});
Run it:
node server.js
Visit http://localhost:3000
in your browser. If you see the message, you’ve just built a server.
Adding CRUD Endpoints
Let’s fake a database (for now) using an array.
// Fake "database"
let todos = [
{ id: 1, task: "Learn Node.js", done: false },
{ id: 2, task: "Build an API", done: true }
];
// GET all todos
app.get('/api/todos', (req, res) => {
res.json(todos);
});
// POST a new todo
app.post('/api/todos', (req, res) => {
const newTodo = {
id: todos.length + 1,
task: req.body.task,
done: false
};
todos.push(newTodo);
res.status(201).json(newTodo); // 201 = "Created"
});
Test it with Postman:
- Send a
GET
tohttp://localhost:3000/api/todos
– you’ll see your fake todos. - Send a
POST
with JSON body{ "task": "Buy coffee" }
– watch your array grow!
Middleware: The Secret Sauce
Middleware functions can:
- Log requests.
- Authenticate users.
- Handle errors.
Example: Add a request logger
// Log every request
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Pass control to the next middleware
});
Now your terminal will show:
[2025-06-15T10:30:00Z] GET /api/todos
Error Handling (Because Stuff Breaks)
Ever seen “Cannot GET /api/todo”? Let’s fix that.
// Handle 404s
app.use((req, res) => {
res.status(404).json({ error: "Route not found. Did you mean /api/todos?" });
});
// Global error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: "Oops, our server had a ☕ moment." });
});
Why This Matters
- Foundational Skills: Every backend role expects REST API knowledge.
- Full-Stack Power: Connect this API to your React/Vue frontend tomorrow.
- Scalability: Later, swap the fake array with MongoDB/Postgres.
Level Up: 3 Pro Tips
- Use
nodemon
to auto-restart your server on changes:
npm install -g nodemon
nodemon server.js
- Structure your code with folders like
routes/
andcontrollers/
. -
Always validate data (try the
joi
library).
Quiz Time! 🧠
Test your Express knowledge here:
👉 Express.JS Quiz
What’s Next?
In Chapter 3, we’ll connect this API to a real database (MongoDB) and deploy it to the cloud. Until then:
- Add
PUT
andDELETE
endpoints. - Experiment with Postman to test your routes.
About the Author
Still Abhinav, still caffeinated. I once spent 3 hours debugging an API only to realize I forgot a comma. Now I write guides so you don’t have to. Find more rants and memes at ExamShala.in.
P.S. Hit a wall? Screenshot your code and tag me on Twitter. Let’s fix it together! 💪