Embed a YouTube channel's current live stream without the video ID
If you know the ID of a YouTube channel, and if that channel streams a livestream set to Public, an iframe with this URL will show it:
https://www.youtube.com/embed/live_stream?channel=YOUR_CHANNEL_ID_HERE
See https://stackoverflow.com/a/39582176/470749
Unfortunately I haven't found a similarly simple way to permanently embed the YouTube chat for that livestream.
As far as I can tell, there's nothing built into the YouTube API that would allow you to embed a channel's current live stream automatically without knowing its ID. That said, it's possible to implement this yourself by writing a custom API and hosting it on your own server.
I recognize that this can look like a daunting task, so I've laid out some rough steps below to get you started.
- Set up an endpoint on your own server. You could accept a
channelId
argument or hard-code one, depending on how extensible you want this to be. - Query YouTube's
search
endpoint1 for the specifiedchannelId
andeventType=live
. An HTTPS request for this will look something like this:https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=[CHANNEL_ID]&eventType=live&maxResults=1&order=date&type=video&key=[YOUR_API_KEY]
- Check the
search
JSON response. If it returns any results (data.pageInfo.totalResults > 0
), you know that the channel is live. - If the channel is live, redirect the request to your server directly to the live video's embed URL based on the video's ID in the query response (
data.items[0].id.videoId
). - If the channel isn't live, create a placeholder as you see fit, or make a second request to search for
eventType=completed
for past broadcasts,eventType=upcoming
for scheduled broadcasts, or remove theeventType
parameter to get the most recent video.
Once you have a server that can respond and redirect requests, you can embed an iFrame in your page that points directly to your API URL. Your server will handle the logic and, using the redirect, change the iFrame to a YouTube video player automatically, without requiring you to perform client-side logic or expose your API key2.
1 As with all YouTube API requests, search#list
queries will count towards your daily quota. If you intend for this to be a high-traffic endpoint, you could either request an increased quota from YouTube, or implement a caching solution on your end to cut down on the number of requests you make.
2 GCP (Google Cloud Platform), which you'll use to manage your access the YouTube Data API, has pretty good protections against API key theft for times when you do have to expose it on the client side. That being said, best practice is to keep your key secret by storing it only on the server whenever possible.