React30-Project 6: Building a Quote Generation API with Express.js

Saurabh Mhatre
4 min readNov 5, 2023
Title image

Introduction

In this tutorial, we’ll create a backend API for generating quotes using Express.js. We’ll start by using local JSON data, and later replace it with data from a MongoDB database.

Building API explanation with Express for a beginners:

Imagine you’re running a toy store.

1. Setting Up Your Store (Initializing Express):
 — First, you need a place where your store will be. That’s like creating your store in a new town (server). So, you tell the town, "Hey, I’m going to have a toy store here!"

const express = require('express');
const app = express();
const port = 3000;

2. Toy Catalog (Creating API Endpoints):
 — Now, you decide what toys you want to sell and create a catalog (API endpoints). You say, "I’ll have a shelf for dolls, a shelf for cars, and a shelf for teddy bears."

 // Dolls shelf
app.get('/dolls', (req, res) => {
res.send('Here are the dolls!');
});
// Cars shelf
app.get('/cars', (req, res) => {
res.send('Check out the toy cars!');
});
// Teddy bears shelf
app.get('/teddy-bears', (req, res) => {
res.send('Snuggle with our teddy bears!');
});

3. Opening Your Store (Starting the Server):
 — Now that everything is set up, you open your toy store (start the server) so that people in the town can visit and buy toys.

app.listen(port, () => {
console.log(`Toy store is open on port ${port}!`);
});

That’s how your toy store (Express API) works.

Now let’s get back to building our project:

Step 1: Set Up Express.js

First, we’ll set up a new Express.js project. Open your terminal, create a new folder quotes-api and run the following commands within the folder:

npm init
touch index.js
npm install express --save
npm install -g nodemon

This command will create a new Express.js project with the necessary files and dependencies.
Next create a `quotesSource.json` file in the project folder and data in the from below link:-
Github-QuotesSource

Step 2: Setting up routes

Open index.js file and add below code to setup basic route for return random API:

const express = require('express');
const app = express();
const quotesJSONArray = require('./quotesSource.json');
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!')
});

app.get('/quotesList',(req, res) => {
res.send({ 'quotesList': quotesJSONArray });
});

app.get('/randomQuote',(req, res)=>{
const randomNumber = Math.floor(Math.random() * 21);
const quoteItem = quotesJSONArray[randomNumber];
res.send(quoteItem);
});

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

Start the server by running below command in terminal:

nodemon index.js

Now if you open the browser and open address localhost:3000/randomQuote you should see random quote returned by server as shown below:

QuotesAPI

Step 3: Connect to MongoDB

  1. Create a MongoDB Atlas account if you haven’t already on below website:
    MongoDB Atlas
  2. Create a new cluster and follow the setup instructions provided by MongoDB Atlas.

Step 4: Install Mongoose

In your terminal, run the following command to install Mongoose and other required packages, a MongoDB ORM for Node.js:

npm install mongoose body-parser dotenv cors --save

Step 5: Connect to MongoDB Atlas

Edit the index.js file to connect to your MongoDB Atlas database:

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors')
const quotesJSONArray = require('./quotesSource.json');
const port = 3000;
require('dotenv').config()

// mongodb connection
mongoose.connect(process.env.DB_CONNECTION_URL, { useNewUrlParser: true }, (err) => {
if(err) {
console.error(err);
} else {
console.log("connected");
}
});

// allow localhost access in frontend
app.use(cors())

// routes for quotes
const quotesRoute = require('./routes/quotes');
app.use(bodyParser.json());
app.use('/quotes', quotesRoute);
app.get('/', (req, res) => {
res.send('Hello World!')
});

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

Create a .env file in your quotes-api folder and add variable `DB_CONNECTION_URL` with value of mongoDB Atlas connection URL.

Step 6: Create a Quote Model

Create a folder named models in the quote-api folder, and inside it, create a file named Quotes.js with the following content:

const mongoose = require('mongoose');

const QuotesSchema = mongoose.Schema({
'quotes': {
type: Array,
required: true
},
})

module.exports = mongoose.model('Quotes', QuotesSchema, "Quotes")

Step 7: Create Quotes routes

Create a folder named routes in the quote-api folder, and inside it, create a file named quotes.js with the following content

const express = require('express');
const router = express.Router();
const Quotes = require('../models/Quotes');

router.post('/add', async (req, res) => {
const quotesObject = new Quotes({
'quotes': req.body.quotes
});
try {
quotesObject.save((err, response) => {
if (err) {
console.log("error", error);
} else {
console.log("saved", response);
}
});
} catch (err) {
console.log(err.message);
res.status(500).send("Error in Saving");
}
res.status(200).json({
"response": "success"
});
});

router.get('/list', async (req, res) => {
const quotesObject = await Quotes.find({});
res.json({'result':quotesObject[0].quotes});
});

router.get('/random', async (req, res) => {
const randomNumber = Math.floor(Math.random() * 21);
const quotesObject = await Quotes.find({});
const quoteItem = quotesObject[0].quotes[randomNumber];
res.send(quoteItem);
});

module.exports = router;

You can either populate the Quotes database directly in MongoDB atlas dashboard with random quotes array or use /add API created above to add the array in database using values from quotesSource.json file added earlier.
Github-QuotesSource

Step 8: Test the API

Restart the server (nodemon index.js) and test the API with Postman or a web browser by visiting localhost:3000/quotes/random.

Github source code:
Github-QuotesGenerationBackend
Note: MongoDB connection details are indexTest.js file in above repo.

Youtube tutorial for first part:

VIdeo tutorial

Conclusion

Congratulations! You’ve successfully built a backend API for quote generation using Express.js and connected it to a MongoDB database hosted on MongoDB Atlas. Have a nice day ahead!

You can find more content on my Youtube channel below:
SaurabhNative-Youtube

Check out project 7 in the series below:-

React30-Part7

--

--