A REST (Representational State Transfer) API—sometimes referred to as a RESTful AP—is an API that uses HTTP requests to access and use resources.

These resources are often represented in JSON format though on some occasions XML, text, and HTML format are used. REST APIs have become a standard way for applications to exchange data over a network through HTTP methods like GET, PUT, POST, and DELETE. They facilitate creating, reading, updating, and deleting resources commonly referred to as CRUD operations.

This guide explores how you can use Node.JS to create a simple CRUD Restful API.

What You Need to Follow Along

Make sure you have Node.js installed on your local machine. Run node -v to check whether Node.JS is installed. This command should return the version number.

Related: How to Install Node.js on Windows

You should also have a working instance of your favorite text editor (e.g. VS Code).

Project Setup

Create a folder for your application and navigate to it. On the terminal and in the directory you just created, initialize package.json by running npm init.

        $ npm init -y 
    

The package.json will help you install and manage npm packages. The -y flag creates the package.json file using the default options without you having to set up the individual details. The output on your terminal should look like this. Note that the name will be different depending on what you named your folder.

Terminal screen showing a generated package.json file

Set Up the Server

To create a server, first, install Express.js and Nodemon. Express.js is a Node.Js framework that was designed to make the development of web applications and APIs easier. You will use it to configure the server and the API endpoints. Nodemon on the other hand is a development tool that will restart your server when your application code changes.

Run the following command to install express and nodemon:

        npm i express nodemon 
    

Next, to create your server, create a file and call it server.js then add the following code.

        // Require express
const express = require("express");
// Initialize express
const app = express();
const PORT = 8080;
// parse JSON
app.use(express.json());
// parse URL encoded data
app.use(express.urlencoded({ extended: true }));
// create a server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

In the above code, require express in your server.js file and initialize it. Then, configure express to parse JSON and URL encoded data. Finally, create a server using the listen() method from Express.

Related: What is Express.js and Why Should You Use It?

Getting Started: Create an Array to Store User Data

For simplicity purposes, you will not be using a database but rather a simple user array. In your app.js, add the following code after the line that parses URL encoded data.

        const users = [{
 id: 1,
 name: "Jane Doe",
 age: "22",
 },
 {
 id: 2,
 name: "John Doe",
 age: "31",
}];

Related: How to Create a Database and Collection in MongoDB

How to Set Up Routes in Express.js

To perform operations on your data, you need to set up routing. Routes will determine how your application will respond to requests made to a particular endpoint. Each route has an HTTP method, a URL, and a handler function that handles the HTTP request and response. To set up the routes, add the following to your server.js file after your users array.

        app.post('/create', (req, res) => {
   // Create a user
});
app.get('/users', (req, res) => {
  // Retrieves all users
});
app.get('/user/:userID', (req, res) => {
   // Returns a user by ID
});
app.put('/user/:userID', (req, res) => {
   // Update a user by ID
});
app.delete('/delete/:userID', (req, res) => {
   // Delete a user by ID
});
app.delete('/users', (req, res) => {
   // Delete all users
});

How to Perform CRUD Operations in Node.Js

You need to create the functions that will manipulate the user data and return a response according to the route matched. These functions will create, read, update, and delete user data.

Related: How to perform CRUD Operations in MongoDB

How to Create a New User

To create a new user, you will need to:

  • Check if the request body is empty—if it is, send an error response.
  • Extract the user data from the request body.
  • Validate the user data.
  • Push the user data to the array.

Note that you are using an array only for simplicity purposes. In a real case scenario, you would be interacting with a database.

Edit your POST route as below.

        app.post("/create", (req, res) => {
// Check if request body is empty
if (!Object.keys(req.body).length) {
   return res.status(400).json({
     message: "Request body cannot be empty",
   });
}
// Use object destructuring to get name and age
const { name, age } = req.body;
if (!name || !age) {
   res.status(400).json({
     message: "Ensure you sent both name and age",
   });
}
const newUser = {
   id: users.length + 1,
   name,
   age,
};
try {
   users.push(newUser);
   res.status(201).json({
     message: "Successfully created a new user",
   });
} catch (error) {
   res.status(500).json({
     message: "Failed to create user",
   });
}
});

How to Read Users

To retrieve all users, return the users array in your response.

        app.get("/users", (req, res) => {
 try {
   res.status(200).json({
       users
     });
 } catch (error) {
   res.status(500).json({
       message: "Failed to retrieve all users",
     });
 }
});

If you test this route using postman, you should receive the array of users in the response body.

postman screenshot showing response from a GET request to an REST API

To retrieve one user only:

  • Get the user ID from the URL parameter.
  • Use find() to identify which specific user data you are requesting.
  • Return the user in the response.
        app.get("/users/:userID", (req, res) => {
 const id = parseInt(req.params.userID);
 console.log(id);
 try {
   let user = users.find((user) => user.id === id);
   if (!user) {
     return res.status(404).json({
       message: "User not found",
     });
   }
   res.status(200).json({
     user,
   });
 } catch (error) {
   res.status(500).json({
     message: "Failed to retrieve user",
   });
 }
});

How to Update Users

To update the user:

  • Retrieve the user ID from the URL.
  • Use find() to check whether the user exists.
  • Use indexOf() to get the index of the user being referenced.
  • Use the index to edit the user data with the data sent through the request body.
        app.put("/users/:userID", (req, res) => {
 try {
   const id = parseInt(req.params.userID);
   let user = users.find((user) => user.id === id);
   if (!user) {
     return res.status(404).json({
       message: "User not found",
     });
   }
   const userIDX = users.indexOf(user);
   users[userIDX].name = req.body.name || users[userIDX].name;
   users[userIDX].age = req.body.age || users[userIDX].age;
   res.status(200).json({
     message: "Successfully updated user",
     user,
   });
 } catch (error) {
   res.status(500).json({
     message: "Failed to retrieve user",
   });
 }
});

How to Delete Users

You can choose to delete one user or all users.

To delete one user:

  • Retrieve the user ID from the URL
  • Use find() to check whether the user exists
  • Use findIndex() to get the index of the user being referenced.
  • Use splice() to delete the user at that index.
        app.delete("/users/:userID", (req, res) => {
 try {
   const id = req.params.userID;
   let userIDX = users.findIndex((user) => user.id === id);
   if (!userIDX) {
     res.status(404).json({
       message: "User not found",
     });
   }
   users.splice(userIDX, 1);
   res.status(200).json({
     message: "Successfully deleted user",
     users,
   });
 } catch (error) {
   res.status(500).json({
     message: "Failed to delete user",
   });
 }
});

To delete all the users, splice the whole array.

        app.delete("/users", (req, res) => {
 try {
   users.splice(0, users.length);
   res.status(200).json({
     message: "Successfully deleted all users",
     users,
   });
 } catch (error) {
   res.status(500).json({
     message: "Failed to delete users",
     x,
   });
 }
});

Learn More About RESTful APIs

This tutorial discusses how to create a basic RESTful API in Node.JS. You have learned how to create an Express server, set up routes, and finally, create handler functions that interact with your data through HTTP requests/responses.

There are however some essential topics not covered here that you should research further, including how to connect your application to a database like MongoDB and how to secure routes.