DEV Community

Cover image for How To Build A YouTube API Connection (Project) Using Vanilla JavaScript
Emmanuel C. Okolie
Emmanuel C. Okolie

Posted on

How To Build A YouTube API Connection (Project) Using Vanilla JavaScript

Introduction

As a developer, you will use API at some point in your web-developing Journey. The use of API is almost an undeniable fact for a developer.

So for the sake of this Guide, we’ll be looking at how the YouTube API Connection can be done. The YouTube Data API retrieves video data and presents it on a webpage when building a YouTube API connection project with vanilla JavaScript. Here is a straightforward, step-by-step setup guide for this project.

Without wasting your precious time! Let's dive into this guide.

Prerequisite

The things you need to achieve building an outstanding YouTube API Connection Project. are as follows:
You must have a basic knowledge of

  1. HTML
  2. CSS
  3. JavaScript(Basic)
  4. Understand API

What Is An API

Application Programming Interfaces, or APIs, are a collection of guidelines and conventions that facilitate communication between various software programs. Imagine it as a bridge that spans two distinct systems, enabling them to communicate or carry out activities without having to comprehend one another's inner workings.

Here’s a breakdown of how an API works and its purpose:
1. The Operation of APIs

An application can send a request to another application through an API, and the other application will reply with the information or action that was requested. To ensure that both programs can understand one another, the format of these requests and answers is standardized.

- Endpoints and URLs: Applications can access particular features or data by using endpoints, also known as URLs, which are usually provided by APIs. For instance, you can search for videos on YouTube using the https://www.googleapis.com/youtube/v3/search endpoint in the YouTube API.

- Data Format: JSON (JavaScript Object Notation) and XML are two typical formats used by APIs to exchange data. These formats organize the data in a way that both programs can understand.

2. The Significance of APIs

  • Facilitate Interconnectivity: APIs enable them to interact and cooperate Whether two systems are located on the same server or on different continents.

  • Encapsulate Complexity: Applications can request functionality or data using APIs without having to understand how the other application operates internally. For example, a weather app can simply ask a weather API for the current weather without having to understand how weather data is gathered.

  • Increase Functionality: APIs enable developers to include features from other platforms or services. For instance, an application may display a map using the Google Maps API rather than creating mapping features from the ground up.

3. Practical Applications of APIs

  • Social Media: To show social media content or enable sharing straight to Facebook, Instagram, or Twitter, many apps leverage their APIs.

  • Payment Processing: Online retailers can take payments without managing private financial information by using payment APIs, such as those offered by PayPal or Stripe.

  • Weather Data: The most recent weather data for any area may be retrieved and displayed by apps and websites using a weather API.

4. Types of APIs

  • Web APIs: Allow applications to communicate over the internet, often using HTTP requests. Examples include REST APIs and GraphQL.

  • Library APIs: Allow code libraries within a programming language to interact with each other, like a math library’s API in Python or JavaScript.

  • Operating System APIs: Allow applications to interact with the underlying operating system, like Windows API or iOS API.

5. REST APIs (Representational State Transfer)
REST APIs are a common type of web API that follow specific architectural principles, making them stateless and standardized. REST APIs operate over HTTP and are designed to work with resources represented as URLs.

Example: Making an API Request to a Weather Service

Imagine you want to know the weather in New York City. You could send an HTTP request to a weather API, like so:

Why is API knowledge necessary?

Understanding APIs (Application Programming Interfaces) is crucial for contemporary software development since they act as a link between various software systems, facilitating smooth functionality and communication. For the following reasons, it is essential to comprehend APIs:


1. Makes Work Easier
Through the use of integration APIs, developers can integrate features without having to start from scratch by allowing various apps or services to communicate with one another. For example:

  • To show videos on your website, use the YouTube API.

  • Incorporate payment gateways such as PayPal or Stripe.

  • Obtain meteorological information from outside sources.


2. Increases Output
Instead of having to start from scratch, the developer can concentrate on creating distinctive features for their apps by utilizing APIs.
For instance:

  • You can utilize APIs like OAuth or Firebase in place of developing a user authentication mechanism.
  • Time is saved by APIs that offer readily usable data and features, such as OpenWeather and Google Maps.

3. Facilitates Scalability
Applications can expand by adding functionality thanks to APIs without having to completely redo the system.
For instance:

  • Create a basic app first, then use the Google Analytics API to add features like user analytics.

  • Integrate third-party services to improve functionality while maintaining the app's flexibility and modularity.


4. Motivates Interoperability
Communication across different platforms, programming languages, and technologies is standardized by APIs. This guarantees that:

  • A React-developed front-end can communicate with Python or Node.js built back-end.
  • APIs allow data to be shared easily across IoT devices, web apps, and mobile apps.

5. Crucial to Contemporary Web Development
To provide dynamic and real-time functionality, the majority of contemporary web and mobile applications mostly rely on APIs:

  • Social media sharing and analytics APIs (Facebook, Twitter).

  • Cloud storage APIs for file management (e.g., Dropbox, Google Drive).

  • APIs for user customization, like Netflix's recommendation API or Spotify's playlist API.

In a nutshell
In today's digital ecosystem, APIs serve as the foundation for connectivity. Knowledge of APIs enables you to integrate, innovate, and grow effectively, making it a crucial ability for developers regardless of the size of the project or application.

Examples Of Scenarios API Can Be Use

Application Programming Interfaces, or APIs, are strong instruments that facilitate data sharing and communication across various software systems.
Here are five significant situations in which APIs can be applied:


1. Social Media Integration Scenario:
Users can sign in on a website or application using their Google, Twitter, or Facebook accounts.
Social media login APIs, such as the Google OAuth and Facebook Graph APIs, were utilized.

Benefits

  • It makes it easier for users to log in.
  • With permission from the user, it enables developers to safely retrieve user profile data.

2. Applications of Weather
Situation: Real-time weather data for locations is shown on a travel app.
Weather APIs, such as OpenWeatherMap and WeatherStack, were utilized.

Benefits

  • Current weather information, such as temperature, humidity, and predictions, is provided.
  • Location-based weather services are made possible.

3. Gateways for payments
Situation: Consumers can use digital wallets like PayPal or Stripe or credit/debit cards to make payments on an e-commerce site.

Payment APIs, such as PayPal and Stripe, were utilized.
Benefits

  • Facilitates safe online transaction processing.
  • Features like fraud detection and recurring payments are supported.

4. Location and Map Services
Situation: A food delivery app watches the delivery driver in real-time and displays the customer's position.
Mapbox and Google Maps are two examples of mapping APIs that are used.

Benefits

  • Provides real-time tracking, route optimization, and geolocation.
  • Interactive maps improve the user experience.

5. Platforms for E-Learning
Scenario: A virtual meeting tool for live courses and video conferencing is integrated into an online learning platform.
Video communication APIs, such as the Zoom and Twilio APIs, were utilized.

Benefits

  • It makes it possible to arrange and schedule live classes with ease.
  • Offers live chat, transcribing, and recording features.

The Reasons APIs Are Essential
APIs make development easier, improve functionality, and guarantee effective service-to-service communication. Instead of starting from scratch, they enable developers to concentrate on generating distinctive features.

Step By Step Process On Building The YouTube Connection Project

Now this is the part we’ve been waiting for. Let’s Go…

So Note that the YouTube Data API is used to retrieve video data and present it on a webpage when building a YouTube API connection project using vanilla JavaScript. Here is a straightforward, step-by-step setup tutorial for this project.

1. Set Up Your Google API Key

  1. Visit the Google Cloud Console. then you’ll see the interface below, that says welcome! the that will take you to the next step.
  2. Create a new project or select an existing one.
    from the image below we created a new project that gave us this view, now you’ll move to the next step.
    Emmykolic’s Snippet

  3. Go to APIs & Services as shown below, and then it will take you to a page with a diagram that looks like statistics. Make sure you are meticulous about this, cause we're getting there…
    Emmykolic’s Snippet

On that page, look at the left side of your screen. You’ll see > Library. Click on it, and it will take you to a fresh-looking page, where you can search for any API Library of your choice. See the image below for more explanation.

Emmykolic’s Snippet

You will search "YouTube Data API v3" in the search bar as displayed below.

Emmykolic’s Snippet

When you click enter for search, you will get the YouTube Data API, this is the API we need which will enable us to make the API connection in our Local Project. The Image Below is an example of what you’ll see after searching…

Emmykolic’s Snippet

After the searching, you’ll click on the YouTube Icon and it will bring you here, all you have to do is to Enable the API, by clicking the Enable Button. As shown Below.

Emmykolic’s Snippet

After enabling the API you click on the Credentials link it’s usually by the left side of your screen directly under where you have Library.
There, you will see the YouTube API you just Generated. where the arrow in the image is pointing. You then click on SHOW KEY the API key will pop up and you will now copy it and keep it somewhere safe in case of implementing it soon.

But note that API Key 1 has a warning beside it, which means your API is not restricted to only the use of YouTube API, and leaving it like that could be very dangerous, so it needs restriction let’s go...

Emmykolic’s Snippet

So to remove the warning sign what we will do is to click on the word API Key. The word is a Link that will take us to a page where we can make some changes, when you get to the new page scroll down you’ll see a section called API Restrictions.

By default it’s in the Don’t restrict key checkbox, you’ll change it and click on the Restrict Key.

As shown Below.

Emmykolic’s Snippet

Immediately a dropdown will display and you will click on the YouTube Data API v3 and then click the ok right beneath the dropdown. After that, you’ll now click on the save button below.

Emmykolic’s Snippet

Immediately you save, it will take you back to the page you were coming from, but this time with a green verified-looking badge. The moment you follow these steps you are good to go.

The image below is the last step. so from here, it’s to make use of the API key you copied, you’ll need it to authenticate requests.

Emmykolic’s Snippet

  1. Basic HTML Structure

Start with a simple HTML structure where you’ll display search results or video information.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>YouTube API Project</title>
  <style>
    /* Basic styling */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    #search-container {
      margin-top: 20px;
    }
    .video {
      margin: 15px 0;
    }
  </style>
</head>
<body>
  <h1>YouTube Video Search</h1>
  <div id="search-container">
    <input type="text" id="query" placeholder="Search for videos" />
    <button onclick="searchVideos()">Search</button>
  </div>
  <div id="results"></div>

  <script src="index.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

3. Make the app.js JavaScript file.
Write the JavaScript code in app.js to communicate with the YouTube API and retrieve video information.

Step-by-Step Code

Establish Your API Key: Specify the YouTube Data API's base URL.
Describe the search. Videos Function: Retrieve videos in response to user queries.
Display Results: Include the video results in the HTML #results div.

Here's how to accomplish it:
Below is the Javascript controlling it. Note: the API_KEY below will be replaced with the copied API_KEY from your YouTube API


// app.js

const API_KEY = 'AIzaSyDGpbbfEO5x89tDGePuCRD8kaev4B26y7Q'; // Replace with your actual API key
const BASE_URL = 'https://www.googleapis.com/youtube/v3/search';

async function searchVideos() {
  const query = document.getElementById('query').value;

  try {
    const response = await fetch(`${BASE_URL}?part=snippet&q=${query}&type=video&key=${API_KEY}`);
    const data = await response.json();

    if (response.ok) {
      displayResults(data.items);
    } else {
      console.error('Error fetching videos:', data.error.message);
    }
  } catch (error) {
    console.error('Network error:', error);
  }
}

function displayResults(videos) {
  const resultsContainer = document.getElementById('results');
  resultsContainer.innerHTML = ''; // Clear previous results

  videos.forEach((video) => {
    const videoElement = document.createElement('div');
    videoElement.classList.add('video');

    videoElement.innerHTML = `
      <h3>${video.snippet.title}</h3>
      <img src="${video.snippet.thumbnails.medium.url}" alt="${video.snippet.title}" />
      <p>${video.snippet.description}</p>
      <a href="https://www.youtube.com/watch?v=${video.id.videoId}" target="_blank">Watch Video</a>
    `;

    resultsContainer.appendChild(videoElement);
  });
}
Enter fullscreen mode Exit fullscreen mode
  1. Key Parts Explained

  2. API Endpoint and Parameters: BASE_URL, the part parameter (snippet for title, description, and thumbnails), and the q parameter for the search query are used to create the URL endpoint.

To obtain just video results, use type=video filters.

  1. Show Results:
  2. You may utilize the snippet.title, snippet.thumbnails, and snippet.description that are included in each video object to fill in the HTML.
  3. Linking to the YouTube video URL is aided by the video.id.videoId.

  4. Managing Errors: Try-catch ensures that API and network errors are detected and recorded.


  1. Execute and Evaluate Your Project
  • Launch a web browser and open the index.html file.
  • Click "Search" after entering a search word. The results container will show the results.

Advice for Improvement

  • To retrieve additional results, use pagination.
  • While the data is being retrieved, use a loading indication.
  • Use more filters, such as publication date or relevance sorting.

With just vanilla JavaScript, this configuration offers a simple yet useful YouTube API connection project!

Here’s the result I got.

Emmykolic’s Snippet

without searching anything you’ll see this, then you search for anything of your choice. As long as it’s on YouTube you’ll see it.
Below I searched for Nickelodeon, and here’s the result.

Emmykolic’s Snippet

After searching, you’ll get the above interface as your result. You can go ahead and find anything you wish. Note that this can be customized to whatever you want in your projects.

Conclusion

An enjoyable method to improve your knowledge of APIs and asynchronous programming is to create a YouTube API connection project with vanilla JavaScript. Following this tutorial, you now know how to:

  1. Use an API key to set up and use the YouTube Data API.
  2. Use' fetch' To handle asynchronous data and make API queries.
  3. Display the retrieved video results by dynamically updating the DOM.
  4. Put error management into practice to guarantee a seamless user experience.

This project shows how powerful JavaScript and APIs are for creating dynamic, data-driven websites. To make the project more aesthetically pleasing and user-friendly, think about incorporating features like pagination, sophisticated search filters, or design improvements as you work on it.

Investigating and implementing these concepts can distinguish your project and strengthen your front-end web development abilities.

But for now, see you next time…

About The Author

Full-stack Laravel developer Emmanuel Okolie has 4+ years of experience in software development. He has developed full-fledged skills by combining software development, writing, and instructing others in what he does.
His stacks include ReactJs Laravel PHP JavaScript, and other languages and frameworks.
As a freelancer, he creates websites for clients and writes technical guides to show people how to do what he does.
If given the chance, Emmanuel Okolie would enjoy speaking with you. Please follow him on his website, Github, LinkedIn, and Twitter.

Top comments (0)