RestFulAPI in ExpressJS

Learn via video courses
Topics Covered

Overview

Imagine yourself in a library. The books inside the library serve as resources, while the library itself is like a server. Now, you require a librarian who serves as the API to interact with the books. The librarian adheres to specific guidelines and practices when using a RESTful API.

RESTful API is very popular and commonly used to create APIs for web-based applications. Express is a back-end web application framework of node.js, and with the help of ExpressJS, we can create an API very easily.

Introduction

Before we jump to the what and hows of RESTful API let's make sure you're familiar with the concept of API in the first place.

APIs encompass a collection of definitions and protocols that play a crucial role in application development and integration. They serve as the bridge between different software components, enabling seamless data exchange between an information provider (server) and a user.

APIs define the data and functionalities accessible to clients making requests to the producer, which in turn returns the appropriate responses.

By utilizing an API, programs can communicate, retrieve information, and execute specific functions. APIs empower users to interact with a system, enabling them to achieve their desired outcomes.

Just like a librarian, an API acts as a mediator between users (clients) and resources (servers)

Below are several reasons highlighting the importance of integrating APIs:

  • Simplifying Resource and Information Sharing: APIs facilitate the streamlined sharing of resources and information between different components or services.
  • Access Control and Authentication: APIs enable you to control and manage access rights, ensuring that only authorized users can interact with specific resources through proper authentication mechanisms.
  • Enhancing Safety and Control: By utilizing APIs, you can enforce security measures and maintain control over the data and functionality exposed, protecting against unauthorized access and ensuring data integrity.
  • Abstracting Software Specifics: APIs abstract away the underlying complexities of the software implementation, allowing users to interact with services without needing in-depth knowledge of their internal workings.
  • Enabling Consistent Communication: APIs provide a standardized communication interface, allowing different services or systems, even if they employ different technologies, to interact seamlessly and exchange data reliably.

Rset Ful API

What is REST API?

REST (Representational State Transfer) is a widely adopted architectural style employed for developing web services.

In the previous section APIs, we discovered that an API (Application Programming Interface) is a set of code that enables communication between two software applications.

Combining these concepts we can say that, a REST API is a software component that facilitates communication between two applications over the internet, enabling interaction across various devices. It acts as the accepted protocol for data exchange in online services.

REST API Basic

The REST API serves as the intermediary between you and the database when you, the client, send a request. It is comparable to using your browser to view a website, but instead of clicking buttons to request information from the server, you write code. The beautiful thing about APIs is that they are adaptable; they can handle a wide range of requests and work in a variety of contexts.

Images, movies, and text are examples of valuable resources in the realm of REST. As a result, when you access a certain URL and send a request to the server, you are effectively requesting it to provide you with the data you require.

Let's explore this more in-depth,

When you request by accessing a URL, it consists of four important components:

  1. The Endpoint: This is the URL structure that starts with the root endpoint followed by additional path elements.
  2. The Method: It chooses which of the five action types you wish to carry out on the server: GET, POST, PUT, PATCH, or DELETE.
  3. The Headers: These fulfil several functions, including authentication and providing details about the request body's contents. To include specified HTTP headers, use the -H or --header option.
  4. The Data or Body: With POST, PUT, PATCH, or DELETE requests, you can provide the server with this data by using the -d or --data option.

Crud Operation

Therefore, these elements come together when you send a request to the server to indicate what you need from it and how you wish to communicate with it.

  1. Using HTTP requests: You can conduct a variety of actions on the database
  2. POST request: You can add new resources or records to the database using this request type.
  3. GET Request: You can use this to read or retrieve a resource from the server, such as a document, an image, or a group of other resources.
  4. PUT and PATCH Requests: These are used to edit particular sections of a resource in the database or to update records that have already been created.
  5. DELETE Request: This enables you to remove a resource from the server, as the name implies.

These actions are commonly referred to as CRUD operations, which stands for Create, Read, Update, and Delete.

When the server responds to your requests, it sends the data back to you in one of the following formats, depending on the server configuration and the type of request made:

  • HTML
  • JSON
  • XLT
  • PHP
  • Python
  • plain text

So far, we've understood what and how's of RESTful API, it's time to explore the "why" part of it.

Why Use a REST API?

Why should you choose REST over other APIs like SOAP? There are several compelling reasons, including scalability, flexibility, portability, and independence.

  1. Freedom From Project Structure Limitations With REST APIs, developers are not tied to a specific project structure. They have the flexibility to work on different aspects independently without affecting other parts of the system. This adaptability allows for more efficient development and maintenance.
  2. Portability and Adaptability REST APIs enable seamless migration from one server to another without significant disruptions. They also provide the ability to update the database and make changes to the system as needed, ensuring adaptability to evolving requirements.
  3. Future Scalability REST's client-server architecture allows for rapid development of the product. The independent nature of client and server components enables scaling the project in the future by introducing new features, functionalities, and integrations without major dependencies or constraints. This scalability ensures that the system can grow and evolve with the changing needs of the business.

In conclusion, REST offers advantages for building modern and adaptable APIs. such as flexibility, portability, and scalability.

Rest API Principles

REST, coined by Roy Fielding in 2000, adheres to the principles and guidelines set by the REST architecture which is defined by six fundamental constraints that serve as guiding principles for designing robust solutions. These constraints are:

1. Client-server Separation

Imagine you're in a restaurant, and a waiter is taking an order from a customer. The waiter represents the server, and the customer represents the client. Similarly, in REST architecture, the server provides services to the client, but they are separate entities and do not rely on each other.

The REST architectural style takes a unique approach to implementing the client and server. They can operate independently without knowing each other.

For instance, the client only needs the Uniform Resource Identifier (URI) of the requested resource and communicates with the server exclusively through that. On the other hand, the server should not impact the client software. It sends the necessary data over HTTP.

What does this mean? It means you can modify the client code without affecting the server's operation, and vice versa. Both the client and server programs can remain modular and independent as long as they communicate using the agreed-upon message format.

By separating user interface concerns from data storage constraints, we achieve improved interface flexibility across different platforms and enhance scalability.

Moreover, each component benefits from this separation because it can evolve independently. A REST interface enables different clients to access the same REST endpoints, perform similar actions, and receive consistent responses.

2. Stateless

Imagine you walk into a shop to make a purchase, and the shopkeeper doesn't remember anything about your previous visits. Similarly, in REST architecture, the server doesn't retain any knowledge of previous requests made by the client. Each request contains all the necessary information to process it, just like placing an order for a pizza without the pizza maker recalling your previous orders.

REST-based systems adhere to the stateless constraint, which means that the server and client operate without knowledge of each other's state. This constraint allows the server and client to understand any incoming message, even if they have not encountered the previous ones.

To maintain this statelessness, resources are used instead of commands. Resources represent the nouns of the web and are used to describe any object that you want to store or communicate to other services.

This constraint offers several benefits, including RESTful API application stability, speed, and scalability. It allows you to control, modify, and reuse components without impacting the overall system.

It's important to note that each request should include all the necessary information for its completion. Client applications are responsible for managing the session state, as server applications do not store any data associated with a client request.

3. Cacheable

Imagine visiting a shop where the shopkeeper remembers the item you previously purchased and recommends something similar. Similarly, the server can store the response to a request and utilize it to expedite future requests. This concept is known as caching.

In REST architecture, one of the constraints is the ability to cache responses. This means that the server can store a copy of a response and serve it directly to the client without performing the same computation or data retrieval again. Caching improves performance and reduces the need for repeated network requests.

Just like the shopkeeper's memory of your previous purchase, caching allows for quicker access to resources, especially when multiple clients request the same information. By leveraging caching, RESTful systems can enhance efficiency and reduce the load on servers, resulting in improved scalability.

It's important to note that caching can be controlled using certain mechanisms and directives provided by the HTTP protocol, allowing clients and servers to determine when and for how long a response should be cached.

4. Layered System

Just like a multi-story building, a RESTful API can be structured with multiple layers, each serving a distinct purpose. Similar to how you can interact with the top floor of a building without needing to know about the floors below, the client can communicate with the top layer of the RESTful API without direct knowledge of the underlying layers

The RESTful architectural style incorporates a layered design structure, which is another important constraint. This design principle involves organizing the API into different layers, each with its specific responsibilities.

Each layer within the REST API has its defined role and follows a hierarchical order. For instance, one layer might be responsible for storing data on the server, the next layer for deploying APIs on a separate server, and another layer for authenticating requests on yet another server.

These layers act as intermediaries, mediating the communication between the client and server applications. Consequently, the client is unaware of which specific server or component it is interacting with.

What does it mean when each layer fulfils its function before passing the data to the next layer? It enhances the overall security and flexibility of the API. The modularity of the layered structure ensures that adding, modifying, or removing APIs within one layer does not impact other components of the interface. This promotes ease of maintenance and extensibility of the API architecture.

5. Uniform Interface

Imagine a restaurant menu with each dish's description and a picture, making it simple for all consumers to grasp what is being offered. Similarly to this, a RESTful API should offer a standardised interface that all clients may easily comprehend. This calls for using URLs to pinpoint specific resources and following accepted HTTP standards like GET, POST, PUT, and DELETE.

According to the uniform interface principle, all API requests for the same resource, from any source, should adhere to a common structure. This guarantees that the language being used to communicate with the API doesn't change. Each resource has a distinct unified resource identifier (URI) that can be used to access related data, like a user's name or email address

The fact that messages are self-descriptive is another facet of the uniform interface principle. API messages should include all the information required for the server to comprehend how to process the request. This contains information that aids the server in handling messages correctly, such as the type of request, mime types, and other pertinent metadata.

6. Code on Demand

Certain RESTful APIs offer the capability to provide executable code to the client, similar to a JavaScript function. This feature proves beneficial as it allows for the inclusion of additional functionality in the client without the need to incorporate it directly into the initial application.

Using Express and Its Architecture

Using Express and Its Architecture

The client submits a request via an HTTP request that takes the form of a JSON file and supports actions like PATCH, POST, and DELETE. The client sends the request to the server, which responds with a message telling the client how the request turned out.

To create an Express.js application, follow these steps:

Step 1: Open your editor and navigate to the desired project directory in the terminal. Run the following command to initialize a new project with a package.json file:

This command will create a JSON file with default settings, in this case, it is as follows,

Step 2: Install the Express.js dependency by running the following command:

This command will install the Express.js package and add it as a dependency in the package.json file.

Step 3: Create a new file named index.js and add the following code:

This app.listen will respond to the server to listen on a specific port which we have defined already as a variable 4000

Step 4: Then we will write a second argument as a callback to tell the API is working, now let's run this code to check if our API is working or node To run this code, we will write a command node.

Step 5: Open a web browser and navigate to http://localhost:4000/scalartopics to test the API. You should see the "youtube or website" response message displayed in the browser.

Congratulations! You have successfully set up a basic Express.js API.

Conclusion

  1. REST API is a software component that facilitates communication between two applications over the internet, enabling interaction across various devices. It serves as the established method for exchanging data in web services
  2. Just like a librarian, an API acts as a mediator between users (clients) and resources (servers)
  3. The client sends a request in the form of a JSON file using an HTTP request, which can include operations like PATCH, POST, and DELETE. The request is initially sent to the server, which then responds to the client with a message, in a particular format which depends on the server configuration and the type of request made, indicating the outcome of the request.