Simple Query Search in Node Express API
Tags: node, express, query, api
Published: 2021-11-16 08:42:07

REST API has become one of the most use protocol for building and integrating application software. It is most refer to as RESTful API which stands for REpresentational State Transfer Application Programming Interface.

My interest is to show how we can create a search query in a REST API. Let me take you on a ride 

###Installing Node
Launch your preferred IDE, am using <a href="https://code.visualstudio.com/download">VSCode</a>  in my case and enter the code to initiate a node package.
<code>npm init --y</code>
After a successful installation of node package, next we have to install the necessary dependencies. The code below installs our needed dependencies.
<code>npm i express</code>
<code>npm i nodemon --save-dev</code>
You might want to know why the nodemon has a different installation command, YES that's because we only need it just for development purpose but if our application is to be hosted it won't be needed as the keyword <code>node</code> will be used as a command to run our application.

We have successfully install node and the necessary dependencies that is need, lets dive to our main focus.

###Creating a Server
The first thing to do is to create a file that our codebase would will live. Get to the terminal and create a file named "<b>server.js</b>".
<code>touch server.js</code>
The file will be created at the explorer nav of your VSCode, all you need is to double click on it to open.

![server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qnhebl8roj24l4bav5n7.PNG)

We required our express library in our file so as to make use of its handle helper functions. Next we created a port on which our server will run on. Now that we have access to the express library an instantiation of it with a variable name "app" was declared to make usage appealing but note the variable name is self define which means you can make a declaration of your choice of name. 
An array of dummy/static data was created for the students containing their information then we created a default routed that throws a welcome message as respond to the user.

Finally, we used the instance of express declared as "app" to point to the <code>listen()</code> method to make sure that server is successfully up and running.

Let's run our server to make sure we are on the right track.
<code>npm start</code>
The above code was made possible because we edited the scripts in package.json file as follows: 
<code>
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
</code>

Next we have to request to the server using POSTMAN. Enter http://localhost:2021 in the url provided and make sure the method is set to <b>GET</b> then hit enter or click on the <b>send</b> button. Result is shown below.

![POSTMAN responds](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6p2cd94hk4mdpshchcix.PNG)

###Query Search
Now that we have our server and responds running, it is time to write our route for searching specific information.

<code>
app.get("/student", async (req, res) => {
  try{
    const userQuery = await req.query;
        const filteredStudent = await studentInformations.filter((info)=>{
            let isValid = true;
            for(key in userQuery) {
                isValid = isValid && info[key] === userQuery[key];
            }
            return isValid;
        });
        res.json({data: filteredStudent})
  }catch(err){
    res.send(err.message)
  }
});
</code>

Brief explanation of sample code: First we get the user request passed as a parameter on the url then filter the database objects based on key after which we loop through the database objects and check if any of the object key from the loop matches what is passed by the user in the url and finally every matched object is now filtered and returned as a responds to the user.

####Result
We want to show all student that took a "Frontend" course. This request would be sent <code>http://localhost:2021/student?course=Frontend</code>

![query search request](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/frthu2pnm61wdcx42h7f.PNG)

That's all.
Hope this helps you hit the like icon and comment for clarity if there is any.
You can get the complete source code from my GitHub repo <a href="https://www.github.com/callmefarad/Simple-Search-Query-In-Node-Rest-API">here</a>

Click on the follow button to always get my posts.