DEV Community

Cover image for How to rapidly build a basic RESTful API using ExpressJS
Emmanuel Fordjour  Kumah
Emmanuel Fordjour Kumah

Posted on

How to rapidly build a basic RESTful API using ExpressJS

In our previous post, we learned how to create an ExpressJs server. In this article, we will learn how to build a basic REST API using ExpressJS.

By the end of the article, you should

  • Know what an API is

  • Be able to create a server

  • Be able to listen to the connection to the server

  • Be able to request for data

  • Be able to send a json response to the client to access the requested data

Prerequisites:

Before continuing with this article, you should be familiar with

Overview

In this article, we will assume you are a developer for a large eCommerce store, and you have been tasked to build an API that lists the products they sell.

The API you will build will enable any developer to integrate the product listings in the eStore he is building.

Let's learn how to build a simple API using ExpressJS.

What is an API?

API stands for Application Programming Interface. It is an interface through which programs talks to one another.

With an API, you can have access to code running on a server and use that code to build applications. This enables developers to build, connect, and integrate applications quickly.

APIs are used to communicate your requests to applications whenever you interact with them to retrieve information or perform actions. This allows it to understand the request and fulfill it.

Backend developers build these APIs and make them accessible to build frontend applications

API

What is REST API?

API comes in many different formats and types. Among these types is REST, which stands for Representational State Transfer.

With REST API, the server transfers a representation of the requested resource's state to the client whenever a request is made.

This state can be represented in JSON, XML, or HTML format. JSON (JavaScript Object Notation) is the most popular file format to use as it is readable by both humans and machines.

For instance, whenever a developer requests Facebook API to fetch a user resource, the API sends the state of the user ( name, friends, posts, followers), represented in either a JSON, XML, or HTML format.

Generally, most APIs follow the REST format.

Accessing data using endpoints

In APIs, an endpoint is a URL that provides the location of a resource on the server. It enables developers to access data on the server to be used for building apps.

The Methodology

In building our basic API, we would not be using any database program like MongoDB. In our project directory, however, we will create a file containing an array of product objects.

The step to follow in creating our basic API is as below:

  • Create an express app and listen for connection to the app (web server)

  • Use HTTP get method to request for data on the app (web server)

  • Send a json response to the client with the requested data

Creating an Express app and listening for connection

You should be familiar with how to set up an express development environment and how to create a basic Express application.

The code below creates an Express app and listen for connection to the app

//index.js
const express = require("express"); //require express
const app = express(); //create the app

app.listen(5000, () => {
  console.log("App has started and running ");
}); // listen for connection to the app
Enter fullscreen mode Exit fullscreen mode

Using the HTTP GET method

We will use the HTTP GET method to request a resource (data) from the server.

If the path (URI) requested by the client matches the route we set on the server, we will executed a specified callback function and send a response to the client

Route definition takes the following structure:

app.METHOD(PATH, HANDLER)
Enter fullscreen mode Exit fullscreen mode
  • app is our express application

  • METHOD is the HTTP request method used

  • PATH is a route on the server

  • HANDLER represents the function executed when the route matches.

Because we want to retrieve some data on the server, we will utilize the app.get() method which represents an HTTP GET request.

On our server, we set the route or path to the data as (/api/v1/products).

Whenever the path requested by the client matches that on the server (i.e /api/v1/products ), we will execute the HANDLER function.

  • The HANDLER function accepts two parameters: req and res.

    • The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on
    • The res object represents the HTTP response that an Express app sends when it gets an HTTP request.

As the moment, we will send an HTML response Building an API to the client whenever the request matches the path on the server.

The code is as below:

//index.js
const express = require("express"); //require express
const app = express(); //create the app

app.get("/api/v1/products", (req, res) => {
  res.send(`<h1>Building an API</h1>`); //responding to the request
});
 // listen for connection to the app
app.listen(5000, () => {
  console.log("App has started and running ");
});
Enter fullscreen mode Exit fullscreen mode

Understanding the res object

Whenever an Express app receives an HTTP request, it returns a res object which basically represents the response that will be sent out as part of the API call.

The res object has tons of methods we can use to respond to the request.

In the code above, we utilized the res.send() method. This method sets the content type to text/HTML. In effect, the data we are returning to the client will be treated as text or HTML.

Using the res.json method

There is a method called res.json(). This method converts the parameter you pass to res.json() into a JSON string using JSON.stringify() , and sets the Content-type header to application/json.

JSON is a light weight way for storing and transporting data, and enable the client to automatically parse the response.

The parameter passed can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.

For instance, in the code below, we pass an array of object as our parameter

res.json([{ user: 'Robert',age: 34 }, {user:"Emmanuel", age: 23}])
Enter fullscreen mode Exit fullscreen mode

Responding to the request

The parameter of the res.json() method, contains the data to send to the client.

In our project directory, we created a data.js file. This file contains an array of objects which are the items to expose to the public to enable the frontend developers build the eStore.

Data

Let's perform the actions below with the data we have:

  • To access the data on our server, export the array of objects using the code below
// data.js
module.exports = products
Enter fullscreen mode Exit fullscreen mode
  • Use the require() method to import the data.js file in the index.js (our express app)

See the snippet below

//index.js
...
const products = require("./data");
...
Enter fullscreen mode Exit fullscreen mode
  • Assign the data to the products variable and pass it as a parameter in the res.json() method.

See the snippet below

app.get("/api/v1/products", (req, res) => {
  res.json(products); //use res.json to respond to the requ
});
Enter fullscreen mode Exit fullscreen mode

Viewing the created API

Whenever a user visits the URI api/v1/products a request is made to the server and the server response with the requested data

Visit the URL http://localhost:5000/api/v1/products . You should see something like the below

API

Congrats, we have successfully created our API.

If the app is deployed to production,you can use the fetch() method to request data from the server.

Below is the complete code for building the API

//index.js
const express = require("express"); //require express
const products = require("./data"); //import the data
const app = express(); //create the app

//request for a resource
app.get("/api/v1/products", (req, res) => {
  res.json(products); //send a JSON response to the client
});

//listen for connection to the server
app.listen(5000, () => {
  console.log("App has started and is running ");
});
Enter fullscreen mode Exit fullscreen mode

Click here to view the Github repo for this project

Summary

You have now created a basic API using ExpressJS. Using this API, developers can build amazing eCommerce apps.

This article is the day 6 post on the 30-day challenge I am undertaking to learn backend development. Please feel free, to drop some insights, comment, or share the post to your networks

Top comments (0)