Very simple REST API using Express.js
Tags: Nodejs, JavaScript, Expressjs, Programming, API

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:

You make a call to the API telling it what you want. The API receives the call, processes or fetches the data you want. 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:

NodeJS A NodeJS package manager. I will be using NPM which is a very popular package manager for NodeJS. 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:

Open a new Terminal window Type node -v & npm -v

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.

Create a new empty folder and open it with Visual Studio Code Once it’s open in Visual studio code, open the Terminal inside 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:

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

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.

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:

Import express Initialize our express app Set up our express routes 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:

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:

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.

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.

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.

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.

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

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.

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

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

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.

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.

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:

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

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.