Quote API Challenge Project (JavaScript)

I loved your solution. I was stuck and it helped me a lot. :smiley: Thanks for sharing.

Quotes API Project

Hey Codecademy Community!

I’m thrilled to present my project,This project was an exciting journey into web development, focusing on server-side programming with Express.js.

Project Features:

  • Fetch random quotes
  • Retrieve all quotes or by author
  • Add new quotes to the database
  • Delete quotes from the database

Explore the Project:

I’d love to hear your feedback, suggestions, and if you’re interested, contributions are welcome! Let’s discuss ways to enhance this tool and make it even more useful for our community.

// Import the Express library to create a server
const express = require('express');
// Initialize the Express application
const app = express();

// Import quotes array and utility functions from local modules
const { quotes } = require('./data');
const { getRandomElement, filterByAuthor } = require('./utils');

// Define the port to listen on, defaulting to 4001 if not specified in the environment variables
const PORT = process.env.PORT || 4001;

// Middleware to parse JSON bodies in requests
app.use(express.json());
// Middleware to serve static files from the 'public' directory
app.use(express.static('public'));

// Function to handle requests for a random quote
function getRandomQuote(req, res)
{
  const randomQuote = getRandomElement(quotes);
  res.json({ quote: randomQuote });
}

// Function to handle requests for all quotes, optionally filtered by author
function getAllQuotes(req, res)
{
  const { person } = req.query;
  if (person)
  {
    const response = filterByAuthor(quotes, person);
    res.json({ quotes: response });
  } else
  {
    const AllQuotes = quotes.map((item, index) => ({
      id: index + 1,
      quote: item.quote,
      person: item.person,
    }));
    res.json({ quotes: AllQuotes });
  }
}

// Function to handle requests to post a new quote
function postQuote(req, res)
{
  const quote = req.query.quote;
  const person = req.query.person;
  if (!quote || !person)
  {
    res.status(400).send({ message: "Both quote and person are required in the query parameters." });
  } else
  {
    const newQuote = { quote, person };
    quotes.push(newQuote);
    res.status(201).send({ quote: newQuote });
  }
}

// Function to handle requests to update an existing quote
function updateQuote(req, res)
{
  const { id } = req.params;
  const index = parseInt(id) - 1;
  const { quote, person } = req.body;
  if (index !== -1)
  {
    if (!quote && !person)
    {
      res.status(404).send({ message: "Quote or person are required in the query parameters." });
    } else
    {
      const unchangedQuote = quotes[ index ].quote;
      const unchangedPerson = quotes[ index ].person;
      quotes[ index ] = { quote: quote || unchangedQuote, person: person || unchangedPerson };
      res.status(200).send({ quote: quotes[ index ] });
    }
  } else
  {
    res.status(404).send({ message: "Quote not found." });
  }
}

// Function to handle requests to delete a quote
function deleteQuote(req, res)
{
  const { id } = req.params;
  const index = parseInt(id) - 1;
  if (index !== -1)
  {
    quotes.splice(index, 1);
    res.status(200).send();
  } else
  {
    res.status(404).send({ message: "Quote not found." });
  }
}

// Define routes for the server
app.get('/api/quotes/random', getRandomQuote);
app.get('/api/quotes', getAllQuotes);
app.post('/api/quotes', postQuote);
app.put('/api/quotes/:id', updateQuote);
app.delete('/api/quotes/:id', deleteQuote);

// Start listening on the defined PORT, with a console log to confirm it's running
app.listen(PORT, () =>
{
  console.log(`Server running on localhost:${PORT}`);
});

Happy Coding!

1 Like

My respository. Happy coding guys!

Hi everyone! Here is my solution.

Quotes API solution

Hello everyone!

Here is my solution to the Quote API exercise

You will see I implemented the PUT and the DELETE methods.
Also, in order for each newly-made quotes, an ID is generated that can be captured for PUT nd DELETE methods to work.

Feel free to leave out any feedback :slight_smile:

1 Like

I will just post the parts of code that are required in the project:

  1. GET /api/quotes/random route:
app.get('/api/quotes/random', (req, res, next)=>{
   const theQuote = getRandomElement(quotes);
   const result = {quote: theQuote.quote};
   res.send(result);
});
  1. GET /api/quotes route:
    User gets whole quotes without query; user gets all quotes by same person in query; user gets empty array when person in query has no found quote.
    For example: when user types in address bar …/api/quotes?person=grace%20hopper, it shows quotes by Grace Hopper.
app.get('/api/quotes', (req, res, next)=>{
   if (Object.keys(req.query).length===0){
    const result = {
      quotes: quotes.map(item => item.quote)
    };
    res.send(result);
   }
   else if (req.query.person){
    let queryName = req.query.person.toLowerCase();
    const result = {
      quotes: quotes.filter(item => item.person.toLowerCase()===queryName).map(item => item.quote)
    };
    res.send(result);
  }
})
  1. POST /api/quotes route:
    reads json format request, adds new quote.
app.use(express.json());

app.post('/api/quotes', (req, res, next)=>{
  if (req.body.quote && req.body.person){
    let newQuote = req.body.quote;
    let newPerson = req.body.person;
    quotes.push({
      quote:newQuote,
      person:newPerson
    });
    res.status(201).send({quote:newQuote});
    console.log(quotes);
  }else{
    res.status(400).send('400 Bad Request');
  }
})
1 Like

Hello guys! :wave:t2:
I also have finished this project. But I think to still try to extend my app later.
Here is my solution on GitHub Quote API

I am trying to do the project off platform and using Postman to call my endpoints at localhost:4001 as per the starter code .
When I run the run the server.js file a browser opens to localhost:8080 and any Postman calls to my endpoint return ‘Error: connect ECONNREFUSED 127.0.0.1:4001’

Any help would be appreciated

Hi,

Are you still have trouble with this? I found that I needed to set the app.listen() up first using the port const provided for us before I could run the node server.js (which I imagine you have already done setting it to port)?

You could try adding a response to the log to confirm the port that it is open in like so:

app.listen(PORT, () => {
    console.log(`Server is running on ${PORT}`);
});

after you run ‘node server.js’ in the console that you are usisng (probably bash following the guidance in previous modules) you can then just navigate to that local port in your browser: http://localhost:4001/

I then tested the features live in the app via the browser.

I am not sure about postman, I got that same issue when trying to follow the example_backend instruction when we were first introduced to postman.

I don’t know if that helps, it is probably stuff you have already tried?

Hi all, OK here is mine, I have not done the additional steps they suggest, just the min ones. Any thoughts or comments let me know.

Many Thanks,
Kiernan

Fun little project. :slight_smile:
Sharing my code here.

Hello, here is my completed code challenge

Regards

This is the code I have completed, and it works as expected.

If you have any suggestions for improvements to add to my project, please feel free to share them with me.