API's - brightstudent/backend GitHub Wiki

API's

What is an API

Consider an API to be a restaurant menu. The menu includes a list of available meals as well as a description of each item. When you indicate the menu items you want, the restaurant's kitchen prepares them and serves them to you. You have no idea how the restaurant prepares the food, and you don't need to. Similarly, an API has a collection of actions that developers may utilize, as well as an explanation of what they perform. The developer does not need to understand how an operating system constructs and displays a "Save As" dialog box, for example. They only need to be aware that it is accessible for usage in their app.

API's that I use

Fetch API

I use fetch to get and print pictures of different restaurants. Then I use it once again inside the function to save a restaurant to my favorites page.


// gets data from database
fetch("/api/restaurants")
  .then((res) => res.json())
  .then(init);


function init(restaurants) {
  const parent = document.querySelector("#option #images");
  const optionName = document.querySelector("#option .name a");
  const optionLocation = document.querySelector("#option .location");

  const rejectBtn = document.querySelector("#reject");
  const saveBtn = document.querySelector("#save");

  let index = 0;
  function displayRestaurant(idx) {
    // If restaurant is set and not empty
    if (restaurants && restaurants.length) {
      // clear previous images if any
      // if has any child then remove the child
      while (parent.firstChild) {
        parent.removeChild(parent.firstChild);
      }
      // % modulo creates a loop for the array
      const restaurant = restaurants[idx % restaurants.length];
      restaurant.pictures.forEach((pic) => {
        const img = document.createElement("img");
        img.src = pic;
        img.draggable = false;
        parent.append(img);
        parent.scrollLeft = 0;
      });
      optionName.textContent = restaurant.name;
      optionName.href = "/restaurants/" + restaurant.slug;
      optionLocation.textContent = restaurant.location;
    }
  }
  // displayRestaurant(index);

  rejectBtn.addEventListener("click", () => {
    displayRestaurant(++index);
  });

  // prints the data
  saveBtn.addEventListener("click", async () => {
    const request = {
      favorite: restaurants[index % restaurants.length]._id, 
      user: localStorage.getItem('email')
    }
    // save fav on the server
    await fetch("/api/favorites", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(request),
    });
    displayRestaurant(++index);
  });
}

localStorage

The localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed. (localStorage data for a document loaded in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.)

I use this API to simulate different users, without developing a login feature. And it ensures that the saved restaurants still be saved.

const startBtn = document.querySelector('input[type="submit"]');

function saveEmail (e) {
  e.preventDefault()
  let email = document.querySelector('input[type=email]').value;
  localStorage.setItem('email', email)
  window.location.href = "/";
}

startBtn.addEventListener('click', saveEmail)

My public API

For my public API I use unsplash to generate random food foto's on my "login-screen". First I had to install the unsplash package and node-fetch. Then require those packages on my server.

const unsplash = require("unsplash-js");
const fetch = require("node-fetch");

This API needs an accesskey which you can require by making an account. To secure the acceskey, I made sure to included it to my dotenv file. After that I could make a request using the query:food to get 10 pictures from the first page and render a random one on my login screen.

app.get("/login", async (req, res) => {
  const api = unsplash.createApi({
    accessKey: process.env.UNSPLASH_KEY,
    fetch,
  });
  const splashResponse = await api.search.getPhotos({query: 'food', page: 1, perPage: 10});
  const pics = splashResponse.response.results
  const randomIndex = Math.floor(Math.random() * 43) % pics.length
  res.render("pages/login", 
    {backgroundImage: pics[randomIndex].urls.regular}
  );
});

Source

https://www.mulesoft.com/resources/api/what-is-an-api https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage