Ravenous Part 4: Interacting with the Yelp API

Congratulations on completing your project!

Compare your project to our solution code and share your project below! Your solution might not look exactly like ours, and that’s okay! The most important thing right now is to get your code working as it should (you can always refactor more later). There are multiple ways to complete these projects and you should exercise your creative abilities in doing so.

This is a safe space for you to ask questions about any sample solution code and share your work with others! Simply reply to this thread to get the conversation started. Feedback is a vital component in getting better with coding and all ability levels are welcome here, so don’t be shy!

About community guidelines: This is a supportive and kind community of people learning and developing their skills. All comments here are expected to keep to our community guidelines


How do I share my own solutions?

  • If you completed the project off-platform, you can upload your project to your own GitHub and share the public link on the relevant project topic.
  • If you completed the project in the Codecademy learning environment, click on “Tools” and use the create a gist button, and then share that link here.

Do I really need to get set up on GitHub?
Yes! Both of these sharing methods require you to get set up on GitHub, and trust us, it’s worth your time. Here’s why:

  1. Once you have your project in GitHub, you’ll be able to share proof of your work with potential employers, and link out to it on your CV.
  2. It’s a great opportunity to get your feet wet using a development tool that tech workers use on the job, every day.

Not sure how to get started? We’ve got you covered - read this article for the easiest way to get set up on GitHub .

Best practices for asking questions about the sample solution

  • Be specific! Reference exact line numbers and syntax so others are able to identify the area of the code you have questions about.

Here is my project. It is very similar to the solution in terms of how everything is set up. CSS is slightly different but logic is pretty much the same.

There are some css issues I would like to fix in the future but as a whole I was just happy to finish the project. If anyone has any suggestions to write cleaner code or anything that they think i should put instead of what I did i would love to hear some suggestions

I am unable to access the Yelp page that is supposed to allow me to generate an API key. Is there any way around this problem? I have sent an email requesting access. Below is what I see when I click on the link - I also get this page when I try to go through this direct link (Fusion Authentication):

This is my freshly baked solution to the Project:

Tutorial:

Resolving the CORS Issue and Setting Up Environment Variables

After facing a series of errors (quite a lot of errors, actually), I managed to find a robust solution to the CORS (Cross-Origin Resource Sharing) issue I was experiencing while trying to consume the Yelp API in my React project. In this tutorial, I will detail how I set up an Express server to handle requests to the Yelp API, and how I structured my development environment to keep my API key secure.

Project Structure:

I created a folder named server at the root of my project, inside of which I placed two files: server.mjs and .env.

Directory:

- server
  - server.mjs
  - .env

Configuring the Express Server:

  1. Module Installation:
    First, we need to install the necessary modules. In the terminal, run the following command:

    npm install express node-fetch cors dotenv
    
  2. File server.mjs:

    import dotenv from 'dotenv';
    import express from 'express';
    import fetch from 'node-fetch';
    import cors from 'cors'; 
    
    dotenv.config();
    
    const app = express();
    
    app.use(cors()); 
    
    app.get('/yelp/businesses/search', async (req, res) => {
      const { term, location, sort_by } = req.query;
    
      try {
        const response = await fetch(
          `https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}&sort_by=${sort_by}`,
          {
            headers: {
              Authorization: `Bearer ${process.env.REACT_APP_API_KEY}`,
            },
          },
        );
    
        const data = await response.json();
        res.json(data);
      } catch (error) {
        console.error(error);
        res.status(500).send('Internal Server Error');
      }
    });
    
    app.listen(3001, () => {
      console.log('Server is running on port 3001');
    });
    

    Here, I created an Express server that listens on port 3001 and has an endpoint that redirects requests to the Yelp API. I used the node-fetch module to make the HTTP request, and cors to handle CORS.

  3. File .env:

    REACT_APP_API_KEY=your_api_key_here
    

Configuring the Front-end:

  1. File Yelp.js:
const apiKey = process.env.REACT_APP_API_KEY;

const Yelp = {
  search(term, location, sortBy) {
    return fetch(
      `http://localhost:3001/yelp/businesses/search?term=${term}&location=${location}&sort_by=${sortBy}`,
      {
        headers: {
          Authorization: `Bearer ${apiKey}`,
        },
      },
    )
      .then((response) => {
        if (!response.ok) {
          return response.json().then((errorResponse) => {
            console.error('API error:', errorResponse);
            throw new Error('API error');
          });
        }
        return response.json();
      })
      .then((jsonResponse) => {
        if (jsonResponse.businesses) {
          return jsonResponse.businesses.map((business) => {
            return {
              id: business.id,
              imageSrc: business.image_url,
              name: business.name,
              address: business.location.address1,
              city: business.location.city,
              state: business.location.state,
              zipCode: business.location.zip_code,
              category: business.categories[0]?.title,
              rating: business.rating,
              reviewCount: business.review_count,
            };
          });
        } else {
          console.log('No businesses found', jsonResponse);
        }
      })
      .catch((error) => {
        console.error('Error fetching and parsing data', error);
      });
  },
};

export default Yelp;

After these configurations, my Express server serves as an intermediary between the front-end and the Yelp API, handling CORS and keeping my API key secure through the use of environment variables. This approach helped me overcome the challenges after hours facing this problem and I hope it can help other developers who might be facing similar issues.

Remember to place the .env file in the .gitignore file if you are going to upload it to GitHub to keep your API key secure.

Live: https://revenouss.netlify.app/
Repository: GitHub - felpsg/ravenous

Great my project is completed!! It looks & work great!

Now i can add additional features, add styling and fix bugs!

Thx a lot! Codecademy! Great challenge!

Last commit Reference:
0911291

I keep getting the following error 403 :

’ Yelp.js:5 GET https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?term=fdfgdf&location=fdhgdf&sort_by= 403 ’

Anyone has an idea what could be the solution ?

I tried to do felpsg fix but now i get ERR_CONNECTION_REFUSED

This is my take on this project:

Source code: GitHub - nabi-cloud/ravenous: React restaurant recommendation app using Yelp's API
Live View: https://ravenous-react-app.netlify.app/