title: How to write a JavaScript download function in my YouTube MP4 & MP3 Downloader
body: <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// put your own value below!
  const apiKey = "AIzaSyCGKrLxvpot6hrekFHQTPaCGeOFj92T3ao";
  const searchURL = "https://www.googleapis.com/youtube/v3/search";
  
  function formatQueryParams(params) {
    const queryItems = Object.keys(params).map(
      key =&gt; `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
    );
    return queryItems.join("&amp;");
  }
  
  function displayResults(responseJson) {
    // if there are previous results, remove them
    console.log(responseJson);
    $("#results-list").empty();
    // iterate through the items array
    for (let i = 0; i &lt; responseJson.items.length; i++) {
      // for each video object in the items
      //array, add a list item to the results
      //list with the video title, description,
      //and thumbnail
      $("#results-list").append(
        `&lt;li&gt;&lt;h3&gt;${responseJson.items[i].snippet.title}&lt;/h3&gt;
        &lt;p&gt;${responseJson.items[i].snippet.description}&lt;/p&gt;
        &lt;img src='${responseJson.items[i].snippet.thumbnails.default.url}'&gt;
        &lt;/li&gt;`
      );
    }
    //display the results section
    $("#results").removeClass("hidden");
  }
  
  async function downloadVideo(videoId) {
    console.log(videoId);
    const response = await fetch(`https://getvideo.p.rapidapi.com/?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D${videoId}`, {
      headers: {
        "X-RapidAPI-Host": "getvideo.p.rapidapi.com",
        "X-RapidAPI-Key": "d390d7b0e9msh42dc09f4e07e285p1486c4jsne0a4edb9e61e"
      }
    });
    const data = await response.json();
    return {
      audio: data.streams.filter(stream =&gt; {
        return stream.format === "audio only";
      })[0].url,
      video: data.streams.filter(stream =&gt; {
        return stream.format !== "audio only";
      })[0].url
    };
  }
  
  function getYouTubeVideos(query, maxResults = 50) {
    const params = {
      key: apiKey,
      q: query,
      part: "snippet",
      maxResults,
      type: "video"
    };
    const queryString = formatQueryParams(params);
    const url = searchURL + "?" + queryString;
  
    console.log(url);
  
    fetch(url)
      .then(response =&gt; {
        if (response.ok) {
          return response.json();
        }
        throw new Error(response.statusText);
      })
      .then(responseJson =&gt; downloadVideo(responseJson.items[0].id.videoId))
      .then(download =&gt; console.log(download))
      // .then(responseJson =&gt; displayResults(responseJson))
      .catch(err =&gt; {
        $("#js-error-message").text(`Something went wrong: ${err.message}`);
      });
  }
  
  function watchForm() {
    $("form").submit(event =&gt; {
      event.preventDefault();
      const searchTerm = $("#js-search-term").val();
      const maxResults = $("#js-max-results").val();
      getYouTubeVideos(searchTerm, maxResults);
    });
  }
  
  $(watchForm);</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
    &lt;head&gt;
      &lt;meta charset="UTF-8" /&gt;
      &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;
      &lt;meta http-equiv="X-UA-Compatible" content="ie=edge" /&gt;
      &lt;title&gt;YouTube video finder&lt;/title&gt;
      &lt;link rel="stylesheet" href="style\style.css" /&gt;
      &lt;link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
      /&gt;
      &lt;script
        src="https://code.jquery.com/jquery-3.3.1.js"
        integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
        crossorigin="anonymous"
      &gt;&lt;/script&gt;
    &lt;/head&gt;
  
    &lt;body&gt;
      &lt;div class="container"&gt;
        &lt;div class="left"&gt;
          &lt;h1 class="finder-heading"&gt;Download a YouTube video&lt;/h1&gt;
          &lt;form id="js-form"&gt;
            &lt;label for="search-term"&gt;&lt;/label&gt;
            &lt;input
              class="search-input"
              type="text"
              name="search-term"
              id="js-search-term"
              required
              placeholder="Search YouTube Videos..."
            /&gt;
  
            &lt;label for="max-results"&gt;&lt;/label&gt;
            &lt;input
              class="max-number"
              type="number"
              name="max-results"
              id="js-max-results"
              value="10"
            /&gt;
  
            &lt;input class="go-button" type="submit" value="Search" /&gt;
          &lt;/form&gt;
        &lt;/div&gt;
  
        &lt;!-- &lt;div class="right"&gt;
          &lt;h1 class="downloader-heading"&gt;Download a YouTube video&lt;/h1&gt;
          &lt;input class="URL-input" placeholder="Paste YouTube link here..." /&gt;
          &lt;button class="download-button"&gt;
            &lt;i class="fa fa-download"&gt;&lt;/i&gt; Download
          &lt;/button&gt;
        &lt;/div&gt; --&gt;
  
        &lt;p id="js-error-message" class="error-message"&gt;&lt;/p&gt;
        &lt;section id="results" class="hidden"&gt;
          &lt;h2&gt;Search results&lt;/h2&gt;
          &lt;ul id="results-list"&gt;&lt;/ul&gt;
        &lt;/section&gt;
      &lt;/div&gt;
      &lt;script src="apps\app.js"&gt;&lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>I am making a web app that is using a 2 API mashup of both youtube API and GET Video and Audio URL API. The problem that I am having is that I don't know how to code the javascript needed in the download portion in this project... </p>
  
  <p>For the moment I have the javascript coded to a point where if you run it and inspect in google chrome you will see in the console how it captures both the audio file and video file of whatever video link you choose to insert into the input. </p>
  
  <p>I expect for this to capture the video produce a thumbnail in the HTML with a given option of downloading MP4 or MP3</p>