Open In App

How to Implement Search and Filtering in a REST API with Node.js and Express.js ?

Last Updated : 10 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Search and filtering are very basic features that an API must possess to serve data to the client application efficiently. By handling these operations on the server-side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance.

In this article, we’ll see how we can build a Node.js REST API that can accept these query strings, filter a list of users based on these provided parameters, and then return the matching results.

Approach

An extremely popular way of implementing this is with the help of query strings. A query string is a part of the URL that allows us to pass data from client to server and vice-versa in the form of parameters and their values.

Syntax:

http://test.com?name=John&age=21

Here, the portion following the question mark (?) is the query string. These are basically key-value pairs that we can use for various purposes.

Then we will filter user data based on query parameters received in the request. We can iterate through the dataset, check if each user matches the specified filters, and return the filtered results as the response.

Also, to build powerful APIs that work seamlessly with modern frontends like React, the Full Stack Development with Node JS course covers API development in Node.js and Express.js with advanced features.

Setting up the Project

First, we’ve to initialize a new project using Node Package Manager. We can complete the setup by selecting all the default options. 

npm init


Next, we’ve to install the express package.

npm install express --save


The entry point of this application is going to be the app.js file. All of our business logic will go here. The REST API will contain only a single route which will return a list of users, with support for searching and filtering using query strings.

Example: Initially, the app.js file will look something like this, with the route returning only a basic message.

JavaScript
// Filename - app.js

const express = require('express');
const data = require('./data');

// Initialize App
const app = express();

// Assign route
app.use('/', (req, res, next) => {
  res.send('Node.js Search and Filter');
});

// Start server on PORT 5000
app.listen(5000, () => {
  console.log('Server started!');
});

Adding Mock Data: For carrying out searching and filtering, we need some mock data i.e. a list of users upon which we can carry out these operations. For this, we can create a separate file data.js

JavaScript
// Filename - data.js

const data = [
  { id: 1, name: 'Alan Wake', age: 21, city: 'New York' },
  { id: 2, name: 'Steve Rogers', age: 106, city: 'Chicago' },
  { id: 3, name: 'Tom Hanks', age: 47, city: 'Detroit' },
  { id: 4, name: 'Ryan Burns', age: 16, city: 'New York' },
  { id: 5, name: 'Jack Ryan', age: 31, city: 'New York' },
  { id: 6, name: 'Clark Kent', age: 34, city: 'Metropolis' },
  { id: 7, name: 'Bruce Wayne', age: 21, city: 'Gotham' },
  { id: 8, name: 'Tim Drake', age: 21, city: 'Gotham' },
  { id: 9, name: 'Jimmy Olsen', age: 21, city: 'Metropolis' },
  { id: 10, name: 'Ryan Burns', age: 21, city: 'New York' },
];

module.exports = data;

Working with the Query String:

  • Let’s consider this URL. Here, we want to fetch all the users who live in Metropolis and are 21 years old.
    http://localhost:5000?city=Metropolis&age=21
  • We can access the query string by using the query attribute of res object
    console.log(res.query)
    >> { city: 'Metropolis', age: '21' }

We can see that it contains all the parameters passed through the URL in form of key-value pairs. To apply these parameters on our list of users, we can use the Array.filter() method and check for each user, if it satisfies all the provided parameters, and if it does, then add it to the filteredUsers list. 

The filteredUsers list is our final result and can be returned as the response. The final code is provided below

JavaScript
// Filename - App.js

const express = require('express');
const data = require('./data');

// Initialize App
const app = express();

// Assign route
app.use('/', (req, res, next) => {
    const filters = req.query;
    const filteredUsers = data.filter(user => {
        let isValid = true;
        for (key in filters) {
            console.log(key, user[key], filters[key]);
            isValid = isValid && user[key] == filters[key];
        }
        return isValid;
    });
    res.send(filteredUsers);
});

// Start server on PORT 5000
app.listen(5000, () => {
    console.log('Server started!');
});

Example 1: URL to Fetch the user whose id is 2

http://localhost:5000?id=2

Output:

[
{
"id": 2,
"name": "Steve Rogers",
"age": 106,
"city": "Chicago"
}
]


Example 2: URL to Fetch all users who live in Metropolis


http://localhost:5000?city=Metropolis

Output:


[
{
"id": 6,
"name": "Clark Kent",
"age": 34,
"city": "Metropolis"
},
{
"id": 9,
"name": "Jimmy Olsen",
"age": 21,
"city": "Metropolis"
}
]

Example 3: URL to Fetch all users who live in Metropolis and are 21 years old

http://localhost:5000?city=Metropolis&age=21

Output

[
{
"id": 9,
"name": "Jimmy Olsen",
"age": 21,
"city": "Metropolis"
}
]

Summary

We can easy implement search and filter in REST API using node and express with the help to query string in the url. By handling query parameters and applying conditions to your database queries, you can create a flexible and powerful search and filtering system.




Previous Article
Next Article

Similar Reads

Creating a REST API Backend using Node.js, Express and Postgres
Creating a REST API backend with Node.js, Express, and PostgreSQL offers a powerful, scalable solution for server-side development. It enables efficient data management and seamless integration with modern web applications. This backend can do Query operations on the PostgreSQL database and provide the status or data on the REST API. Installation R
4 min read
Node.js Building simple REST API in express
Let's have a brief introduction about the Express framework before starting the code section:Express: It is an open-source NodeJs web application framework designed to develop websites, web applications, and APIs in a pretty easier way. Express helps us to handle different HTTP requests at specific routes.As it is NodeJs web framework so make sure
2 min read
How to generate document with Node.js or Express.js REST API?
Generating documents with Node and Express REST API is an important feature in the application development which is helpful in many use cases. In this article, we will discuss two approaches to generating documents with Node.js or Express.js REST API. Table of Content Document Generation using PdfKit libraryDocument Generation using Puppeteer libra
3 min read
Filtering MongoDB Documents by ID in Node.js with Express.js
Filtering is a very basic feature that an API must possess to serve data to the client application efficiently. By handling these operations on the server side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance. In this article, we are going to learn how to filter data from Mong
3 min read
Build a document generator with Express using REST API
In the digital age, the need for dynamic and automated document generation has become increasingly prevalent. Whether you're creating reports, invoices, or any other type of document, having a reliable system in place can streamline your workflow. In this article, we'll explore how to build a Document Generator using Node and Express, two powerful
2 min read
REST API using the Express to perform CRUD (Create, Read, Update, Delete)
In this article, we are going to learn how can we build an API and how can we perform crud operations on that. This will be only backend code and you must know JavaScript, NodeJs, Express.js, and JSON before starting out this. This Node.js server code sets up a RESTful API for managing student data. It provides endpoints for performing CRUD (Create
9 min read
Difference Between REST API and RPC API
REST and RPC are design architectures widely used in web development to build APIs (Application Programming Interface). It is a set of instructions that permits two systems to share resources and services. The client creates a request to the server that responds to it with data in JSON or XML format. REST APIs It stands for Representational State T
3 min read
Know the Difference Between REST API and RESTful API
APIs (Application Programming Interface) act as an interface between two applications to interact and provide the relevant data. It uses a set of protocols using which the operation is done. Salesforce was the first organization to officially launch API, followed by eBay and Amazon. Also, 60% of transactions made on eBay use their APIs. If we talk
5 min read
Difference between REST API and SOAP API
REST (Representational State Transfer) and SOAP (Simple Object Access Protocol) are the most common methods for communications These services enable web to communicate with the servers with HTTP protocol. REST is architectural style that works over HTTP for communication while SOAP is a protocol with strict standards and is helpful for complex syst
2 min read
Build a Social Media REST API Using Node.js: A Complete Guide
Developers build an API(Application Programming Interface) that allows other systems to interact with their Application’s functionalities and data. In simple words, API is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data and interact with each other.API is a service created
15+ min read
What is REST API in Node.js ?
REST (Representational State Transfer) is an architectural style for designing networked applications. A RESTful API is an API that adheres to the principles of REST, making it easy to interact with and understand. In this article, we'll explore what REST API is in the context of Node.js, its principles, and how to create one. Table of Content Unde
11 min read
RESTful Blogging API with Node and Express.js
Blogs Websites have become very popular nowadays for sharing your thoughts among the users over internet. In this article, you will be guided through creating a Restful API for the Blogging website with the help of Node, Express, and MongoDB. Prerequisites:Node JS & NPMExpress JSMongoDBApproach to Creating Restful Blogging App:To create a Restf
6 min read
How to Build a RESTful API Using Node, Express, and MongoDB ?
This article guides developers through the process of creating a RESTful API using Node.js, Express.js, and MongoDB. It covers setting up the environment, defining routes, implementing CRUD operations, and integrating with MongoDB for data storage, providing a comprehensive introduction to building scalable and efficient APIs. Prerequisites:NodeJS
6 min read
How to Resolve form-data is getting undefined in Node/Express API ?
Working with forms and handling data submissions is a basic requirement in web development. When using Node and Express for building APIs, you might get an error that the FormData object is undefined. In this article, we'll explore how to resolve form data getting undefined in a Node/Express API. The FormData object is a part of the Web API and is
3 min read
Travel Planning App API using Node & Express.js
In this article, we’ll walk through the step-by-step process of creating a Travel Planning App With Node and ExpressJS. This application will provide users with the ability to plan their trips by searching for destinations, booking flights and hotels, submitting reviews, receiving notifications, sharing their trips on social media, and processing p
10 min read
How to Call an API Continuously from Server Side Itself in Node.js/Express.js ?
To call an API continuously from the server side in a Node.js/Express.js environment, you can implement a periodic task that executes at regular intervals. This is typically done using functions such as setInterval, which is built into Node.js for scheduling repeated operations. There are multiple ways to make API calls from a Node.js server, depen
3 min read
How to use TypeScript to build Node.js API with Express ?
TypeScript is a powerful version of JavaScript that incorporates static typing and other features, making it easy to build and maintain large applications. Combined with Node.js and Express, TypeScript can enhance your development experience by providing better type safety and tools. This guide will walk you through the Node.js API using Express an
4 min read
How to Make a search function using Node Express and MYSQL
In this article, we will learn how to create a search function using Node with Express framework to search terms inside MYSQL tables. Prerequisites:MySQLNode JSExpress JSWe will discuss the following methods to search: Table of Content Searching term with partial matchSearching term with exact matchingSearching term in multiple columnsApproach to m
5 min read
Building a REST API with PHP and MySQL
This brief tutorial is a step-by-step guide on how to develop a REST API using PHP and MySQL. REST API will implement HTTP commands (Get, Post, Put, DELETE) and response will be in form of JSON. For development setup, we will be using the XAMPP while for testing of the API, we will use the Postman app. Steps to Build REST API with PHP and MySQLStep
4 min read
How to create a REST API using Java Spring Boot
Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems
6 min read
REST API in Hyperledger
REST, or Representational State Transfer, is an architectural style for building web services. It is based on a set of principles that define how web resources should be defined, accessed, and manipulated. One of the key principles of REST is the use of the HTTP protocol for communication between clients and servers. This means that REST APIs are b
7 min read
How to create Covid19 Country wise status project using REST API ?
Today, All Countries in the world fighting with Coronavirus. Every day, Coronavirus cases rising rapidly. It is important for all to keep track of COVID Cases daily and should try to keep himself/herself safe. We have made small web apps that will tell you the total no of cases, new cases, new death, recovery, etc. to the user. You have to just ent
7 min read
Best Coding Practices For Rest API Design
JSON, Endpoints, Postman, CRUD, Curl, HTTP, Status Code, Request, Response, Authentication, All these words are familiar to you if you are in backend development and you have worked on API (Application Programming Interface). Being a developer you might have worked on some kind of APIs (especially those who are experienced developers). Maybe a paym
10 min read
Why REST API is Important to Learn?
API... Being a developer what comes to your mind first when you listen to this word... JSON, Endpoints, Postman, CRUD, Curl, HTTP, Status Code, Request, Response, Authentication, or something else... If you're familiar with the above word then surely you might have worked on some kinds of APIs (especially those who are experienced developers) in yo
8 min read
Consuming a Rest API with Axios in Vue.js
Many times when building an application for the web that you may want to consume and display data from an API in VueJS using JavaScript fetch API, Vue resource, jquery ajax API, but a very popular and most recommended approach is to use Axios, a promise-based HTTP client. Axios is a great HTTP client library. Similar to JavaScript fetch API, it use
2 min read
How to Create A REST API With JSON Server ?
Setting up a RESTful API using JSON Server, a lightweight and easy-to-use tool for quickly prototyping and mocking APIs. JSON Server allows you to create a fully functional REST API with CRUD operations (Create, Read, Update, Delete) using a simple JSON file as a data source. Table of Content GET Request Returns a List of all UsersPOST Request to c
4 min read
REST API Introduction
REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP) technology bec
5 min read
HTTP REST API Calls in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. We already know about the importance of HTTP REST
13 min read
Consuming a REST API ( Github Users ) using Fetch - React Client
In this article, you will learn to develop a React application, which will fetch the data from a REST API using Fetch. We will use GitHub Users API to fetch the user's public information with their username. You can find the API reference and source code links at the end of this article. Prerequisites:NodeJS or NPMReactJSSteps to Create the React A
3 min read
REST API Call to Get Location Details in Vue.js
In this article, we will know the REST API call to get the location details in VueJS, along with understanding its implementation through the examples. VueJS is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to design the user interface layer, it is easy to pick up for any developer. It is compatible with other libraries
7 min read
three90RightbarBannerImg