Building Restful APIs using Express – Fundamentals

3 min read

In this section, we will learn the fundamentals of building a Restful API using the Express framework. We will apply the knowledge gained in the introductory section of this series, to manage the list of radio stations for our online radio streaming application. We will store all data in a simple array in memory, in order to avoid database complexity at this stage.

The focus here is to build an http service that can be exposed and consumed by various client applications. This client applications include mobile apps, web front end applications and so on. In a later tutorial, I will explain how to store all information in a database like MongoDB.

Express Framework

The Express framework provides a proper structure to Node applications, and helps in keeping a maintainable code base, as the project routes increases. Express is a popular lightweight, fast and properly documented framework for building web applications on top of Node.js

Demo Application with Express

Firstly, let’s create a new project folder and give it a name. I have named my own folder to be express-app.

Secondly, navigate into the project folder and run the npm init –yes command. This command generates the package.json file for our project.

Next, we need to install express using the command below.

npm i express

Building API with Express

Using the project we have just created with express package installation, create a file with the name, index.js. This will serve as the entry point to our application.

Secondly, we need to load the express module using the require function, as shown below.

require('express');

By loading the express module using require keyword, a function is returned and this will be stored in a constant called express, as show below.

const express = require('express');

The next step is to make a call to the function above. The above function returns an object of the type express. The object is usually referred to as app in express projects.

const app = express();

The constant, with the name app refers to an instance of our application. It has a couple of useful methods that can be called on it. This includes the get(), post(), put() and the delete() method. Each of this methods corresponds to the HTTP verbs discussed in section one of this series. 

With this fundamental understanding of setting up an Express project, let’s now implement an endpoint that can respond to an http get request using our radio streaming application as an example.

Handling HTTP GET Request

The HTTP GET Request simply takes two arguments: the website url for hosting the API resources and callback function. The callback represents the function that will be called when there is an http GET request to the endpoint. The callback function contains two arguments: the request and the response.

The request object in Express, contains a lot of properties that can inform us about an incoming request. In order to have a good understanding of this properties, read more by following this link

The first endpoint we are going to build is the base url of our website. We will respond with a welcome message, whenever there is an http GET request to the root of the website from a client application.

app.get('/', (req, res) => {
   return res.send('Welcome to RadioApp...')
});

Finally, we need to listen on a port by specifying a port number. Also, we need to specify a function that will be called, once the application start listening on the specified port.

app.listen(3000, () => console.log('Listening on port 3000...'));

The next thing is to execute our Node application in the terminal using the command below.

node index.js
express web server listening on port 3000

Also, let’s test in a browser by visiting localhost:3000. All things equal, there should be a response from the server with a welcome message..

http response in browser when a client app send a get request

Defining more Routes

Using our radio streaming application, let’s define a route to get the list of radio stations, by following the same steps as we did above.

app.get('/api/v1/stations', (req, res) => {
   return res.send(['Dublab', 'BBC-Radio', 'KAMP-FM']);
});

For real world implementation of this particular project, we will want to get the list of radio stations from a database. This will then be display in a client application such as mobile applications. Some of the popularly used database includes MongoDB, MySQL or Postgres. For demonstration purposes, we will return an array of radio stations when there is an http GET request to the path ‘/api/v1/stations’.

The code snippet below shows the complete index.js file for this section.

Finally, let’s go back to the terminal and execute the updated index.js file, by using the command node index.js.

http request to get list of radio stations from an api endpoint

Notice that we need to stop and start the server again, whenever we make changes to our Node application files. This is a little bit manual and stressful, especially when developing a large application. In order to make sure that the server is restarted automatically whenever there is a change in our project files, we need to make use of a Node package called Nodemon. Read this tutorial to learn how to improve our developed application

HTTP Put and Delete Requests – Building Restful APIs…

In order to update or delete an information, we need have the object ID. Let's analyze the code block below for handling HTTP Put...
appdevchannel
1 min read

Validating POST Request – Building Restful APIs using Express:…

It is important to have a validation mechanism that validates inputs when building web services. Read more as we use the joi package to...
appdevchannel
2 min read

Building Restful APIs using Express: Part 6 – POST…

In this section, we will discuss how to use http POST request to create a new radio station. We will test endpoint using the...
appdevchannel
2 min read

3 Replies to “Building Restful APIs using Express – Fundamentals”

Leave a Reply

Your email address will not be published. Required fields are marked *

Never miss a tutorial from us, get weekly updates in your inbox.