How To Create Random Quote Generator API In Node.js Express
Are you interested in creating API's using Node.js and Express? If yes, then you've come to the right place! In this post, we'll walk you through the steps to create a simple yet powerful quote generator API.
Prerequisites
Before we dive into the code, let's take a quick look at what we'll be using:
- Node.js - an open-source, cross-platform JavaScript runtime environment that allows developers to build fast and scalable network applications.
- Express - a popular framework for building web applications in Node.js.
- node-quotegen - a simple package that provides a collection of quotes that you can use to generate random quotes.
With these tools in hand, let's get started!
Step 1: Create a new Node.js project
To create a new Node.js project, open your terminal and run the following command:
mkdir quote-generator-api
cd quote-generator-api
npm init -y
Step 2: Install Express and node-quotegen
Next, let's install the required packages using the following command:
npm install express node-quotegen
Step 3: Create the quote generator API
Create a new file called app.js
and add the following code:
const express = require("express");
const { getQuote } = require("node-quotegen");
const app = express();
// Define a GET route to generate random quote
app.get("/api/quote", (req, res) => {
const quote = getQuote();
res.json({ quote });
});
// Define a GET route to generate quote from a specific category
app.get("/api/quote/:category", (req, res) => {
const quote = getQuote(req.params.category);
res.json({ quote });
});
// Start the server
app.listen(3000, () => {
console.log("Server listening on port 3000");
});
Let's take a look at what's going on here:
First, we import the required modules - Express
and node-quotegen
.
We create a new Express app and define two routes:
- A
GET
route that generates a random quote usinggetQuote()
function and sends it back as a JSON response. - A
GET
route that generates a quote from a specific category using thegetQuote()
function and sends it back as a JSON response.
Finally, we start the server and listen on port 3000.
Step 4: Test the API
To test the API, run the following command in your terminal:
node app.js
This will start the server, and you should see the message "Server listening on port 3000".
Next, open your web browser and navigate to http://localhost:3000/api/quote. You should see a JSON response with a random quote.
To generate a quote from a specific category, navigate to http://localhost:3000/api/quote/motivational (replace "motivational" with any other category). You should see a JSON response with a quote from that category.
And that's it! You've successfully created a random quote generator API using Node.js and Express. You can now use this API to generate quotes for your web or mobile applications.
Top comments (0)