APIs and the Random Quote Machine - Not even sure what to ask

I feel so extraordinarily unprepared for this project. I don’t even know where to start looking for resources. FCC’s been good to me so far but this project feels like being thrown into a deep pool full of laser sharks and being given a pair of water-wings and told “just go for it!”

Sorry. I’m a little frustrated.

I guess what I’m looking for are some stepping stones. I’m doing the Codecademy course on jQuery and I feel like that’s helped me understand that part of the challenge, but I’m just baffled on how to interact with an API and all of the resources I’ve looked at so far seem to assume a level of knowledge I just don’t have. So, campers, any suggestions on where to find some really basic info to get me started?

9 Likes

@paintingfire Hi, I am a newbie here… what I do is I create some kind of a pseudocode or a general overview/outline of the major steps that I would take in order to solve the project then narrow each major step to more specific steps. After creating an overview, I read the documentation that I will be using (e.g. jQuery Ajax docs, API usage docs).

1 Like

What’s helped me is Intro to jQuery and Intro to Ajax.

There is also this series of videos, I haven’t watched it yet. but it looks even better

And the funny thing is you’ll come back to the FCC few snippets of code and realise everything is there :slight_smile:

7 Likes

You don’t have to use an API for that project. Here’s how I did it: I simply stored a list of quotations in an array and wrote a function that randomly selects a quote from the array and displays it on the page with innerHTML. That function is called when the page loads and when the user clicks the “new quote” button. (Demo)

I’m not saying that there is anything wrong with using an API though.

9 Likes

I thought about doing this and I may still. I was trying to look at it as an opportunity to learn something new and useful but I feel like I’m banging my head against a wall.

2 Likes

Have you completed all the sections before and fully understood the JSON APIs and AJAX section on FCC ? If yes, you will be fine.What you have to do is :

  1. find one external service that provides a quotes API.Just type “quotes API” in google and you’ll find them.Some are easy to use, some require you to register your app, some are complicated…

  2. read their documentation/usage example to see how it works.

  3. Use jQuery, start with simple code.Don’t make a button, don’t do CSS.Just try to display the content of the quote in the body of the page.

5 Likes

I just started the Ajax course- thanks for the resources!

Cool - I don’t if it’s because I’d watched both Intros on Udacity but the youtube course really clarified a lot of things for me. Good luck,

2 Likes

I did go through all those sections, but no, I didn’t fully understand them. I found a service, and I can get it to display one quote, but for some reason I can’t get the random function to work. I don’t understand the code from the API website well enough to figure out what I’m doing wrong, so I’m trying to fill in the gaps in what FCC didn’t teach about this topic because I found their lessons on jQuery and Ajax to be incomplete, at least for my needs.

I wrote the original random quote machine for the FCC curriculum. Quincey saw it and asked if they could include it in FCC. It was not meant to be an API project, but it can be. I did it as a random selection from an array of quotes. If you do it that way it’s a fairly “basic” project that uses (or can use) just jquery and basic javascript.

Adding a twitter share adds a challenge, and adding an api adds a challenge.

Make the basic one first using an array of quote. You can reuse most of your code with an API once you get the basic version working.

5 Likes

That’s a huge step to build on. The remaining problem is probably as trivial as a typo somewhere.
If you put what you have so far on CodePen and post a link, we’ll get this sorted out in no time together.
In case you’re worried because it feels like cheating to have others point you in the right direction—remember that the officially recommended FCC methodology is “read, search, ask”. You are apparently in the “ask” stage now. There is nothing wrong with that, we’ve all been there.

1 Like

Thanks. I guess it does kind of feel like cheating, but what you say makes sense.

Here’s my project so far. I haven’t done any styling yet, or tried to format the twitter button. I was trying to get the quote to work first.

Hi again.

Thank you for sharing this issue.Thanks to you, I’m learning new stuff !

it seems getJSON is caching the quote, and instead of making new call each time to the api, it reuses the same data, not cool at all :

this may help you :

2 Likes

As expected, the problem was easy to solve. Working code below.
Hints:

  • Rewrite the anonymous function inside $('#get-another-quote-button').click() as a named function so you can execute it both when the page loads and when the user clicks the button.
  • Google “getJSON cache false”.

Spoiler alert: Working code below.

// query the API
function getQuote() {
    $('#quote-content').empty();
    $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(a) {
        $("#quote-content").append(a[0].content + "<p>— " + a[0].title + "</p>");
    });
}

// Execute getQuote() when users click the button
$('#get-another-quote-button').click(getQuote);

$(document).ready(function() {
    // set cache to false so we get a new quote every time:
    $.ajaxSetup({
        cache: false
    });
    getQuote();
});

I’ve used React to set do it, the process was fairly quick, I’ve repeated code which I should put in a function, also I’ve not styled it at all, that’s the task for tomorrow, got enough with setting the API and this simple component today.

class App extends Component {
  constructor() {
    super();
    this.state = {
      quotation: "Great things in business are never done by one person. They're done by a team of people.",
      randomId: 1
    };
  }
  
  componentWillMount() {
    const API_URL = "http://localhost:8081/api/quotations/1";
    axios.get(API_URL)
      .then(res => {
        console.log(res.data);
        this.setState({
          quotation: res.data.data
        });
      })
      .catch(err => {
        console.error(err);
      });
  }
  
  fetchQuotation(e) {
    // Repeated code, I know, will refactor later
    let randomId = Math.floor(Math.random() * 10) + 1;
    const API_URL = `http://localhost:8081/api/quotations/${randomId}`;
    axios.get(API_URL)
      .then(res => {
        console.log(res.data);
        this.setState({
          quotation: res.data.data
        });
      })
      .catch(err => {
        console.error(err);
      });
  }
  
  render() {
    return (
      <div className="App">
        <h1>{this.state.quotation.content}</h1>
        <button onClick={ (e) => this.fetchQuotation(e) }>Generate number</button>
      </div>
    );
  }
}

export default App;

One of the advantages of React is re-rendering once the state has changed :slight_smile:

Hi @paintingfire , maybe you’ve completed your RQM challenge by now but i felt exactly how you felling now “Deep Waters!” so if you haven’t; remember that you can always complete a challenge in so many ways, i.e. use an array ( var arr = [“quote1”, “quote2”, “etc”]; ) of quotes an iterate through them and let me tell you that if i got out of those waters and killed all those sharks you can too!

1 Like

I did the same I went too fast and based mine on design and favorite characters instead of looking for an api then, after finishing my design i realized that there were not many api’s to be found so i used an array
https://tommygebru.github.io/quote/

this is a good idea i think the best way to practice react is to redo your old projects, also it can be done offline :smile: :blush:

I’ve finished the functionality https://github.com/Oxyrus/Wonka

I’ll style it tomorrow :slight_smile:

I also used Quotes on Design for my API, and ran into the same caching issue. I read a bunch of work-arounds, but the most reliable fix for me was adding an extra parameter to each http get request.

I use angularjs and wrote a service to handle the ajax. The syntax is slightly different than jQuery but the principle is the same: add an extra query parameter to the http request - one that the server doesn’t expect and that’s always unique. The server will ignore it, but it forces your browser to not cache the response. So what’s always unique?: the current time. Note the timestamp parameter below:

function get() {

    var quoteApi = {
        endpoint: 'https://quotesondesign.com/wp-json/posts',
        params: {
            'filter[orderby]': 'rand',
            'filter[posts_per_page]': 1,
            'timestamp': new Date().getTime()
        }
    };
         
    return $http.get(quoteApi.endpoint, { params: quoteApi.params } );

}

The resulting http get request url assembles into this:

http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&timestamp=1482517017595

You can do the same thing in jQuery. The .getJSON() method takes an optional data argument:

$.getJSON(api_endpoint, data, callback);

data needs to be an object, just like the params object in my example above.

2 Likes