Why do you have APIphobia when you make API calls daily?

Why do you have APIphobia when you make API calls daily?

Make your first API call with me and embrace the power of APIs in 6 minutes by learning through storytelling.

ยท

6 min read

Finally, it's the weekend and you want to boost up your mood after having a hard week with Javascript at your workplace. You are all set to play golf, but it suddenly starts raining. You decided to stay at home and binge-watch a web series instead. Before starting the series, you wish to grab some snacks that your mother has prepared for you. You're lazy so you asked your younger sibling to pick up the snacks for you from the kitchen. She is kind enough to do that for you. Congrats, you just made an API call, and I'm not even kidding.

Well yeah, it's just that simple. Let me explain it to you in detail now.

So, when you asked your sibling to fetch the snacks for you, she basically did what APIs do in general, i.e., getting data (snacks) from a server (kitchen) on the client's (your) request. Let's dig deeper into what exactly these jargons mean.

  • Client

Think of a client as any smart device that can get data from somewhere using the internet. E.g. Laptops, smart watches, tablets, mobile phones, etc.

  • Server

You can assume servers as just simple computers or computer programs that accept requests from clients asking for something and gives a response accordingly.

A successful API call is when the client makes a request to the server asking for something and the server gives a response to the client with that particular thing.

You must be angry at me as I have introduced a few more fancy words and I didn't explain them till now. I'm going to elaborate on them first so that you don't kill me.

  • Request-Response Cycle

Screen Shot 2022-08-04 at 8.01.13 PM.png

  • Request -> Device asks for a resource. E.g. data, images, etc.
  • Response -> Response is the reply to a request.

The request could contain the resource asked by the client or it may contain a response saying that the client isn't authorised to receive the resource. For instance, if the client is asking for a piece of secret information, the server will respond with a 403 Forbidden error.

Now, let's just get back to the story. You're ready to watch the series, but when you logged in to your Netflix account, suddenly you are confused about what you should watch. You ask your younger sister to recommend you something, but she has no clue about what actually you're talking about (she knows about Shinchan though ๐Ÿ˜‚). You just learnt about APIs, client, server, request and response so you think about implementing it to good use.

You decide that you'll make a Web Series Recommendation website that suggests a random web series with every button click. You googled for how to fetch data from APIs. You get to MDN web docs and read about Fetch API. The fetch request looked like this :

Snap (1).png

You get to know that fetch() takes one argument โ€” the path to the resource you want to fetch. I'll talk about promises some other day in a different article as I don't wish to make this article complicated for beginners. For now, just remember that we are getting data from the website on our machine using fetch() method.

Since you're new to the fetch() method, you decided to first make the skeleton of the website and get back to the Javascript part later. You started by writing these HTML and CSS files :

index.html

<html>
    <head>
        <link rel="stylesheet" href="index.css">
    </head>
    <body id="body">
        <h1 id="title">Web Series Recommendation</h1>
        <p id="suggestion">Click the button and I'll suggest a web series you could watch</p>
        <button id="get-suggestion">Suggest me</button>
        <script src="index.js"></script>
    </body>
</html>

index.css

body {
    display: flex;
    flex-direction: column;
    align-items: center;
}

h1{
    margin-top: 1em;
    font-size: 3rem;
}

p{
    margin: 4em 0;
    font-size: 2rem;
    font-weight: 200;
}

button {
    height: 3rem;
    width: 8rem;
    background-color: coral;
    font-size: 1.2rem;
    font-weight: bold;
    border: 2px solid black;
    cursor: pointer;
}

button:active, button:hover{
    background-color: green;
}

Your website currently looks like this:

Screen Shot 2022-08-04 at 8.49.03 PM.png

Now, you just need to make that Suggest me Button work. It should ideally recommend a web series when you click on it. You are clueless about what API you should use to fetch the title of the web series. You head over to Scrimba's Discord channel and ask your colleague to provide you with an API that provides web series details. She told you about TV Maze API and when you clicked on the link provided by her, it showed many lines which were unreadable. It looked like a JSON file.

You copied all the text from the website and pasted it on JSON Formatter then you clicked on Format option. It was readable now. It looked like this:

Screen Shot 2022-08-04 at 9.12.15 PM.png

You were only interested in the name of the series, and the name could be accessed with the key "name" as seen in the picture above. But, it showed a list of web series and you wanted 1 random series on every button click. You searched about how to generate random numbers in Javascript and you found this code:

    // Generates a number between 1 and 245
    // +1 so that it starts from 1 and not 0 as id = 0 is not present
    let random = Math.floor(Math.random() * 245) + 1;
    console.log(random)
    // Logs value between 1 and 245 (both inclusive)

You can use any number instead of 245 as long as it doesn't exceed the value of id. It will show undefined on the screen if we hit that number because it will not be able to find the title of web series with an invalid id

You now know how to generate a random number between two numbers so you are all set to go. You write a Javascript code to fetch a random web series title from the API and display it on the browser with every button click. This was the code you wrote :

index.js

document
  .getElementById("get-suggestion")
  .addEventListener("click", function () {
    // Generates a number between 1 and 245
    let random = Math.floor(Math.random() * 245) + 1;
    // ${random} will be the dynamic value provided by the random variable.
    // It will search a movie title with a different id every time and hence, a unique web series suggestion
    fetch(`https://api.tvmaze.com/shows/${random}`)
      .then((response) => response.json())
      .then((data) => {
        // As we have seen in JSON file, the title of the web series can be accessed by the key "name"
        // so we are using data.name instead of data
        document.getElementById("suggestion").textContent = data.name
      });

Now, your website suggests a random web series with each button click.

Screen Shot 2022-08-04 at 9.45.10 PM.png

Screen Shot 2022-08-04 at 9.45.34 PM.png

Screen Shot 2022-08-04 at 9.46.05 PM.png

You're a happy soul now and you will never have to ask for a web series recommendation from anyone ever again. If you're reading until now, make sure to reward yourself with a web series binge-watch that your website has suggested.

Follow me for more articles. See you super soon with another article. I hope you enjoyed learning through storytelling.

ย