• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Building a REST API with Express: A Step-by-Step Tutorial

  • July 1, 2023
  • CODE OF GEEKS
  • 0
In this Tutorial ->
  • Prerequisites
  • Setting Up the Project
  • Creating Basic Endpoints
  • Basic HTTP Status Codes
  • Handling HTTP Methods
  • Implementing CRUD Operations
  • Source Code
  • Testing the working of our REST APIs
Building a REST API with Express
Building a REST API with Express

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).

Get request to api/user
Get request to api/user

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).

Post request to api/user

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).

Get user with id 1

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

Updating age and email field for existing user
Updating age and email field for existing user

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

User Deleted with id = 1

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,

Tags: Building a REST API with Express tutorialBuilding a RESTful API using Express and Node.js tutorialBuilding RESTful APIs with Express from scratchCreating a REST API with Express and MongoDB tutorialCreating a RESTful API with Express guideExpress REST API tutorial for beginnersExpress REST API tutorial step-by-stepExpress.js API development tutorialExpress.js REST API tutorial with examplesStep-by-step guide to building a RESTful API with Express
  • Previous Validating HTTP Requests using express-validator: A Comprehensive Tutorial
  • Next Working with Cookies in Express: A Comprehensive Tutorial

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

More on Node.js

  • Introduction to Node.js
  • NPM in Node.js
  • Non-Blocking Nature of Node.js
  • First Application with Node.js
  • Node.JS Modules
  • HTTP Module Node.js
  • Reading File with Node.js
  • Writing File with Node.js
  • Creating File with Node.js
  • Updating File with Node.js
  • Deleting File with Node.js
  • Renaming File with Node.js
  • URL Module in Node.js
  • Event Programming with Node.js
  • async-await in Node.js
  • Buffer in Node.js
  • Sending Mails with Node.js
  • Connecting to MySQL(CRUD) in Node.js

More on Express.js

  • Introduction to Express.js
  • Creating First App with Express.js
  • Routes in Express.js
  • Middlewares in Express.js
  • Web App with Express & Pug
  • Web App with Express & EJS
  • Serving Static Files with Express.js
  • Handling Forms with Express.js
  • Handling File uploads in forms
  • Working with Cookies in Express.js
  • Session Handling with Express.js
  • REST API with Express.js
  • Validating Requests in Express.js
  • Fetch data from External API with axios
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.