a magnifying glass searching for something on the laptop keyboard

Build a No-Nonsense Search API with Express

A few months ago I used Node.js and Express to build Recite, a free to use REST API that returns quotes from popular novels. Just hit this API route and you get a random quote before you.

But in this post, let’s see how we can build a search API with Express JS which can return relevant quotes that matches our search query.

Scenario

On our MongoDB database, there’s a collection called “Quotes”, which has a bunch of quotes from popular books containing a the quote itself, the name of the book and the author, length of the quote, and no. of words.

{
_id: string,
// the actual quote from the book
quote: string,
// name of the book
book: string,
// name of the author
author: string,
// length of the quote
length: number,
// total words in the quote
words: number,
// date and time of first published
createdAt: string,
// date and time of update (if any)
updatedAt: string
}

When a user searches a query, relevant quote(s) should display that are the best results for that particular query.

Here’s how we can do it.

Steps

1. Create an Express app

npm init -y

This will create a bare minimum Node.js project by taking “yes” as a default answer to any of the questions asked while creating the project.

To install Express, 

npm install express

2. Create the Server

Create an index.js file on the root directory, then copy and paste the code below:

const express = require("express");
const connectDb = require("./utils/connectDb"); // database connection file

const app = express();

connectDb();

app.use(express.json());

app.use("/api", quoteRoute);

const port = 6001;

app.listen(port, () => {
console.log(`listening on http://localhost:${port} `);
});

You can setup the connection of your MongoDB server using this guide.

3. Create a route

We need to hit an API route to get the relevant quotes. Here we can define that route.

const router = express.Router();

router.get("/quotes/search", searchQuotes);

In the next step, we will create the searchQuotes controller function.

4. Create Search controller function

This is the main function that will actually search and fetch the relevant quotes from the database.

const searchQuotes = async (req, res) => {
try {
const { query } = req.query;

if (!query) {
return res
.status(400)
.send({ success: false, message: "Please provide a search query." });
}

const quotes = await QuoteModel.find({
$or: [
{ quote: { $regex: query, $options: "i" } },
{ author: { $regex: query, $options: "i" } },
{ book: { $regex: query, $options: "i" } },
],
});

if (quotes.length > 0) {
res.status(200).json({
success: true,
query: query,
total: quotes.length,
data: quotes,
});
} else {
res.status(200).json({
success: true,
message: "No result found",
});
}
} catch (error) {
console.error(error);
}
};

In the above code, 

  • First, I am taking out the query from the API URL.
const { query } = req.query;
  • If a query is not specified it the API request, I am returning an error message instructing the user to provide a search query.
if (!query) {
return res
.status(400)
.send({ success: false, message: "Please provide a search query." });
}
  • I am finding the relevant quotes from the QuoteModel schema that I have defined in my project to store quotes. 
  • Then I am applying a logical OR condition and finding if the relevant query string exists in any of the three fields (quote, author, and book) using regular expression and setting it as case-insensitive.
const quotes = await QuoteModel.find({
$or: [
{ quote: { $regex: query, $options: "i" } },
{ author: { $regex: query, $options: "i" } },
{ book: { $regex: query, $options: "i" } },
],
});
  • If there is at least one relevant quote, I am returning it in the response in the form of an array of quote objects.
  • If NOT, I am returning “No result found”.
if (quotes.length > 0) {
res.status(200).json({
success: true,
query: query,
total: quotes.length,
data: quotes,
});
} else {
res.status(200).json({
success: true,
message: "No result found",
});

5. Test it!

Open Postman or any other API testing tool to test your new API route!

I am going to type the URL below and search for a query in my MongoDB collection.

http://localhost:6001/api/quotes/search?query=harper

When I hit this API request, this is the response that I receive on Postman.

I get 2 quotes that matches “harper” and in this case, it comes in the author’s key.

What if I don’t enter a query?

I get a bad request (400 error) response saying, “Please provide a search query.”

Conclusion

This is how you can create a simple search API using Node.js and Express js. 

Contact me on X (Twitter) or LinkedIn to ask me any question about this.


Try Recite in your project.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top