Express JS, a web application framework for Node.js, provide an ideal environment for creating RESTful APIs
In this comprehensive guide, we’ll walk through the process of building a REST API with Node.js and Express.
Prerequisites
Before getting started with building a RESTful API using Node.js and Express, make sure you have the following prerequisites in place:
- Node.js and npm: Ensure you have Node.js and npm (Node Package Manager) installed on your system. You can download them from the official website: Node.js Downloads.
- Text Editor or IDE: Choose a code editor or integrated development environment (IDE) to write your code. Popular choices include Visual Studio Code, Sublime Text.
🚀 Getting Started:
Let’s start by creating a new Node.js project and setting up the environment.
Step 1: Initialize a Node.js Project
Open your terminal or command prompt and navigate to the directory where you want to create your project.
Run the following command to initialize a new Node.js project:
npm init
You will be prompted to provide information about your project. Follow the prompts to complete the initialization.
Step 2: Install Express
Now that your project is initialized, you need to install the Express framework. Run the following command to install Express as a project dependency:
npm install express
This will download and install the Express package.
Step 3: Create the Main Application File
Create a new file in your project directory, typically named app.js
or index.js
. This file will serve as the main entry point for your application.
In this file, you need to require Express, create an instance of the application, and set up a basic route. Here’s a minimal example:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
// Parsing incoming requests
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Step 4: Start the Application
You can now start your Node.js application by running the following command in your terminal:
node app.js
Your application should be running on the specified port (or the default port 3000). You can access it by opening a web browser and navigating to http://localhost:3000
. You should see the “Hello, World!” message.
👷 Building a RESTful API:
Now that you have a basic Express application up and running, it’s time to create a RESTful API.
Step 1: Define API Routes
In a RESTful API, routes correspond to resources, and HTTP methods define actions on these resources. Here’s an example of defining routes for a simple REST API:
// Define a list of items
const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
];
// Get all items
app.get('/api/items', (req, res) => {
res.json(items);
});
// Get a single item by ID
app.get('/api/items/:id', (req, res) => {
const itemId = parseInt(req.params.id);
const item = items.find(i => i.id === itemId);
if (!item) {
return res.status(404).json({ message: 'Item not found' });
}
res.json(item);
});
In this example, we’ve defined two routes: one to get all items and another to get a single item by ID.
Step 2: Handle HTTP Methods
In REST, HTTP methods such as GET, POST, PUT, and DELETE are used to perform actions on resources. You can define routes for these methods to create a full-fledged API.
// Add a new item (POST)
app.post('/api/items', (req, res) => {
const newItem = req.body;
items.push(newItem);
res.status(201).json(newItem);
});
// Update an item (PUT)
app.put('/api/items/:id', (req, res) => {
const itemId = parseInt(req.params.id);
const updatedItem = req.body;
const index = items.findIndex(i => i.id === itemId);
if (index === -1) {
return res.status(404).json({ message: 'Item not found' });
}
items[index] = updatedItem;
res.json(updatedItem);
});
// Delete an item (DELETE)
app.delete('/api/items/:id', (req, res) => {
const itemId = parseInt(req.params.id);
const index = items.findIndex(i => i.id === itemId);
if (index === -1) {
return res.status(404).json({ message: 'Item not found' });
}
const deletedItem = items.splice(index, 1);
res.json(deletedItem[0]);
});
These routes handle creating, updating, and deleting items using the HTTP methods POST, PUT, and DELETE, respectively.
Step 3: Test the API
Here is the Complete Code:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
// Define a list of items
const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
];
// Parsing incoming requests
app.use(express.json());
// Get all items
app.get('/api/items', (req, res) => {
res.json(items);
});
// Get a single item by ID
app.get('/api/items/:id', (req, res) => {
const itemId = parseInt(req.params.id);
const item = items.find((i) => i.id === itemId);
if (!item) {
return res.status(404).json({ message: 'Item not found' });
}
res.json(item);
});
// Add a new item (POST)
app.post('/api/items', (req, res) => {
const newItem = req.body;
items.push(newItem);
res.status(201).json(newItem);
});
// Update an item (PUT)
app.put('/api/items/:id', (req, res) => {
const itemId = parseInt(req.params.id);
const updatedItem = req.body;
const index = items.findIndex((i) => i.id === itemId);
if (index === -1) {
return res.status(404).json({ message: 'Item not found' });
}
items[index] = updatedItem;
res.json(updatedItem);
});
// Delete an item (DELETE)
app.delete('/api/items/:id', (req, res) => {
const itemId = parseInt(req.params.id);
const index = items.findIndex((i) => i.id === itemId);
if (index === -1) {
return res.status(404).json({ message: 'Item not found' });
}
const deletedItem = items.splice(index, 1);
res.json(deletedItem[0]);
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Restart your Node app.js and test your REST API.
To test your RESTful API, you can use tools like Postman, Insomnia, VS Code Thunder Client extension, etc.
# Get all items
Request (GET) - http://localhost:3000/api/items
Response (200):
[
{ "id": 1, "name": "Item 1" },
{ "id": 2, "name": "Item 2" },
{ "id": 3, "name": "Item 3" }
]
# Get a single item
Request (GET) - http://localhost:3000/api/items/1
Response (200) - {"id":1,"name":"Item 1"}
# Add a new item
Request (POST) - http://localhost:3000/api/items
Payload (JSON) - {"id":4, "name":"John"}
Response (201) - {"id":4, "name":"John"}
# Get all items (after adding a new item)
Response:
[
{ "id": 1, "name": "Item 1" },
{ "id": 2, "name": "Item 2" },
{ "id": 3, "name": "Item 3" },
{ "id": 4, "name": "John" }
]
# Update an item
Request (PUT) - http://localhost:3000/api/items/4
Payload (JSON) - {"id":4, "name":"Rahul"}
Response (200) - {"id":4, "name":"Rahul"}
# Get all items (after update the id 4)
Response:
[
{ "id": 1, "name": "Item 1" },
{ "id": 2, "name": "Item 2" },
{ "id": 3, "name": "Item 3" },
{ "id": 4, "name": "Rahul" }
]
# Delete an item
Request (DELETE) - http://localhost:3000/api/items/3
Response (200) - {"id":3, "name":"Item 3"}
# Get all items (after deleting the id 3)
Response:
[
{ "id": 1, "name": "Item 1" },
{ "id": 2, "name": "Item 2" },
{ "id": 4, "name": "Rahul" }
]
Conclusion:
Building a RESTful API with Node.js and Express is an easy and powerful way to create a backend for your web applications.
This guide provides a starting point for creating a RESTful API using Node and Express, and you can expand it by adding more things as per the requirement of the project like –
- Using Database to store data
- Error Handling and Validation
- Authentication and Authorization
- File Uploading. Etc.
Thank You… 🙏❤️❤️