Learn API by Building 3 Cool Projects— Part 1

We learn better when we implement ;)

Pushpa Kumari
TheLeanProgrammer
15 min readMay 24, 2021

--

What is an API?

API (Application Programming Interface), is a software intermediary that enables data transmission between two applications.

Example of an API-

Sign in page of a website
GeeksForGeeks Login Page

Sign In Using Goggle / Facebook / LinkedIn etc.

We all must have seen this option in many websites while signing in to that website. It makes signing in to a website convenient for us, as we don’t have to enter the credentials. But have you ever wondered how it works?

The way it works is pretty simple. When the application loads it checks whether the user is signed in. If not then, when the user clicks the “Sign In using Google / Facebook / LinkedIn, etc.” button, a pop-up appears where the user has to confirm that they want to sign in using the specified social media account. When the user confirms, the API provides the application with identification information, so it knows who’s logging in.

Common APIs

  • The YouTube API allows you to embed YouTube videos on your site, search for YouTube videos, and much more.
  • The Pinterest API allows you to include pins in your website and manage Pinterest boards.
  • Flickr API can be used to retrieve photos from a Flickr photo-sharing service using a variety of feeds — public photos and videos, favorites, friends, group pools, discussions, and much more.

You can view more such APIs at ProgrammableWeb.

How does an API work?

When the user submits its query to the server, then the API fetches the data if it is accessible otherwise it returns with an error message (as API provides you only the data which is for external users, other data items remain hidden).

Now, it's important for us to use the concepts we learn in real life as well. It not only clears one’s concepts on that topic, but it also helps to boost our confidence regarding that particular topic.

These days I am making small projects using HTML, CSS, and JavaScript from the course 50 Projects In 50 Days by Brad Traversy and Florin Pop. Don’t worry if you are a complete beginner to APIs, this article will help get started with APIs.

What Are We Going to Build in This Article Series?

Okay, so finally it's time to make some really cool API projects. Let’s just have a quick overview of the projects that we will be making.

  1. Movie App — An application where users can search for movies by their titles. Each movie card will display the rating and a short description of the movie with a movie poster.
  2. GitHub Profile Search — An application that displays the details of the searched GitHub user (if valid). Details like profile image, short description, number of followers, number of repositories, recently created repositories, etc.
  3. Pokedex — It lists some Pokemons with their image, ID, name, and type. Depending upon the Pokemon type we will set the background color of the card.

Some Prerequisites

Before getting started with the projects we need to set up the project environment. Following are the steps:

  1. Download Atom / Sublime Text/ VS Code (I have used Atom for the projects).
  2. Install Atom / Sublime Text/ VS Code.
  3. Sign up on The Movie Database (TMDb) (to get an API key for Movie App).

Note: — You don’t need to Sign up for GitHub API and Pokemon API.

Project 1 — Movie App

Movie App Image

An application where users can search for movies by their titles. Each movie card will display the rating and a short description of the movie with a movie poster. For this project, we will be using The Movie Database (TMDb).

You can check the complete code on my GitHub repository.

Now, let’s just have a quick look at how the project will look, once we complete it.

Movie App in Action

Steps of Making the Project-

We will be making the project step by step. Below are the steps which we will follow:

  1. Creating a folder for the project, with HTML (e.g. index.html), CSS (e.g. styles.css), and JavaScript (e.g. script.js) files
  2. UI and styling of the project
  3. Fetching data from the API
  4. Adding movies to the DOM

So, let’s get started.

Step 1 — Creating a Folder for the Project

This is the easiest step of the project. All you need to do is to go to your Atom / Sublime Text/ VS Code editor (whichever you are using) and make a folder named “MovieApp”. Then add 3 files there, HTML (e.g. index.html), CSS (e.g. styles.css), and JavaScript (e.g. script.js) files.

Let me write down the steps for clear understanding:

  1. Open Atom / Sublime Text / VS Code.
  2. Go to File > Add Project Folder.
  3. Select the folder where you want to store the project files > Right-click there > New > Add Folder.
  4. Name your folder whatever you feel like and click enter, then click on “Select Folder” to create the folder (I have named it MovieApp).
  5. File > New File (Make 3 files by following this step repeatedly).
  6. Save the first file as index.html, the second file as styles.css, and the third file as script.js.

Don’t worry if you couldn’t follow the above steps. You can follow the video given below:

Creating a Folder for the Project With HTML, CSS, and JavaScript Files

After creating the files, the next thing we need to do is to add a boilerplate to the index.html (HTML File) and styles.css (CSS File). It's simply a project starter that is used in almost all projects.

Open the “index.html” file and type the following code.

That's our boilerplate code for HTML. We are using two <meta> tags, one for the charset and another for the viewport. Then we are linking our “styles.css” file and “script.js” file.

Now, coming to the CSS file boilerplate.

Open the “styles.css” file and type the following code.

In the CSS file (styles.css) we will import the font from Google Fonts (I am using Cinzel, you can use any font of your choice).

Mainly, I will be using just two colors (#22254b and #373b69) for the UI of the project. So I have stored them in a variable.

We are selecting every element in the project using * and defining how the width and height of that element will be calculated using the box-sizing property.

Okay, so now we are done with the Project Starter.

Step 2 — UI And Styling of the Project

The web application page is basically divided into two parts, first the Search Bar, and the second is the section containing the Movies List.

We will put the Search Bar inside the <header> tag. The <header> tag will contain a <form> with just one input i.e. Search Bar. Users will enter the movie they want to search and hit enter to view the search results.

Now type the following code between <body> and <script> tag for Search Bar.

The next section will be containing movie lists. The data of this section will be fetched from the API. But, for now, we are going to hard code this section so that we can style it. Later we will delete the hard-coded data and fetch the data in the JavaScript file through the API.

For styling purposes, I have taken dummy data in the <main> tag. I have added an image from Unsplash and Lorem ipsum text as the movie overview (You can put any image and text, as we will be deleting this later on).

Now type the following code between </header> and <script> tag.

Here we have 3 divisions (<div>) with class=”movie”. Each movie class holds the poster of the movie with two more divisions (<div>). In the first division (<div>) movie information is stored like Movie Title and Movie Rating. We have stored the Movie Overview in the next division (<div>).

With this, the structuring of the page finishes. Now, we will style it using CSS.

Open the “styles.css” file you created and type the following code to style the <header>.

Here we have defined the <header> as a flex container.

Type the following code in “styles.css” for styling the Search Bar.

I assume that the above code is pretty self-explanatory. So try to understand it by yourself.

Again type the following code in “styles.css”.

We have defined the <main> as a flex container. Flex-wrap property has been given the value of wrap, which ensures that the data automatically gets adjusted to the next line if it exceeds the present line.

Now, we will be styling the movie cards. Note that here I have taken different colors for different movie ratings, i.e. Rating ≥ 8.0 will be displayed in green color, 8.0 > rating ≥ 5 will be displayed in orange color, and 5 > rating will be displayed in red color.

And, lastly, type the following code in “styles.css”.

The overview of a movie is initially kept hidden, and it shows upon hovering the movie poster. We have done this by adding the hover property to the overview class.

That’s it!! Our HTML and CSS part of the project is done. And with this, we have completed Step — 2 of the project.

Now our project looks something like the one given in the video below.

Movie App After Completing Step 2

Step 3 — Fetching Data From the API

I hope you have Signed Up for The Movie Database (TMDb) API.

Now, let's have a quick overview of The Movie Database (TMDb) API. Visit The Movie Database (TMDb) > Discover Examples. Here you will see the different methods by which you can discover /fetch specific types of data.

For example, if you want the most popular movies then you can use the following URL: https://discover/movie?sort_by=popularity.desc, or if you want the best dramas that were released this year, then use the following URL: /discover/movie?with_genres=18&primary_release_year=2021.

But for now, we will just focus on getting our API key. So follow the steps given below to get your API key.

  1. Visit The Movie Database (TMDb).
  2. Click on developers.themoviedb.org, given under API Documentation.
Click on “developers.themoviedb.org”

3. Click on API Link under Introduction.

Click on “API Link”

4. Now, your account will open. Click click here under Request an API key. And then fill in the details which have been asked.

Note: — Application URL will be “http://localhost” (because the project is on localhost).

Click on “click here”

After this click the “submit” button.

5. You will be redirected to the page where you can find your API key under API Key (v3 auth).

For example, given below is my API key.

My API Key

After getting the API key, now we want to fetch the data.

There are 3 ways to search for and find movies, TV shows, and people on TMDb. Search, Discover and Find. In this project, we will be using Search and Discover methods.

/search — Text-based search is the most common way. You provide a query string and it outputs the closest match. Searching by text takes into account all original, translated, alternative names and titles.

/discover — Sometimes it is useful to search for movies and TV shows based on filters or definable values like ratings, certifications, or release dates. The discover method makes it easy.

First, we will look at the Discover Method:

Remember, we discussed about fetching different types of data at the beginning of Step — 3. Here, I am fetching the most popular movies in descending order (I have fetched data for 1 page only), which will be displayed on the website.

Discover API URL format — https://<sub-domain>.<domain>/<version of API>/<URL of the type of data you want to fetch>&api_key=<your API Key>&page=1

So, type the following code in “script.js”.

Now, we will look at the Search Method:

Search API URL format — https://<sub-domain>.<domain>/<version of API>/<url of the type of data you want to fetch>&api_key=<your API Key>&query=”<whatever users inputs in Search Bar>”

Type the following code in “script.js”.

Did you notice that we haven’t added anything after the query in the above URL? That’s because we will concatenate the string query which users enter using a JavaScript function to the SEARCH_API URL to make the SEARCH_API URL completely working.

The next thing we want is the movie poster.

Image URL format — https://image.tmdb.org/t/p/w1280<poster path>

Type the following code in “script.js”.

We haven’t added the poster path yet. The poster path will be added when data will be added to the DOM (i.e in Step — 4).

Note: — w1280 is the size of the image in the Image URL. You can change the size as you wish.

Okay, so we have added all the URLs which we will need to fetch the data for this project.

Now, we will import the elements to make them functional through JavaScript. Type the following code in the “script.js” file.

We have imported search to make it functional so that when a user searches, it accepts the query and gives the results.

Similarly, in <main> we will add the movie cards through JavaScript.

To make a query request successful we need to fetch data from the API URLs. So, let's build a function that will fetch the data from API.

We will be using async-await. Type the following code in the “script.js” file.

getMovies() is an asynchronous function. It gets the API_URL as its parameter and calls showMovies() function to display the movies.

await fetch(url) starts a request to the URL. Because the await keyword is present, the function getMovies() is paused until the request completes. A promise is returned at this stage.

When the request completes, the promise is resolved with a res object.

await res.json() is a method on the res object that lets you extract a JSON object from the res (this is the line that fetches the data actually).

Go through this article to have a clear understanding of fetch with async/await.

Note: — If you want to check whether the data is being fetched or not, then simply replace the “showMovies(data.results)” with “console.log(data);” in getMovies() function. The output will be something like the one shown in the below video.

Fetched Data

We also want to search for movies through the Search Bar. To make the Search Bar working, type the following code in “script.js”.

Adding an event listener of type submit makes the form accept string queries from the user.

Whatever the user is entering in Search Bar is being stored in the variable searchTerm and then the searchTerm is being concatenated at the end of SEARCH_API to complete the SEARCH_API link (only if the user doesn’t enter an empty string). Then the final link is passed as an argument to getMovies() function to show the results.

Else if the user enters an empty string, then the page reloads.

With this, we are now done with Step — 3.

Step 4 — Adding Movies to the DOM

Do you remember the function we called in getMovies() function with the name showMovies()?

So, we are fetching data through the getMovies() function, but we also need to display those fetched movies on our website. showMovies() function will do this task. As we will display the movies from the JavaScript function then we don’t need the movies we hard-coded in “index.html”.

Let's remove everything between the <main> opening and closing tags. The final HTML code will be as follows:

Type the code given below in “script.js”.

Whenever showMovies() function is called, the <main> tag is set to empty so that, new fetched movies can be listed in it.

For each movie, we are fetching its title, poster_path, vote_average, and overview. Then we are adding a division element <div> in <main> with class movie using the following code:

Remember that I told you earlier in this article that to fetch the poster of a movie we have to concatenate the IMG_PATH with the poster_path. Below is the code for it.

After this, we are inserting the movie name, vote_average, and overview.

To display the ratings, we are inserting vote_average and setting the class of it by passing the vote_average to getClassByRate(), which decides the class on the basis of vote_average.

getClassByRate() function is yet to be defined. It will set the font color for different types of ratings (i.e. rating≥8.0 then color should be green, 8.0>rating≥5.0 then color should be orange, else red). Type the code given below in “script.js”.

The above code is self-explanatory in my opinion. It just sets the class to green, orange, and red of the ratings. And depending upon the class they are assigned different colors.

That’s it !! We have completed our first API project.

Movie App

I hope you liked this article. If you have any doubts, please ask me in the comments section. And, if you enjoyed this article, then please hit the like button.

Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer

--

--