Node.js REST API

Learn via video courses
Topics Covered

Overview

APIs are the backbone of modern web applications which enable different applications to communicate with each other. Developers today use APIs provided by various other companies in their applications. This helps them build applications quickly and also reduces the burden of maintenance since these publicly available APIs are usually secure and very well tested. There are APIs available for user authentication, payment gateways, maps, emails, social media profiles, and almost anything you can think of. In this article, we’ll learn about REST APIs and dive deep into the world of Node.js REST APIs.

What is an API?

When you’re using scrolling through Instagram on your phone, the app sends some requests to its server. Their server receives the request, processes it, and returns a response to your phone. The app on your phone processes the response and presents it to you in a readable manner. Here, the app on your phone talks to Instagram’s servers via what we call Application Programming Interface or APIs.

Let’s take another example to understand APIs. You must have heard of UPI payments and apps like GPay, PhonePe, and Paytm which allow you to do transactions via UPI. The UPI payment system is managed by NPCI or National Payments Corporation of India which exposes its APIs so that these payment apps can use them and facilitate UPI transactions to their customers. Simply put, an API is a way for two or more software systems to communicate with each other.

The application sending the request is commonly referred to as a client and the application sending the response is called the server. So, in the above example, the app on your device is the client which requests data from Instagram’s servers.

The way an API works is that the client sends some request to the server at a particular endpoint, with some payload using one of the HTTP methods; the server processes the request and returns a response which can be in HTML, XML, JSON, etc. REST API ARCHITECTURE

What is REST API?

There are various API architectures which define the rules for API calls namely SOAP, RPC and REST. Out of these, REST is the most popular choice for building APIs

REST stands for Representational State Transfer and was introduced by Roy Fielding in the year 2000

REST is not a protocol or a standard but a set of design principles based on HTTP or Hypertext Transfer Protocol

Any API that complies with the principles of the REST architectural style and allows interaction with RESTful systems is called REST API

Principles of REST

For an API to be called RESTful, it should align with the following six design principles:

1. Client Server Decoupling

REST enforces that the client and the server should be independent of each other. The client should only have information regarding the URI of the resource and the client should not interact with the server in any other way. Similarly, the server should not interact with the client in any way other than sending the requested data.

2. Stateless

REST APIs are stateless which means that each request from the client to the server must contain all the information needed to process the request. The server applications are not allowed to store any information related to client requests.

3. Uniform Interface

All the resources and actions available at specific endpoints should be decided and obeyed by both the client and the server. Also, all the API requests for accessing a particular resource should look the same irrespective of the client sending the request. The response shouldn't be very long, but it must provide all the details the client would require.

4. Cacheable

Caching is a method of temporarily storing frequently used data in local memory so that the data will be served from local memory instead of being retrieved from the server when the client asks for the same information. This principle enforces that information regarding whether caching is permitted for the provided resource should be included in the server response.

5. Layered System Architecture

REST APIs should be designed in a way that prevents the client from being able to determine whether it is communicating with the end server or an intermediary server. This architecture improves system scalability by allowing load balancing and shared caches.

6. Code on Demand

This is an optional constraint and it states that, instead of a JSON or XML response, an API response can also contain executable code in the form of applets or scripts. Thus, the server can provide some parts of features to the client in the form of code and the client only needs to execute the code.

Why REST?

The decoupling between client and server is the most important advantage of using REST APIs. This decoupling allows the client and server-side systems to evolve independently and increases the development velocity.

The decoupling also helps developers to extend their functionality without much difficulty making them more scalable.

REST APIs are flexible. They can handle a wide variety of requests and transfer data in various formats like HTML, XML, YAML, and JSON. REST APIs are language and platform agnostic which means that they can be integrated with any client irrespective of the language and platform that the API is written in.

With RESTf APIs, we can use HTTP cache and proxy server to manage high load and thus improve performance.

REST is very easy to learn and use.

Creating a Secure REST API in Node.js

Let’s create our own Node.js REST API for better understanding. For this particular use case, we will serve dummy data from a JSON file to imitate a database. We’ll also be using Postman to test our Node.js REST APIs.

Step 1: Initialize npm and Initial Setup

Create a new directory api-demo, traverse to that directory, and initialize npm in that directory using npm init

  • -y here stands for "yes to all" and will select the default values for all the fields that npm needs for initialization.
  • As we’re already aware, Node.js is just a runtime environment that allows developers to run Javascript on the server. So, for performing other common web development tasks, we need to use web frameworks.
  • Express is one such commonly used Node.js web framework built on top of Node.js which provides the common set of utilities for building servers and web applications in general. It also makes writing handlers for Node.js REST APIs very easy and fairly straightforward.
  • Since we’re not using an actual database here, but creating a JSON file which will act as our database, we’ll need a Node.js module named fs (short for filesystem) that’ll help us read and write to files on our system.

Let’s go ahead and install express and fs in our project

Step 2: Create a Dummy Database

Create a file named users.json as shown below. Here, we have a JSON object with five key-value pairs where each key is a random ID assigned to each user while the value is an object containing the user properties. This file will act as a database for our Node.js REST API.

Step 3: Creating app.js File and Setting up the Server

Create a file named app.js - this will be the main file for our project where we’ll define all the HTTP methods for our Node.js REST API and setup the backend server.

Step 4: Fetching Data of All Users Using the GET method

When using Express, the usual syntax for making HTTP requests looks something as shown below:

Here, req and res stand for the request and response objects respectively. So, to retrieve data of all the users, we can write a GET request as shown below:

When we make the request using Postman, as expected, we get the data of all the users in the response.

REST API POSTMAN

Step 5: Fetching Data of a User Using their ID as a Route Parameter

In this case, we’ll get the ID of the user from the route and send only that user’s data in the response. So, here's what the GET method in our Node.js REST API would look like:

Sample request in Postman: SAMPLE REQUEST POSTMAN

Step 6: Creating a New User With the POST Method

To create a new user in our database, we need to make a POST call with the user’s data. Also, note that since we’re creating a database of our own, we have to explicitly add the logic for getting the subsequent user id. If you’re using something like MongoDB, it'll automatically assigns IDs to all the database entries.

For testing the POST API, make sure to add the user details in the request body. To add user data, go to the Body section, select raw data, select JSON as the data type, and add the JSON object in the textbox as shown below: REST API REQUEST POSTMAN

Step 7: Updating the First Name and Age of a User Using the PATCH Method

To update some properties of a user, we can use the PATCH method, pass the user ID in the route param, and the properties to be updated in the request body. All the other user properties would remain the same. The following is an illustration of PATCH method in our Node.js REST API:

Sample request in Postman: PATCH REQUEST POSTMAN

Step 8: Overwriting a User's Data Using the PUT Method

To overwrite all the details of a user, we can use the PUT method. It will replace the current properties of the user with the properties passed in the request body.

Sample request in Postman: DATA USING PUT

Step 9: Deleting a User Using the DELETE Method

To delete a user with a particular ID, we can use the HTTP DELETE method in our Node.js REST API.

Sample request in Postman: DELETE REQUEST POSTMAN

With this, we've finished writing our Node.js REST API with basic Create, Read, Update and Delete or CRUD functionality.

REST API Best Practices

Send Request and Response in JSON

Since JSON is supported by most programming languages and can be read easily, it should be the go-to choice for sending and receiving data instead of XML or YAML.

Use nouns instead of verbs in REST API endpoints

Use https://example-site.com/users instead of https://example-site.com/getUsers since HTTP methods like GET, POST, etc are already verbs.

Use plural nouns in API endpoints to denote a collection name

Use /users/abc instead of /user/abc to make it evident that abc is a route parameter and there can be more users.

REST API response must always have an HTTP status code

You should always return an HTTP status code to let the client know the status of their request and in case the clients want to do some processing at their end.

API endpoints should have nesting to show relationships

Using an endpoint like users/userId/profile makes it easier to understand that we’re requesting the profile of a particular user.

API endpoints should have filtering, sorting, and pagination in case the database is very large

Having an endpoint like /posts?tags=nodejs makes it easier for the client to retrieve only posts with the 'nodejs' tag instead of retrieving all the posts and then filtering them at the client's end.

API domain should Always Use SSL

Secure Socket Layer or SSL offers enhanced security which is critical for REST APIs. So, your URL should start with HTTPS instead of HTTP.

Make the API Version Evident in the Endpoint

REST APIs should specify their version in the endpoint itself so that new versions do not affect the current systems. For example, having a URL like https://example-site.com/users/v1 makes it clear that we’re using version 1 of the API.

API documentation must be easy to read and should have all the information that may be needed

API documentation is the instruction manual for any developer who wants to use your APIs in their service. You must make sure that the documentation is easy to understand and has all the information about the request and response objects. You can use tools like Swagger, Stoplight, ReadMe, etc. to write excellent API documentation and help your users. GitHub and Stripe's API documentation are examples of simple and easy-to-understand documentation.

Conclusion

  • APIs facilitate communication between two web applications
  • The application that sends the request is called a client, and the application that sends the response is known as a server.
  • APIs built using the REST design principles are called REST APIs
  • JSON is the most popular format for sending and receiving data using Node.js REST APIs
  • The main advantage of REST APIs is the separation of client and server which makes them more scalable and flexible
  • REST APIs are faster and lightweight when compared to other standards like SOAP and RPC
  • Express is the commonly used framework for Node.js REST APIs
  • Postman is a popular tool for developers to build and test their APIs.