July 11, 2023

Simple RESTful API Using NodeJS and Express

IT Tips & Insights: Learn to create a REST API using Express and NodeJS combined.

By Andre Picoli, Software Engineer

What is RESTful API?

RESTful API is an interface that two computer systems use to exchange information securely over the internet. Most business applications have to communicate with other internal and third-party applications to perform various tasks. RESTful APIs follow secure, reliable, and efficient software communication standards.

What is an API?

An application programming interface (API) defines the rules that you must follow to communicate with other software systems. Developers expose or create APIs so that other applications can communicate with their applications programmatically. You can think of a web API as a gateway between clients and resources on the web.

Clients

Clients are users who want to access information from the web. The client can be a person or a software system that uses the API.

Resources

Resources are the information that different applications provide to their clients. Resources can be images, videos, text, numbers, or any type of data. The machine that gives the resource to the client is also called the server. Organizations use APIs to share resources and provide web services while maintaining security, control, and authentication. In addition, APIs help them to determine which clients get access to specific internal resources.

What is REST?

Representational State Transfer (REST) is a software architecture that imposes conditions on how an API should work. REST was initially created as a guideline to manage communication on a complex network like the internet. You can use REST-based architecture to support high-performing and reliable communication at scale. You can easily implement and modify it, bringing visibility and cross-platform portability to any API system.

API developers can design APIs using several different architectures. APIs that follow the REST architectural style are called REST APIs. Web services that implement REST architecture are called RESTful web services. The term RESTful API generally refers to RESTful web APIs. However, you can use the terms REST API and RESTful API interchangeably.

Why REST?

REST is one of the most used and reliable protocols in the programming world these days, but it is not the only option. Different approaches could use SOAP protocol (older) or something more recent like GraphQL which are other communication protocol options. All of them use the HTTP protocol for data transfer. For this example, I found it feasible to use the simplicity and ease of the REST protocol.

HTTP request methods

HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred to as HTTP verbs. Each of them implements a different semantic.

For this article, we will cover the following methods.

GET – The GET method requests a representation of the specified resource. Requests using GET should only retrieve data. 

POST – The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server. 

PUT – The PUT method replaces all current representations of the target resource with the request payload. 

DELETE – The DELETE method deletes the specified resource. 

Basically, one notable difference between HTTP verbs in our example is that some support body like POST and PUT, and some don’t, such as GET and DELETE.

Learn more about RESTful APIs here. Now that we understand REST API, let’s start our NodeJS API. 

Setting up NodeJS Application 

The first step is to have NPM and NodeJS installed on our machine. 

What is NPM? 

Node package manager is the default package manager for NodeJS. Basically, NodeJS is a JavaScript runtime environment that allows developers to develop scalable applications in a given time. Yarn is another package manager if you desire to learn more about it as well.

What is NodeJS? 

NodeJS is an open-source, cross-platform JavaScript library and runtime environment. You can use it to run web apps outside the client’s browser. NodeJS is the most popular web development technology. With a “Single Threaded Event Loop” architecture, NodeJS manages multiple concurrent clients at the same time. The Node.js processing model is built on the JavaScript event-based model, as well as the JavaScript callback mechanism. 

Installing NPM and NodeJS 

On Ubuntu

https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-20-04 

On Mac OS or Windows

https://coderwall.com/p/mhd6nw/install-node-js-on-mac-os-x-and-windows 

After installing all dependencies, let’s move to creating our directories of Node.

A file called package.json will be created automatically. This file represents all the dependencies we are going to use to have our API running properly. 

The first 2 dependencies that we are going to use will be express and cors.
Express is a minimum framework for web Node applications with many features.
Cors will allow applications to receive requests from different domains.

Installing both together:

Let’s code!

In your favorite IDE or in a notepad, let’s start by creating the first file. It will be called server.js. It is where our application starts. Inside this file, let’s give it some code.

server.js

In the first 3 lines, we are importing all dependencies of express and cors in our project. 

To import the requirements from models that we need, I am using CommonJS by Node, but we have another option which is ECMAScript Modules. You can learn more about the differences between them here.
https://blog.logrocket.com/commonjs-vs-es-modules-node-js/

The next lines are about telling the application that we want to allow external requisition from different domains, return results as JSON and our application is set to run on the 3333 port. 

To keep watching our application in real-time we are going to add one more dependency, Nodemon that is going to monitor our application. Every time we change the code inside, Nodemon will update our application so we don’t have to update the application every time we change something on the code.

Let’s run the API for the first time.

If you get a similar message to this, you are on the right path.

Creating Controllers 

A controller is a pattern for MVC applications that control the logic flow. It is responsible for receiving HTTP requests and giving a response back to the user. Let’s create a folder called src that will be our root for MVC. Inside this folder, create another folder called Controllers. Since the controller’s folder is created, let’s create a controller file. 

UserController.js

What we did here was to create a response body for each type of HTTP method request, to be able to give our application a response. Now let’s create our route for this controller. 

Routing

Routing defines the way in which the client requests are handled by the application endpoints. Basically, we are linking HTTP methods endpoints with their controller methods.

Inside the src folder, create a new folder, Routes.  

Inside the routes folder, create the new following files.

UserRoute.js

index.js

Now that we have all requirements configured, let’s get back to the server.js file and change only one line inside of it to point to the new route we created. 

server.js

Using Postman or Insomnia will make it easier to make calls to our new API (highly recommended). 

This is how our structure looks after all code creation.

Calling our API 

Using localhost and port 3333 we can reach our API. 

GET BY ID – Getting user by Identifier 1

GET  – Getting all users

PUT – Updating user with Identifier 1

POST – Creating user

DELETE – Deleting user with Identifier 1

Now that you have all the routes configured, you can enrich your application and give it a reason to exist. 

Thank you for reading! See you next time!

About

Hey! I’m André and I’ve been working as a software developer for just over 10 years. Here at Softensity, in addition to using Java, my specialization, I have had the opportunity to learn a little more about other languages. In addition, I am currently a Java community leader, but I have also ventured to learn more about the world of NodeJS. Thinking a little outside the box :).
Very happy to be able to contribute to this blog and also to be part of this Softensity family for more than one year.

BACK TO MAIN PAGE

Let’s Talk