api - sasjakoning/blok-tech-2022 GitHub Wiki

api

Application Programming Interfaces (APIs) are constructs made available in programming languages to allow developers to create complex functionality more easily.

Battle Matcher uses an API to generate quotes for the different users displayed while swiping. These quotes can be viewed by clicking on a card which will flip it.

gif of api

To load these quotes, first a fetch package will need to be installed since Node does not have it build in by default.

For Battle Matcher I installed node-fetch.

the api I used is called Quotable created by Luke Peavey.

To fetch the quotes I created a new function in app.js called getQuote()

    // quotes API
    const getQuote = async () => {
    let randomQuotes = [];

    // get 2 quotes and push to randomQuotes
    for (let i = 0; i < 2; i++) {
        let quote = await fetch(
        "https://api.quotable.io/random"
        );

        quote = await quote.json();

        randomQuotes.push(quote.content);
    }

    console.log(randomQuotes)


    return randomQuotes;
    };

The above code gets two quotes from the api and pushes it into an array which I then add to the user documents that I serve to Handlebars.

    // result = user documents from MongoDB
    result.forEach((element) => {
    let i = result.indexOf(element);
    element.quote = randomQuotes[i];
    });

Due to the API being handled server side, there is no client-side Javascript required for this api to work.