Building a Node.js Rest API Using Express

Abdulhafeez Abdulraheem

In this article, you’ll learn how to create a simple food ordering API with Node.js and Express. You’ll also understand the http methods (get, post, patch and delete) involved in creating a standard API.

Prerequisites

To follow this article a basic understanding of JavaScript is required. Please ensure that you have Node.js and npm installed before you begin.

We’ll be using these tools to build out our application:

  1. Express
  2. Node.js

Setting Up the App

To get started, we need to create a new folder and generate a package.json . The package.json file is what bootstraps our Node app and manages the dependencies of our project.

To do this, we’ll use npm at the CLI to generate the package.json:

$ npm init -y

We’ll also use npm to install Express and body-parser. Express makes it easy to create routes and logic connected to each routes. The body-parser package is a middleware that we’ll use to parse the body of incoming requests.

To install express, open the terminal and run:

$ npm install express body-parser

We are done with setting up the app for development.

App Entry Point

We want want to build a food ordering system that:

  • Creates a new food order
  • Gets all food orders
  • Updates a food order
  • Deletes a food order

First we create our API entry point which is a simple JavaScript file called app.js.

Input the following code into the file:

const express = require("express");

const app = express();
const bodyparser = require("body-parser");

const port = process.env.PORT || 3200;

// middleware

app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));

app.listen(port, () => {
  console.log(`running at port ${port}`);
});

To run the following code, open the package.json and add this into the scripts object:

"start": "node app.js"

Open the CLI and run:

$ npm start

you should see a message like this:

running at port 3200

Creating a New Food Order

Creating a new food order can be likened to sending a post request to an API, the http post method allows you to send data from the client to the API.

First we need a variable to hold all the orders. Normally, this would be a database (SQL, MongoDb), But we are focusing on the API in this tutorial so we’ll skip the database layer.

Let’s create a variable to hold all the orders in our app.js file, like so:

const orders = [];

This will hold all food orders that come into our API from the client. To create a new food order, we’ll collect the following:

  • Food Name
  • Customer Name
  • Food Quantity

To create a new order, input to the following code just before the app.listen, like so:

app.post("/new_order", (req, res) => {
  const order = req.body;

  if (order.food_name && order.customer_name && order.food_qty) {
    orders.push({
      ...order,

      id: `${orders.length + 1}`,

      date: Date.now().toString()
    });

    res.status(200).json({
      message: "Order created successfully"
    });
  } else {
    res.status(401).json({
      message: "Invalid Order creation"
    });
  }
});

We created a new route, /new_order, with the post method to accept the incoming food order data, and we check if any of the required data needed to created a new order is valid, then we push a new order object to the the orders array we created earlier and we add an id and date key to the order. To test restart the server.

Getting All Food Orders

To retrieve all the food orders, simply input the code below, like so:

app.get("/get_orders", (req, res) => {
  res.status(200).send(orders);
});

This creates a get request on the /get_orders route and sends the orders as an array to the client.

Updating a Food Order

To update a food order, we use the patch method, like so:

app.patch("/order/:id", (req, res) => {
  const order_id = req.params.id;

  const order_update = req.body;

  for (let order of orders) {
    if (order.id == order_id) {
      if (order_update.food_name != null || undefined)
        order.food_name = order_update.food_name;

      if (order_update.food_qty != null || undefined)
        order.food_qty = order_update.food_qty;

      if (order_update.customer_name != null || undefined)
        order.customer_name = order_update.customer_name;

      return res
        .status(200)
        .json({ message: "Updated Succesfully", data: order });
    }
  }

  res.status(404).json({ message: "Invalid Order Id" });
});

This accepts the order id and the updates related to the order id and updates it by looping through the orders array to get the id that matches with the one in the orders array and updates it. If it doesn’t find an order with the id passed in to the route it returns a 404 http code and a message of Invalid Order Id.

Deleting a Food Order

To delete a food order we create a route that accepts the id of the particular order that needs to be deleted, like so:

app.delete("/order/:id", (req, res) => {
  const order_id = req.params.id;

  for (let order of orders) {
    if (order.id == order_id) {
      orders.splice(orders.indexOf(order), 1);

      return res.status(200).json({
        message: "Deleted Successfully"
      });
    }
  }

  res.status(404).json({ message: "Invalid Order Id" });
});

This accepts the order id and finds the order in the orders array by looping current and getting the corresponding order with the id provided. Using the splice method we can remove the order from the orders array.

Conclusion

With the tools and methods covered in this tutorial, you should now be able to create simple REST APIs in Node.js using Express. This is only an example of what can be done and you can extend this by connecting to a database, to make the data persistent.

You can find the source code here.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#