How to use YouTube APIs

YouTube has become a very popular platform since its launch over a decade ago. It’s a great source of self-education videos, such as “how-tos”, and a great source of entertainment videos, such as “best of” videos for classical music.

By using YouTube APIs, you can access this wealth of content within your applications. Whether you want to make a full-featured search app, or just add a link to relevant videos to complement your main content, YouTube APIs can really enhance your product.

In this blog post, we’re going to take a look at how to use YouTube APIs within your React app.

Connect to the Youtube API

What is React?

React is a new JavaScript framework that simplifies the process of making complex, interactive websites and web apps. In React, you write React Components that focus on what your code should look like, rather than how it should get to that point. In other words, React lets you focus on the what, rather than the how.

Tip: New to React? Check out How to use an API with ReactJS

What are React Hooks?

React Hooks are a new way to write React Components that manage their own data, or “state”. In the early days of React, you’d have to create a JavaScript class and call a method this.setState to change state. Now, Hooks make this process much more convenient.

For example, if you wanted to store state for a string representing someone’s name, with a default value of “Bob”, you might have the following code:

function MyComponent() {
  const [name, setName] = React.useState("Bob");
  // ...
}

In this code, we used React Hooks to create the name and setName variables. The name variable will be the current value of the name when rendering your React Component. You can use the setName function to change this value, whether from an async function or an event handler.

What are Async Functions?

In JavaScript, Async Functions are a convenient way to write asynchronous code that looks and reads linearly. Async functions return a Promise, and all Promises can be waited for inside an async function using await syntax. For more information, see this article on Async/await in JavaScript.

Connect to the Youtube API

How to build a YouTube React app

Let’s build a simple React YouTube app. In the end, it will be able to:

  1. Let a user type a search string into an input field.
  2. Start a search using a typical button element.
  3. Call a YouTube API from React, returning a list of videos.
  4. Store this video list in our App Component.
  5. Link to each video in a compact, attractive HTML card.

Step 1: Setup a new React app

To make things very easy on ourselves, let’s use Create React App. This is a command-line utility (CLI) created by Facebook that simplifies the process of creating a new React app. It takes care of everything for us, from integrating the testing framework, to running the development server.

So let’s set that up now:

  1. Make sure to install NPM if you don’t already have it installed.
  2. Open your favorite command line terminal.
  3. Run the command npx create-react-app react-youtube-app --use-npm
  4. Go into that directory with cd react-youtube-app
  5. Open the directory in your favorite code editor, such as Visual Studio Code.
  6. Start the project by typing npm start
  7. A placeholder web page will open up at http://localhost:3000

Keep both the placeholder page and your code editor open in the background, we’ll come back to them in just a bit.

Step 2: Subscribe to YouTube Search API

For our purposes, we’re going to use YouTube Search Results API. Head on over to that page and you’ll see that it’s a very simple API to use: you give it a search string, and it returns an array of search results that match.

There is a small fee for the higher tiers of this API, but we’re going to use the Basic tier, which has a small quota of 100 requests per day. This tier is perfect for us, since it lets us test out the API for free, to see how it’s used in practice.

So click on the Pricing tab on this page, and subscribe to the Basic plan. If you don’t already have a RapidAPI account, now’s a good time to get one. It’s free, and you get instant access to numberless APIs and their API Keys.

Connect to the Youtube API

Step 3: Test the API Endpoint

Now that we’re all subscribed, head back on over to the Endpoints tab, and let’s try it out!

Notice that there’s only one required parameter, called q. This is a typical name for search (or “query”) parameters.

So let’s fill that in with some sample data:

And then click Test Endpoint to try the API out:

Now, in the Results tab, you should see JSON data that look something like this:

Great! This API returns something we can work with. For each video item, we have:

  • title of the video.
  • link to the video on YouTube.
  • description of what the video is, in brief.
  • thumbnail as a link to the video’s image.
  • author with name and ref as a link to their page.
  • views, duration, and uploaded_at as interesting metadata.

Note: The type key of each item is not always "video"! But we’re only concerned with videos for now.

Step 4: Copy the JavaScript code

In order to use this API in our React app, we’ll need some code to work with. Fortunately, RapidAPI gives us quick access to this, via the Code Snippets tab on the right:

  1. Click the Code Snippets tab.
  2. Open the language drop-down.
  3. Choose the JavaScript option.
  4. Select fetch in the JavaScript sub-menu.

We’re using fetch because it’s the easiest and shortest code, and it works great with async functions. This makes it a perfect match for React.

Note: Modern browsers natively support the fetch() function. But if you’re supporting a much older browser, you’ll need a fetch polyfill.

But this code isn’t useful by itself. We’ll need to turn it into a reusable function, specifically an async function.

For your convenience, I’ve done just that. Remember when I said we’ll come back to our IDE? Open it back up, find the src/App.js file, and paste the code below somewhere into it:

async function searchYouTube(q) {
  q = encodeURIComponent(q);
  const response = await fetch("https://youtube-search-results.p.rapidapi.com/youtube-search/?q=" + q, {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "youtube-search-results.p.rapidapi.com",
      "x-rapidapi-key": /* Paste your RapidAPI key here. */    }
  });
  const body = await response.json();
  console.log(body);
  return body.items.filter(item => item.type === 'video');
}

This function does a few things:

  • Takes the query string as a parameter, URI-encodes it, and appends it to the API’s URL.
  • Uses await syntax to get the response and get JSON from out of the response’s body.
  • Returns the items key, filtering out everything except items with a type key of "video".

Tip: Make sure to include your RapidAPI key in the example above, on line 7, or it won’t compile! You can find your RapidAPI key in the original code snippet that we copied just a minute ago.

Connect to the Youtube API

Step 5: Replace the React App Component

Now that we have a powerful new async function for searching YouTube, let’s use it in our new React component!

Replace the App component in src/App.js with the following code:

function App() {
  const [query, setQuery] = React.useState('European history');
  const [list, setList] = React.useState(null);

  const search = (e) => {
    e.preventDefault();
    searchYouTube(query).then(setList);
  };

  return (
    <div className="app">
      <form onSubmit={search}>
        <input autoFocus value={query} onChange={e => setQuery(e.target.value)} />
        <button>Search YouTube</button>
      </form>
      {list &&
        (list.length === 0
          ? <p>No results</p>
          : (
            <ul className="items">
              {list.map(item => (
                <li className="item" key={item.id}>
                  <div>
                    <b><a href={item.link}>{item.title}</a></b>
                    <p>{item.description}</p>
                  </div>
                  <ul className="meta">
                    <li>By: <a href={item.author.ref}>{item.author.name}</a></li>
                    <li>Views: {item.views}</li>
                    <li>Duration: {item.duration}</li>
                    <li>Uploaded: {item.uploaded_at}</li>
                  </ul>
                  <img alt="" src={item.thumbnail} />
                </li>
              ))}
            </ul>
          )
        )
      }
    </div>
  );
}

This is a very straightforward code. All we do is:

  1. Store the query string and the list of YouTube videos in-state using React Hooks.
  2. Create a search() function that calls our searchYouTube function.
  3. Set the result of our YouTube search to the new list variable using our setList setter.
  4. After the search has finished, show it in the view, displaying only the interesting properties.

Step 6: Add our own CSS styling code

Our app works, but it’s not pretty. But thanks to modern CSS, it only takes a small amount of effort to make a huge difference.

So open up src/App.css and replace the contents with the following CSS:

body {
  background: #f7f7f7;
}

.app {
  width: 36em;
  margin: 3em;
}

form {
  display: grid;
  grid-template-columns: 1fr auto;
  gap: 1em;
  margin-bottom: 1em;
}

button {
  background: #17f;
  color: #fff;
  font: inherit;
  border: none;
  border-radius: 3px;
  outline: none;
  padding: 0.5em 1.5em;
}
button:active { background-color: #05b; }

input {
  border: 1px solid #999;
  border-radius: 3px;
  font: inherit;
  padding: 0.5em;
  outline: none;
}
input:focus { outline: auto #17f; }

ul {
  list-style-type: none;
  padding-left: 0;
}

.items {
  display: grid;
  gap: 1em;
}

.item {
  background: #fff;
  padding: 1em;
  border-radius: 6px;
  box-shadow: 0px 1px 6px 2px #0002;
  transition: transform 100ms ease-in-out;

  display: grid;
  gap: 1em;
  grid-template:
    "d i"
    "m m";
}
.item:hover { transform: scale(1.02); }
.item div { grid-area: d; }
.item img { grid-area: i; }
.item ul  { grid-area: m; }

.meta {
  display: grid;
  grid-auto-flow: column;
  gap: 2em;

  font-size: 80%;
  color: #555;
}

Step 7: Try it out!

Now open your page back up, and try it out with your favorite topic.

You should see something like this:

Beautiful! We made a professional-looking YouTube app, with almost no effort, all thanks to React and our YouTube Search API.

Connect to the Youtube API

Conclusion

Using React makes it extremely easy to create attractive, user-friendly, and powerful apps and websites in a very little time. When combining this with the right APIs, we can make professional, real-world apps that provide serious value to users.

For extra credit, try handling types of items other than "video", and see if you can make a full-featured YouTube app!

FAQ

How do you use an API in React?

Using APIs in React is easy. APIs work like function calls: you make a request, and get a response back. In React, there are two main places to make API calls: in callbacks, like onClick handlers, or in lifecycle events, such as useEffect.

Is there a YouTube API?

YouTube has its own official developer API, which you can access through YouTube.com. On top of that, there are many APIs available on RapidAPI.com which provide easy and quick access to videos, playlists, and other YouTube content.

How do I embed a YouTube video in React?

Embedding a YouTube video in React is actually very easy: using an NPM library like react-youtube, you can embed any video into your React component tree using a YouTube component. All you need is the video ID.

5 / 5 ( 1 vote )
Steven

With over a decade of professional front-end experience, Steven uses his accumulated knowledge and experience to write instructive technical articles about the latest technologies such as JavaScript, TypeScript, React.js, and many APIs.

Share
Published by

Recent Posts

API Testing Tutorial: API Testing with RapidAPI

What is API Testing? API testing is a type of software testing that involves testing application programming interfaces (APIs) directly…

7 days ago

Test APIs From Development to Deployment with RapidAPI Testing

We are excited to introduce RapidAPI Testing — a functional API testing solution for creating…

1 week ago

Build a Influencer Search App with Ruby on Rails

Internet search has gone way beyond the traditional web search. Thanks to other mediums of…

4 weeks ago

React API Authentication & Authorization

Introduction Security on the internet comes under scrutiny the more our personal lives and business…

4 weeks ago

How to use WordPress with React (WordPress React API Tutorial)

WordPress WordPress claims to be, "the world’s most popular website builder" based on the statistic…

1 month ago

How to use an E-mail API with JavaScript

Introduction This tutorial will show you how to use JavaScript to call an API to…

1 month ago