Very simple REST API using Express.js

Reanimated
Analytics Vidhya
Published in
9 min readOct 4, 2020
Graphic illustration of backend and frontend interaction
Designed by slidesgo / Freepik

What is a REST Api?

In simple terms a REST Api is an API on a backend which you make a call to from the frontend/client side, telling it what you want and it returns your data.

API Example

A very simple example is as follows: Let’s say you have a database with a bunch of product data in. You want a list of products that is cheaper than $200. You make a call to the API from the frontend. The API queries the database and returns a list of products cheaper than $200. Very simple right! You can create very complex APIs, but most of the time you’ll only need a very simple one. It’s most commonly used to query and return data from a database.

Just to summarize, the steps are:

  1. You make a call to the API telling it what you want.
  2. The API receives the call, processes or fetches the data you want.
  3. Sends the data back to you.

Building a REST API with Express.js

Just quickly before we start. What is Express.js?

Express is a backend web framework for Node.js which you can use to easily make an API

Getting Started

Things that you will need:

  1. NodeJS
  2. A NodeJS package manager. I will be using NPM which is a very popular package manager for NodeJS.
  3. A code editor. I will be using Visual Studio Code

After you have installed NodeJS and NPM, make sure that it’s installed correctly. This is very easy:

  1. Open a new Terminal window
  2. Type node -v & npm -v
Snippet of CMD window about checking whether node and npm are installed as well as which version are installed
CMD window showing Node and NPM versions

Now that you can see your Node and NPM versions you can rest assured that it’s installed and jump right into the next thep. If you don’t see a version, try restarting your PC or reinstalling Node or NPM.

Setting up the project

Before we can install express, first we need to create our project.

  1. Create a new empty folder and open it with Visual Studio Code
  2. Once it’s open in Visual studio code, open the Terminal inside of VS Code
Snippit of VS Code
Click to open Terminal inside of VS Code

3) Now we want to initialize your project as an NPM project. This will allow us to use NPM. What NPM does is essentially downloads and installs libraries/extensions/plugins we can use.

We do this by typing npm init into the terminal:

VS Code snippit about initializing an npm project
How to initialize an NPM project so that you can make us of NPM

Once you press enter, it will ask you a bunch of questions which you don’t have to worry about when getting started. Just enter through all of them and leave them as they are.

Great! You have now initialized an NPM project, and you can now make use of NPM to install packages such as Express and Nodemon.

Installing Express and Nodemon

To do this you just need to type the following into your terminal:

npm install express & npm install nodemon

VS Code terminal snippet about installing the express and nodemon packages

Once you press enter, NPM will install the packages and everything needed to use those packages for you. These packages are called Dependencies and are stored in a newly created folder called node_modules which you can just ignore.

What is Nodemon and why do we need it?

We will be using Nodemon to automatically restart the application as soon as we make any changes to any of our files so that the latest version of our application is always running.

We don’t need Nodemon, but we will then need to restart our program manually each time we make a change to see it take effect which would be very unproductive.

By now you have already accomplished a lot and might want to take a quick break. We’ll be getting into some actual programming from here on out.

“Taking a break can lead to breakthroughs.”
Russell Eric Dobda

Creating API with Express

We have now installed everything we need and can start by setting up our backend API.

We’ll start off by creating a file called server.js. This will be our main application file. Think of an exe file for a game. It’s the file you open to start up your project. You can name it anything you want to, but server.js is commonly used and makes sense, because our API will run on a backend server and this file will be used to start up the backend application.

VS Code snippet about creating our main application entry file, server.js
Create a new file inside of VS Code in your main directory

Now open your newly created server.js file. Let’s quickly think about the steps we need to follow:

  1. Import express
  2. Initialize our express app
  3. Set up our express routes
  4. Set up our express listener

This might seem like a lot of steps and at the moment you might not understand what any of these steps mean, but don’t worry in just a while everything will make more sense.

Import Express

To use express we first need to import it into our program. That makes sense right? Well thankfully it’s super easy to import packages. See the following code example:

Code snippet where we import express
The following line of code imports the express package

Very quick and easy right! We can now start using express.

Initialize Express app

We can now use features from express, but it won’t work properly if we don’t initialize our express application first. Luckily for us, it’s very quick and easy to do:

Code snippet where we initialize our express application
This code initializes an express application

Explanation

Line 5: Here we all creating a constant variable named app and setting it equal to an express application.

It’s a constant variable because it will never change. Express() initialized an express application and we want to store that application somewhere so that we can use it right? So that’s why we store it in a variable named app. Don’t worry about understanding it too much, you just need to remember this step.

Line 6: Here we are creating a variable named port and setting it to an integer value of 3000. This port will be used to access our application on when viewing it in the browser. It can be any 4 digit value from 0 to 65535. You don’t need to worry about this, as it will be explained better later when we use this variable in the last step.

Set up Express Routes

An Express Route is a specific location which we can make a call to. Let’s pretend that it’s a number. Each route is a business and each business has its own unique number. We can use that number to call the business and get specific information from them. Let’s see the code so that it makes more sense.

Code snippet where we set up our express route
This code creates a route that we can now access in the browser once the application is running

Explanation

Line 9: Here we use our app variable which is an express application. We call the get procedure, which means we are simply calling the route/business to get information. The first parameter ‘/’ is the location/number we are calling. The second parameter is an anonymous function with two parameters namely req (request) and res (response). These parameter variables can be called anything but the current names make more sense.

Line 10: Inside of the anonymous function we send a response with res.send(). res stands for response, and we send it. Makes sense so far right. Inside of the send() procedure we pass in the information we want to send back. Here we are simply sending back some text that says ‘Hello World!’ when the client makes a call on the ‘/’ route, which is also the base path.

Line 11: We simply close the get procedure.

Inside of the anonymous function we can do calculations, make function calls etc. and then send those calculation or returned values from the functions as the response. We’ll be doing an example once the application is set up and running.

Set up our Express Listener

This is the last step we need to do before we can start our application. We basically need to tell our application on which port to listen for calls. This will be using the port variable we made at the start of the application.

Code snippet where we set up our Express listener
This code tells the express application to listen for any calls on port 3000

Explanation

Line 14: Here we use our express application’s listen procedure with two parameters. The first one being the port variable on which the application should listen on. The second parameter is an anonymous callback function which runs as soon as the application starts listening on that port.

Line 15: Here we just put any code that should run as soon as the application starts listening on the specified port. We are simply logging a string to the console that states the location that we can use to make API requests.

Starting our Express API application

To start the application we are going to be using nodemon and the VS Code terminal. It’s very easy. You will simply type nodemon <insert main file name> to start your application with nodemon.

Terminal snippet showing you how to start application with Nodemon
This terminal code will start the application with nodemon

Once you see the following text in your terminal you have succeeded in making your very first API using Express.

Terminal snippet showing you that the application is running via Nodemon

We can now make an API call using our browser. To do this open your browser and visit the following URL: http://localhost:3000/

Browser snippet showing API response

Awesome!

Here you can see that our API is working. We visited the URL: http://localhost:3000/ which is basically the same as accessing the ‘/’ route.

Note that from now on when you make additional changes to the application you don’t need to start the application again unless you closed VS Code. This is why we installed Nodemon. When me make changes in the future Nodemon will keep watch on all of our files, and when we make a change to them it will automatically restart our program for us. You will then see the following text in the terminal.

Terminal snippet of how Nodemon automatically restarts server
Nodemon automatically restarting our application on file changes

Let’s make some more useful routes.

We can keep the base route of ‘/’ so that we can easily check that our program is still working, but let’s make something more interesting.

Create another Route

Code snippet of our new route setup
This will be our second route

Just below our first route we can create another route with a path of ‘/newRoute’. This path could be anything and can be accessed at http://localhost:3000/newRoute

For now we will just simply send a basic string back to the client

Browser snippet where we show that accessing our new route works
When accessing http://localhost:3000/newRoute we will receive our newly created response

Let’s now do something more interesting. Let’s create a list of food names. We will then set up a route that will return a random food name. Think of it as a random food selector or a food of the day feature maybe.

Let’s change the route we just created. Firstly we will change the path, and then create a simple variable with food strings in.

Code snippet where we are setting up a new API route for getting back a random food name
New route that will return a random food name

We now want to get a random item from the food array and send it as the response to the API call.

VS Code snippet of our Random Food Selector API route
This API route is now functional and we can

As you can see, this time we did some calculations first before sending the response/data back to the client. Like the example above, you can run any other javascript code within the API call and then return a response with the data generated. You can also return variables (like we did above), javascript arrays, JSON etc.

Let’s see it in action:

A short GIF where we are making API calls and receiving random food names
Each time you refresh the API will return a response containing a string with a random food name

Example of how it can be used in a real life project

A short GIF showing an example of how an API can be used in a real world project
Real World Demo example of API usage

The gif above is a preview of a real world application demo on how this API could be used. In the video it’s used on a company site that’s all about recipes. They use it to generate some very cool and random recipes for the users. It adds some more functionality to the website and makes it more interactive and dynamic so that it can stand out from competitors.

Keep an eye on my Medium profile for future articles where we will be going more in depth and learning some other Express features so that we can take our API to the next level.

Thanks for reading.

--

--

Reanimated
Analytics Vidhya

Digital solutions for humans by humans. We specialize in web, desktop and mobile applications.