Creating a REST API is one of the most common tasks developers perform when building web applications. In this tutorial, we’ll guide you through setting up a RESTful API using Node.js and the Express framework. Express is a minimal and flexible Node.js web application framework that makes it easier to build APIs quickly.
Let’s dive into the process.
Prerequisites
Before we start, ensure you have the following installed:
- Node.js: You can download and install Node.js from here.
- npm (Node Package Manager): npm comes with Node.js, so installing Node will also install npm.
- A code editor like VS Code.
- Basic knowledge of JavaScript and Node.js.
Step 1: Initialize a Node.js Project
Start by creating a directory for your project and initialize a new Node.js project:
- Open your terminal or command prompt.
- Create a new directory and navigate to it:bashCopy code
mkdir my-api cd my-api
- Initialize a new Node.js project:bashCopy code
npm init -y
This will create apackage.json
file with default values.
Step 2: Install Dependencies
Next, install Express and nodemon (for automatic server restarts during development):
bashCopy codenpm install express
npm install --save-dev nodemon
- Express is the web framework for Node.js.
- Nodemon is a development tool that monitors for changes in the source code and automatically restarts the server.
Add the following script in your package.json
file to use nodemon
to start your server:
jsonCopy code"scripts": {
"start": "nodemon server.js"
}
Step 3: Create the API Server
Now, let’s create the server file (server.js
):
- In your project folder, create a file called
server.js
:
bashCopy codetouch server.js
- Open
server.js
and add the following code to set up the Express server:
javascriptCopy code// server.js
const express = require('express');
const app = express();
const port = 3000;
// Middleware to parse JSON request bodies
app.use(express.json());
// Sample data (in-memory storage for demonstration purposes)
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' },
];
// Root endpoint to check if the API is working
app.get('/', (req, res) => {
res.send('Welcome to the Node.js REST API!');
});
// GET all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET a user by ID
app.get('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const user = users.find((u) => u.id === userId);
if (!user) {
return res.status(404).send('User not found');
}
res.json(user);
});
// POST a new user
app.post('/api/users', (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).send('Name and email are required');
}
const newUser = {
id: users.length + 1,
name,
email,
};
users.push(newUser);
res.status(201).json(newUser);
});
// PUT to update a user's details
app.put('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const { name, email } = req.body;
const user = users.find((u) => u.id === userId);
if (!user) {
return res.status(404).send('User not found');
}
user.name = name || user.name;
user.email = email || user.email;
res.json(user);
});
// DELETE a user by ID
app.delete('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const userIndex = users.findIndex((u) => u.id === userId);
if (userIndex === -1) {
return res.status(404).send('User not found');
}
users.splice(userIndex, 1);
res.status(204).send();
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Explanation of the Code:
- Express Setup: We import Express, create an
app
instance, and set the port to3000
. - Middleware: The
express.json()
middleware is used to parse incoming JSON data. - Routes:
GET /api/users
: Returns a list of all users.GET /api/users/:id
: Retrieves a user by ID.POST /api/users
: Creates a new user and adds it to theusers
array.PUT /api/users/:id
: Updates the user’s name and/or email.DELETE /api/users/:id
: Deletes a user from theusers
array.
Step 4: Run the Server
Now that the server is set up, you can run it with the following command:
bashCopy codenpm start
This will start the server using nodemon, and it will be accessible at http://localhost:3000
.
Step 5: Test the API Endpoints
You can test the API endpoints using tools like Postman, Insomnia, or even curl commands:
- GET all users:
URL:http://localhost:3000/api/users
- GET a user by ID:
URL:http://localhost:3000/api/users/1
- POST a new user (Send JSON data in the request body):
URL:http://localhost:3000/api/users
Body:jsonCopy code{ "name": "Alice Johnson", "email": "alice@example.com" }
- PUT (Update user details):
URL:http://localhost:3000/api/users/2
Body:jsonCopy code{ "name": "Jane Doe", "email": "janedoe@example.com" }
- DELETE a user by ID:
URL:http://localhost:3000/api/users/1
Step 6: Conclusion
You’ve just created a simple REST API with Node.js and Express! This API has basic CRUD operations to manage users, and it runs on port 3000
.