Step 1: Setting Up the Node.js Environment
Before we begin coding, make sure you have Node.js and npm (Node Package Manager) installed on your system.
Install Node.js and npm
Download and install Node.js from the official website here. npm comes bundled with it.
Initialize the Project
Open your terminal or command prompt and create a new folder for the project. Navigate to the folder and initialize a new Node.js project by running:
mkdir node-rest-api
cd node-rest-api
npm init -y
This will create a package.json
file, which will manage the project’s dependencies.
Step 2: Installing Required Dependencies
Next, we need to install Express to handle routing, as well as body-parser to parse incoming request bodies in JSON format.
npm install express body-parser
Step 3: Creating the Basic Express Server
Now let’s create the basic structure for our REST API using Express. Start by creating a file named server.js
.
In server.js
, set up a simple Express server:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
// Middleware to parse incoming JSON requests
app.use(bodyParser.json());
// Basic route to check if the server is running
app.get('/', (req, res) => {
res.send('Hello, this is a Node.js REST API!');
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Start the server by running:
node server.js
Open your browser and navigate to http://localhost:3000
. You should see the message "Hello, this is a Node.js REST API!"
Step 4: Defining the Routes for CRUD Operations
Now let’s add the main REST API routes to handle CRUD operations. For simplicity, we will manage a list of users with their name
and email
.
First, create an in-memory array to store users:
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];
Now, let’s define the RESTful routes:
Here is the complete code with CRUD routes:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];
// Create a new user
app.post('/users', (req, res) => {
const { name, email } = req.body;
const newUser = {
id: users.length + 1,
name,
email
};
users.push(newUser);
res.status(201).json(newUser);
});
// Get all users
app.get('/users', (req, res) => {
res.status(200).json(users);
});
// Get a single user by ID
app.get('/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.status(200).json(user);
});
// Update a user by ID
app.put('/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');
const { name, email } = req.body;
user.name = name || user.name;
user.email = email || user.email;
res.status(200).json(user);
});
// Delete a user by ID
app.delete('/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');
users.splice(userIndex, 1);
res.status(204).send();
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Step 5: Testing the API
Now that we have created the REST API with the basic CRUD functionality, you can test it using tools like Postman or curl.
Create a user (POST /users
):
http://localhost:3000/users
POST
Get all users (GET /users):
URL: http://localhost:3000/users
Method: GET
Get a specific user (GET /users/:id):
URL: http://localhost:3000/users/1
Method: GET
Update a user (PUT /users/:id):
URL: http://localhost:3000/users/1
Method: PUT
Body:
Get all users (GET /users
):
http://localhost:3000/users
GET
Get a specific user (GET /users/:id
):
http://localhost:3000/users/1
GET
Update a user (PUT /users/:id
):
http://localhost:3000/users/1
PUT
{
"name": "Updated Name",
"email": "updated@example.com"
}
Delete a user (DELETE /users/:id
):
http://localhost:3000/users/1
DELETE
Conclusion
You have now successfully built a simple REST API using Node.js and Express.js. This API supports the fundamental CRUD operations (Create, Read, Update, and Delete) for managing user data. The flexibility of Express allows you to expand the functionality with additional routes, middleware, authentication, and database integration.