In this Tutorial ->

In this tutorial, we’ll explore how to build a powerful and SEO optimized REST API using Express, a fast and flexible web application framework for Node.js. Whether you’re a beginner or an experienced developer, this step-by-step guide will help you understand the core concepts and best practices of building RESTful APIs with Express.
Prerequisites
To follow along with this tutorial, you’ll need the following:
- Basic understanding of JavaScript and Node.js.
- Node.js and npm (Node Package Manager) installed on your machine.
- A code editor (e.g., Visual Studio Code).
Setting Up the Project
To get started, follow these steps:
Step 1: Create a new directory for your project.
mkdir rest-api-tutorial
cd rest-api-tutorial
Step 2: Initialize a new Node.js project and install Express.
npm init -y
npm install express
Step 3: Create an index.js file in the project directory and open it in your code editor with this code.
const express = require('express');
const app = express();
const port = 3000;
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
4. Install and Import the Required Middleware: Ensure that you have installed the body-parser middleware package. You can install it by running npm install body-parser. Then, import it into your Express application:
const bodyParser = require('body-parser')
Use the Middleware in Your Application: Add the following lines of code to your Express application to use the body-parser middleware:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
The body-parser middleware is used to parse different types of request bodies, such as URL-encoded and JSON bodies.
Creating Basic Endpoints
In this section, we’ll create the basic endpoints for our REST API that specifically performs CRUD operations on User Model.
Step 1: Import Express and create an instance of the application.
const express = require('express');
const app = express();
Step 2: Create a GET endpoint to retrieve a list of users.
app.get('/api/user', (req, res) => {
// Logic to fetch and return the list of users
});
Step 3: Create a POST endpoint to create a new user.
app.post('/api/user', (req, res) => {
// Logic to create a new user
});
Step 4: Create a GET endpoint to retrieve a specific user by ID.
app.get('/api/user/:id', (req, res) => {
// Logic to fetch and return a specific user by ID
});
Basic HTTP Status Codes
Status Codes represent common responses from the server to the client and provide information about the outcome of the HTTP request. It’s important to familiarize yourself with these status codes and their meanings to effectively handle and interpret API responses.
200 OK – Success
201 Created – Created
204 No Content – No Content
400 Bad Request – Bad Request
401 Unauthorized – Unauthorized
403 Forbidden – Forbidden
404 Not Found – Not Found
500 Internal Server Error – Internal Error
503 Service Unavailable – Unavailable
Handling HTTP Methods
In this section, we’ll handle different HTTP methods using Express middleware.
Step 1: Parse JSON data in request bodies using Express middleware.
app.use(express.json());
Step 2: Handle PUT requests to update a user by ID.
app.put('/api/user/:id', (req, res) => {
// Logic to update a specific user by ID
});
Step 3: Handle DELETE requests to delete a user by ID.
app.delete('/api/user/:id', (req, res) => {
// Logic to delete a specific user by ID
});
Implementing CRUD Operations
In this section, we’ll implement the CRUD (Create, Read, Update, Delete) operations for users.
Step 1: Create an array to store the users.
let users = [];
Step 2: Implement the logic to fetch and return the list of users (for GET request).
app.get('/api/user', (req, res) => {
try {
res.json(users);
} catch (error) {
if (error.response) {
// The API responded with a non-2xx status code
const {
status
} = error.response;
res.status(status).json({
error: `API request failed with status ${status}`
});
} else if (error.request) {
// The request was made, but no response was received
res.status(500).json({
error: 'No response received from the API'
});
} else {
// Other errors occurred
res.status(500).json({
error: 'An error occurred while fetching data from the API'});
}
}
});
Step 3: Implement the logic to create a new user (for POST request).
app.post('/api/user', (req, res) => {
try {
const newUser = req.body;
users.push(newUser);
res.status(201);
res.json(
{
"message": "User Added !!",
"body": newUser
});
} catch (error) {
if (error.response) {
// The API responded with a non-2xx status code
const {
status
} = error.response;
res.status(status).json({
error: `API request failed with status ${status}`
});
} else if (error.request) {
// The request was made, but no response was received
res.status(500).json({
error: 'No response received from the API'
});
} else {
// Other errors occurred
res.status(500).json({
error: 'An error occurred while fetching data from the API');
}
}
});
Step 4: Implement the logic to fetch and return a specific user by ID (for GET[ID] request).
app.get('/api/user/:id', (req, res) => {
try {
const userId = req.params.id;
const user = users.find(r => r.id === userId);
if (!user) {
res.status(404).json({
error: 'User not found'
});
} else {
res.json(user);
}
} catch (error) {
if (error.response) {
// The API responded with a non-2xx status code
const {
status
} = error.response;
res.status(status).json({
error: `API request failed with status ${status}`
});
} else if (error.request) {
// The request was made, but no response was received
res.status(500).json({
error: 'No response received from the API'
});
} else {
// Other errors occurred
res.status(500).json({
error: 'An error occurred while fetching data from the API'});
}
}
});
Step 5: Implement the logic to update a specific user by ID (for PUT request).
app.put('/api/user/:id', (req, res) => {
try {
const userId = req.params.id;
const updatedUser = req.body;
// Find the user and update its properties
const userIndex = users.findIndex(r => r.id === userId);
if (userIndex === -1) {
res.status(404).json({
error: 'User not found'
});
} else {
users[userIndex] = {
...users[userIndex],
...updatedUser
};
res.json(users[userIndex]);
}
} catch (error) {
if (error.response) {
// The API responded with a non-2xx status code
const {
status
} = error.response;
res.status(status).json({
error: `API request failed with status ${status}`
});
} else if (error.request) {
// The request was made, but no response was received
res.status(500).json({
error: 'No response received from the API'
});
} else {
// Other errors occurred
res.status(500).json({
error: 'An error occurred while fetching data from the API'});
}
}
});
Step 6: Implement the logic to delete a specific user by ID.
app.delete('/api/user/:id', (req, res) => {
try {
const userId = req.params.id;
// Find the user and remove it from the array
const userIndex = users.findIndex(r => r.id === userId);
if (userIndex === -1) {
res.status(404).json({
error: 'User not found'
});
} else {
const deletedUser = users.splice(userIndex, 1);
res.json(deletedUser[0]);
}
} catch (error) {
if (error.response) {
// The API responded with a non-2xx status code
const {
status
} = error.response;
res.status(status).json({
error: `API request failed with status ${status}`
});
} else if (error.request) {
// The request was made, but no response was received
res.status(500).json({
error: 'No response received from the API'
});
} else {
// Other errors occurred
res.status(500).json({
error: 'An error occurred while fetching data from the API'});
}
}
})
Source Code
Please feel free to download source code from here.
Testing the working of our REST APIs
1. Starting the Application
node index.js
Make sure your server is up and running.
2. Configuring Postman
Postman is a common and efficient way to verify its functionality and ensure that it behaves as expected. Postman provides a user-friendly interface for sending HTTP requests and inspecting the responses.
3. Install and Launch Postman
If you haven’t already, download and install Postman from the official website (https://www.postman.com/downloads/). Postman is available for Windows, macOS, and Linux operating systems.
Launch Postman: Once installed, launch the Postman application on your computer.
4. Create a New Request
In Postman, click on the “New” button in the top left corner to create a new request. You can choose the HTTP method (GET, POST, PUT, DELETE, etc.) based on the operation you want to test.
5. Making a get request to http://localhost:3000/api/user (as in step 2 above).

This endpoint returns empty list with 200 success response. Result is empty as currently there are no users.
6. Making a post request to http://localhost:3000/api/user (as in step 3 above).

Now, we have added a user with id = 1.
7. Making a get request to http://localhost:3000/api/user with id (as in step 4 above).

7. Making a put request to http://localhost:3000/api/user with id (as in step 5 above).

8. Making a delete request to http://localhost:3000/api/user with id (as in step 6 above).

To verify this, you can re-invoke our get api (/api/user) to fetch all users, you will get empty result.

So, now we have tested all our REST Endpoints.
This is still a lot more to explore about REST APIs like request validation, error handling, testing the API, pagination, and securing the API. We have explained each of them in our next tutorials.
Keywords to search for:
Building a REST API with Express tutorial,
Express REST API tutorial step-by-step,
Creating a RESTful API with Express guide,
Building RESTful APIs with Express from scratch,
Express REST API tutorial for beginners,
Step-by-step guide to building a RESTful API with Express,
Express.js REST API tutorial with examples,
Building a RESTful API using Express and Node.js tutorial,
Creating a REST API with Express and MongoDB tutorial,
Express.js API development tutorial,
