Building a REST API with Node.js and Express
What is a REST API?
A REST (Representational State Transfer) API is an architectural style for designing networked applications. It relies on a stateless, client-server communication protocol””almost always HTTP. REST APIs are the backbone of modern web services, allowing different applications to communicate with each other over the internet.
Why Node.js and Express?
- Node.js is a JavaScript runtime built on Chrome's V8 engine. It allows you to run JavaScript on the server, making it perfect for building fast and scalable network applications.
- Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies the process of building APIs by providing tools for routing, middleware, and handling HTTP requests and responses.
Setting Up Your Project
First, make sure you have Node.js and npm (Node Package Manager) installed.
-
Initialize your project:
mkdir my-api cd my-api npm init -y -
Install Express:
npm install express
Creating Your First Server
Create a file named index.js and add the following code:
const express = require('express');
const app = express();
const port = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Run your server with node index.js. You can now visit http://localhost:3000 in your browser and see "Hello, World!".
Building API Endpoints (Routing)
A REST API is defined by its endpoints. Let's create a simple in-memory "database" and build CRUD (Create, Read, Update, Delete) endpoints for a collection of users.
// ... (keep the initial setup code)
let users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// GET all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET a single user by ID
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found.');
res.json(user);
});
// POST a new user
app.post('/api/users', (req, res) => {
if (!req.body.name || req.body.name.length < 3) {
return res.status(400).send('Name is required and should be minimum 3 characters.');
}
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).json(newUser);
});
// PUT (update) a user
app.put('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found.');
user.name = req.body.name;
res.json(user);
});
// DELETE a user
app.delete('/api/users/:id', (req, res) => {
const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
if (userIndex === -1) return res.status(404).send('User not found.');
const deletedUser = users.splice(userIndex, 1);
res.json(deletedUser);
});
// ... (keep the app.listen code)
Next Steps: Connecting to a Database
While an in-memory array is great for learning, a real-world application needs a persistent database like MongoDB or PostgreSQL. You would use a library like Mongoose (for MongoDB) or Sequelize (for SQL databases) to connect your Express app to the database and replace the users array with database queries.
Conclusion
You've successfully built a basic REST API with Node.js and Express! You've learned how to set up a server, create routes for different HTTP methods, and perform CRUD operations. This is a fundamental skill for any back-end or full-stack developer. From here, you can explore middleware for authentication, error handling, and connecting to a real database.




