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.
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
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.
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.
Let’s build a simple React YouTube app. In the end, it will be able to:
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:
npx create-react-app react-youtube-app --use-npm
cd react-youtube-app
npm start
Keep both the placeholder page and your code editor open in the background, we’ll come back to them in just a bit.
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.
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.
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:
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:
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.
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:
search()
function that calls our searchYouTube
function.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; }
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.
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!
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.
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.
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.
We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…
Are you curious about what your API consumers are searching for? Is your Hub effectively…
The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…
This January's release brings exciting features and improvements designed to empower you and your developers.…
Rapid API is committed to providing its users with the best possible experience, and the…
In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…