How to check if YouTube channel is streaming live - youtube

I can't find any informations to check if a YouTube channel is actually streaming or not.
With Twitch you just need the channel name, and with the API you can check if there is a live or not.
I don't want to use OAuth, normally a public API key is enough. Like checking the videos of a channel I want to know if the channel is streaming.

You can do this by using search.list and specifying the channel ID, setting the type to video, and setting eventType to live.
For example, when I searched for:
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCXswCcAMb5bvEUIDEzXFGYg&type=video&eventType=live&key=[API_KEY]
I got the following:
{
"kind": "youtube#searchListResponse",
"etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/gE5P_aKHWIIc6YSpRcOE57lf9oE\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/H-6Tm7-JewZC0-CW4ALwOiq9wjs\"",
"id": {
"kind": "youtube#video",
"videoId": "W4HL6h-ZSws"
},
"snippet": {
"publishedAt": "2015-09-08T11:46:23.000Z",
"channelId": "UCXswCcAMb5bvEUIDEzXFGYg",
"title": "Borussia Dortmund vs St. Pauli 1-0 Live Stream",
"description": "Borussia Dortmund vs St. Pauli Live Stream Friendly Match.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/W4HL6h-ZSws/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/W4HL6h-ZSws/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/W4HL6h-ZSws/hqdefault.jpg"
}
},
"channelTitle": "",
"liveBroadcastContent": "live"
}
}
]
}

The search-method (https://www.googleapis.com/youtube/v3/search) is awfully expensive to use though. It costs 100 quota units (https://developers.google.com/youtube/v3/determine_quota_cost) out of the 10,000 you have by default.
This means you only get 100 requests per day which is terrible.
You could request an increase in the quota but that seems like brute forcing the the problem.
Is there really no other simpler method?

I know this is old, but I figured it out myself with PHP.
$API_KEY = 'your api3 key';
$ChannelID = 'the users channel id';
$channelInfo = 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId='.$ChannelID.'&type=video&eventType=live&key='.$API_KEY;
$extractInfo = file_get_contents($channelInfo);
$extractInfo = str_replace('},]',"}]",$extractInfo);
$showInfo = json_decode($extractInfo, true);
if($showInfo['pageInfo']['totalResults'] === 0){
echo 'Users channel is Offline';
} else {
echo 'Users channel is LIVE!';
}

Guys I found better way to do this. Yes, it requires you to make GET requests to a YouTube page and parse HTML, but it will work with newer versions + works with consent + works with captcha (most likely, 90%)
All you need to do is make a request to https://youtube.com/channel/[CHANNELID]/live and check the href attribute of the <link rel="canonical" /> tag.
For example,
<link rel="canonical" href="https://www.youtube.com/channel/UC4cueEAH9Oq94E1ynBiVJhw">
means there is no livestream, while
<link rel="canonical" href="https://www.youtube.com/watch?v=SR9w_ofpqkU">
means there is a stream, and you can even fetch its data by videoid.
Since canonical URL is very important for SEO and redirect does not work in GET or HEAD requests anymore, I recommend using my method.
Also here is the simple script I use:
import { parse } from 'node-html-parser'
import fetch from 'node-fetch'
const channelID = process.argv[2] // process.argv is array of arguments passed in console
const response = await fetch(`https://youtube.com/channel/${channelID}/live`)
const text = await response.text()
const html = parse(text)
const canonicalURLTag = html.querySelector('link[rel=canonical]')
const canonicalURL = canonicalURLTag.getAttribute('href')
const isStreaming = canonicalURL.includes('/watch?v=')
console.log(isStreaming)
Then run npm init -y && npm i node-html-parser node-fetch to create project in working directory and install dependencies
Then run node isStreaming.js UC4cueEAH9Oq94E1ynBiVJhw and it will print true/false (400-600 ms per one execution)
It does require you to depend on node-html-parser and node-fetch, but you can make requests with the built-in HTTP library (which sucks) and rewrite this to use regex. (Do not parse HTML with regex.)

I was also struggling with API limits. The most reliable and cheapest way I've found was simply a HEAD request to https://www.youtube.com/channel/CHANNEL_ID/live. If the channel is live then it will auto load the stream. If not then it will load the channels videos feed. You can simply check the Content-Length header size to determine which. If live the size is almost 2x when NOT live.
And depending on your region you might need to accept the cookies consent page. Just send your request with cookies={ "CONSENT": "YES+cb.20210420-15-p1.en-GB+FX+634" }.

if you point streamlink at a https://www.youtube.com/channel/CHANNEL_ID/live link, it will tell you if it is live or not
e.g. lofi beats is usually live,
$ streamlink "https://www.youtube.com/channel/UCSJ4gkVC6NrvII8umztf0Ow/live"
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/channel/UCSJ4gkVC6NrvII8umztf0Ow/live
Available streams: 144p (worst), 240p, 360p, 480p, 720p, 1080p (best)
whereas MKBHD is not
$ streamlink "https://www.youtube.com/c/mkbhd/live"
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/c/mkbhd/live
error: Could not find a video on this page

The easisest way that I have found to this has been scraping the site. This can be done by finding this:
<link rel="canonical" href="linkToActualYTLiveVideoPage">
as in Vitya's answer.
This is my simple Python code using bs4:
import requests
from bs4 import BeautifulSoup
def is_liveYT():
channel_url = "https://www.youtube.com/c/LofiGirl/live"
page = requests.get(channel_url, cookies={'CONSENT': 'YES+42'})
soup = BeautifulSoup(page.content, "html.parser")
live = soup.find("link", {"rel": "canonical"})
if live:
print("Streaming")
else:
print("Not Streaming")
if __name__ == "__main__":
is_liveYT()
It is pretty weird, honestly, that YouTube doesn't have a simple way to do this through the API, although this is probably easier.

I found the answer by #VityaSchel to be quite useful, but it doesn't distinguish between channels which have a live broadcast scheduled, and those which are broadcasting live now.
To distinguish between scheduled and live, I have extended his code to access the YouTube Data API to find the live streaming details:
import { parse } from 'node-html-parser'
import fetch from 'node-fetch'
const youtubeAPIkey = 'YOUR_YOUTUBE_API_KEY'
const youtubeURLbase = 'https://www.googleapis.com/youtube/v3/videos?key=' + youtubeAPIkey + '&part=liveStreamingDetails,snippet&id='
const c = {cid: process.argv[2]} // process.argv is array of arguments passed in console
const response = await fetch(`https://youtube.com/channel/${c.cid}/live`)
const text = await response.text()
const html = parse(text)
const canonicalURLTag = html.querySelector('link[rel=canonical]')
const canonicalURL = canonicalURLTag.getAttribute('href')
c.live = false
c.configured = canonicalURL.includes('/watch?v=')
if (!c.configured) process.exit()
c.vid = canonicalURL.match(/(?<==).*/)[0]
const data = await fetch(youtubeURLbase + c.vid).then(response => response.json())
if (data.error) {
console.error(data)
process.exit(1)
}
const i = data.items.pop() // pop() grabs the last item
c.title = i.snippet.title
c.thumbnail = i.snippet.thumbnails.standard.url
c.scheduledStartTime = i.liveStreamingDetails.scheduledStartTime
c.live = i.liveStreamingDetails.hasOwnProperty('actualStartTime')
if (c.live) {
c.actualStartTime = i.liveStreamingDetails.actualStartTime
}
console.log(c)
Sample output from the above:
% node index.js UCNlfGuzOAKM1sycPuM_QTHg
{
cid: 'UCNlfGuzOAKM1sycPuM_QTHg',
live: true,
configured: true,
vid: '8yRgYiNH39E',
title: '🔴 Deep Focus 24/7 - Ambient Music For Studying, Concentration, Work And Meditation',
thumbnail: 'https://i.ytimg.com/vi/8yRgYiNH39E/sddefault_live.jpg',
scheduledStartTime: '2022-05-23T01:25:00Z',
actualStartTime: '2022-05-23T01:30:22Z'
}

Every YouTube channel as a permanent livestream, even if the channel is currently not actively livestreaming. In the liveStream resource, you can find a boolean named isDefaultStream.
But where can we get this video (livestream) id? Go to https://www.youtube.com/user/CHANNEL_ID/live, right click on the stream and copy the video URL.
You can now make a GET request to
https://youtube.googleapis.com/youtube/v3/videos?part=liveStreamingDetails&id=[VIDEO_ID]&key=[API_KEY] (this request has a quota cost of 1 unit, see here)
This will be the result if the stream is currently active/online.
{
"kind": "",
"etag": "",
"items": [
{
"kind": "",
"etag": "",
"id": "",
"liveStreamingDetails": {
"actualStartTime": "",
"scheduledStartTime": "",
"concurrentViewers": "",
"activeLiveChatId": ""
}
}
],
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
}
}
If the stream is currently offline, the property concurrentViewers will not exist. In other words, the only difference between an online and offline livestream is that concurrentViewers is present or not present. With this information, you can check, if the channel is currently streaming or not (at least for his default stream).

I found youtube API to be very restrictive given the cost of search operation. Web scraping with aiohttp and beautifulsoup was not an option since the better indicators required javascript support. Hence I turned to selenium. I looked for the css selector
#info-text
and then search for the string Started streaming or with watching now in it.
You can run a small API on heroku with flask as well.

Related

how do I get youtube shorts from youtube api data v3

I want a way to get YouTube shorts for a specific channel from YouTube API. I looked every where and I couldn't find anything.
Currently I can get a playlist ID for all channel videos with this endpoint:
request = youtube.channels().list(
part="contentDetails",
id=id
)
I also tried these parameters:
request = youtube.channels().list(
part="snippet,contentDetails,statistics,brandingSettings",
id=id
)
So is there a way to get YouTube shorts from a specific channel from YouTube API or any other source if it's available.
One way of detecting if a YouTube video ID is a Short without even using the API is to try a HEAD HTTP request to the /shorts/ version of the URL and see if it redirects you.
https://www.youtube.com/shorts/hKwrn5-7FjQ is a Short and if you visit that URL, you'll get an HTTP status code of 200 and the URL won't change.
https://www.youtube.com/watch?v=B-s71n0dHUk is not a Short, and if you visit https://www.youtube.com/shorts/B-s71n0dHUk, you get a 303 redirect back to the original URL.
Keep in mind, that this behavior might change down the line, but it works as of May 2022.
It seems that once again YouTube Data API v3 doesn't provide a basic feature.
For checking if a given video is a short:
I would recommend you to use my open-source YouTube operational API. Indeed by requesting the JSON document https://yt.lemnoslife.com/videos?part=short&id=VIDEO_ID containing item["short"]["available"] boolean, your problem is solved.
Example of short id: ydPkyvWtmg4
For listing shorts of a channel:
I would recommend you to use my open-source YouTube operational API. Indeed by requesting the JSON document https://yt.lemnoslife.com/channels?part=shorts&id=CHANNEL_ID. The entry item["shorts"] contains the data you are looking for. Note that the pagination works as the one of YouTube Data API v3.
Example of result for channel UC5O114-PQNYkurlTg6hekZw:
{
"kind": "youtube#channelListResponse",
"etag": "NotImplemented",
"items": [
{
"kind": "youtube#channel",
"etag": "NotImplemented",
"id": "UC5O114-PQNYkurlTg6hekZw",
"shorts": [
{
"videoId": "fP8nKVauFwc",
"title": "India: United Nations Counter Terrorism Committee Watch LIVE #shorts",
"thumbnails": [
{
"url": "https:\/\/i.ytimg.com\/vi\/fP8nKVauFwc\/hq720_2.jpg?sqp=-oaymwEYCNAFENAFSFryq4qpAwoIARUAAIhC0AEB&rs=AOn4CLCgJEYgv_msT5pkfWeEEN3VBt4wjg",
"width": 720,
"height": 720
}
],
"viewCount": 3700
},
...
],
"nextPageToken": "4qmFsgLlARIYVUM1TzExNC1QUU5Za3VybFRnNmhla1p3GsgBOGdhU0FScVBBVktNQVFxSEFRcGZRME00VVVGU2IyWnZaMWxqUTJob1ZsRjZWbEJOVkVVd1RGWkNVbFJzYkhKa1dFcHpWa2RqTW1GSFZuSlhibU5SUVZOSlVrTm5PSGhQYWtVeVRtcGplVTE2VlRST2FrVXdUbXBCY1VSUmIweFhWRUl5VGtab1dGSllSbGRNVmtVU0pEWXpOakJoTkRVNUxUQXdNREF0TWpKaE15MDRObUV6TFdRMFpqVTBOMlZqWVRSbFl4Z0I=,CgtuNjFmZlJlR0QxcyiVgICbBg=="
}
]
}
Below is a sample python code to send the HEAD HTTP request.
import requests
def is_short(vid):
url = 'https://www.youtube.com/shorts/' + vid
ret = requests.head(url)
if ret.status_code == 200:
return True
else: # whether 303 or other values, it's not short
return False
I don't know why but I don't get status code 303 whether it's a short or not with axios. So this is another way of checking if it's a short or not.
const isShort = async (videoId) => {
const url = "https://www.youtube.com/shorts/" + videoId
const res = await axios.head(url)
console.log(res.request.res.responseUrl)
// if it's a short it ends with "/shorts/videoId"
// if it's NOT a short it ends "/watch?=videoId"
}
Maybe axios automatically redirects?
You can use the new dimension called 'creatorContentType' from Youtube Analytics and Reports API.
// You can get IDs from PlaylistItems or Search API
const IDs = ["videoID1", "videoID2", "videoID3"];
// Get the analytics data of selected videos based on their IDs
const { data: analyticsData } = await youtubeAnalytics.reports.query({
ids: "channel==MINE",
startDate: "2019-01-01",
// Today's date
endDate: new Date().toISOString().split("T")[0],
metrics: "views",
dimensions: "video,creatorContentType",
filters: `video==${IDs.join(",")}`,
access_token,
});
It basically returns values listed below:
Value
Description
LIVE_STREAM
The viewed content was a YouTube live stream.
SHORTS
The viewed content was a YouTube Short.
STORY
The viewed content was a YouTube Story.
VIDEO_ON_DEMAND
The viewed content was a YouTube video that does not fall under one of the other dimension values.
UNSPECIFIED
The content type of the viewed content is unknown.
Notes:
Don't forget it returns values just for the videos uploaded after 01.01.2019.
Don't forget to add analytics scopes and enable Analytics and Reports API.

How to get emotes for YouTube live chat messages?

I've been playing around with the YouTube live chat API to look render a YouTube live stream chat, but I'm stuck on how to handle emotes.
The YouTube API for live chat messages seems to only ever return the message in plain text, not metadata about emotes. This itself is fine, as there is standard syntax for emotes within the plain text, but I'm struggling with how to convert those into images.
If I look at the response I get from the YouTube API, I can see no information about the emotes beyond what is in the plain text message:
{
"kind": "youtube#liveChatMessage",
"etag": "UaRmhczzavJeCA9S1_s8J_4MHD0",
"id": "LCC.CjgKDQoLd1VwYUIzYTdkVW8qJwoYVUNEWExPVjNTMEdUd21EOFY4R1A2dzlREgt3VXBhQjNhN2RVbxJFChpDT25vOHN6SW92VUNGZUFJMWdBZE85b1BfZxInQ1BhdG12UEhvdlVDRlhzNFRBb2RVSE1BeVExNjQxNjU5MDY5OTU3",
"snippet": {
"type": "textMessageEvent",
"liveChatId": "Cg0KC3dVcGFCM2E3ZFVvKicKGFVDRFhMT1YzUzBHVHdtRDhWOEdQNnc5URILd1VwYUIzYTdkVW8",
"authorChannelId": "UC_MMOdc84fer50_SIPiPX1Q",
"publishedAt": "2022-01-08T16:24:28.363Z",
"hasDisplayContent": true,
"displayMessage": ":yougotthis::elbowcough:",
"textMessageDetails": {
"messageText": ":yougotthis::elbowcough:"
}
},
"authorDetails": {
"channelId": "UC_MMOdc84fer50_SIPiPX1Q",
"channelUrl": "http://www.youtube.com/channel/UC_MMOdc84fer50_SIPiPX1Q",
"displayName": "Blake Nolan",
"profileImageUrl": "https://yt3.ggpht.com/ytc/AKedOLSVNcUaOuoH49GXdG1Zlam0uBMJYJXUI5h_pHtMr-rOVr5hDnjzspewBUVqgKyw=s88-c-k-c0x00ffffff-no-rj",
"isVerified": false,
"isChatOwner": false,
"isChatSponsor": false,
"isChatModerator": false
}
}
But if I look at how this message shows up in YouTube chat, the emotes are rendered:
What am I missing to perform this lookup and conversion myself so that I can render the emotes from the chat messages?
Cheers.
To complete my answer from your other question on this precise question:
By running step 1. you'll get live messages sent in HTML format before your request with emotes in the format :emote: but then come the URL of the emote image.
By running all steps, you'll get live messages sent in real time in JSON format, in the same way you'll get live chat messages with emotes in the format :emote: but then come the URL of the emote image.
I let you understand both HTML and JSON format.
Note: I also found while reverse-engineering the URLs https://www.gstatic.com/youtube/img/emojis/emojis-svg-N.json with N between 0 and 8, that return a bunch of emotes codes linked to their image URL however some emotes like both you stated aren't in these files I don't know why.

Get a YouTube channel uploaded video list by publish date

I am aware of similar questions being asked before, but not this exact one, so please bear with me...
I want to reproduce a channel's uploaded videos list as they appear on YouTube's web page (broken into pages and sorted by publish date).
To do this, I am trying to get a list of VideoIDs from a YouTube channel that's sorted by publish date (by YouTube, not my code since there could be 1000's of videos in a playlist and YouTube limits to 50 results per query which can add up when I only want to show the user the first 25 entries).
Initially, I was using this YouTube Data API v3 Search query:
https://www.googleapis.com/youtube/v3/search?key=[APIKey]&channelId=[ChannelID]&part=snippet,id&order=date&type=video&maxResults=25
However, as some of the previous posts on stackoverflow mentioned (YouTube API v3 Search not returning all videos), this method does not guarantee to return all videos and indeed, some videos are missing from the result, making use of this query problematic.
I then saw this google video in some of the posts:
https://www.youtube.com/watch?v=RjUlmco7v2M
In the video, it is explained that you must first get the 'uploads' playlist for a channel (I'm also grabbing the channel's title and thumbnail in this query), which I do using:
https://www.googleapis.com/youtube/v3/channels?key=[APIKEY]&part=snippet,contentDetails&id=[ChannelID]
And once I have the 'uploads' playlist ID, I query:
https://www.googleapis.com/youtube/v3/playlistItems?key=[APIKey]&playlistId=[PlaylistID]&part=snippet,id&order=date&type=video&maxResults=25
However, the returned entries are not sorted by the publish date and according to the documentation (https://developers.google.com/youtube/v3/docs/playlistItems/list), there is no optional "order" parameter associated with this query.
With all these issues in mind, how do I get the first 25 entries of the 'uploads' playlist sorted by publish date without downloading the entire playlist so I can faithfully recreate how the YouTube website is listing videos.
After making some tests and thanks to this answer (and the next answers too) I was able to retrieve the information you need using the YouTube Data API v3 and here is how I made it:
First, in your question you're using the "search" API - since I don't know which criteria you're using in the search request, I omitted it for get direct to get the "upload" playlist id from a given channel_id.
Using the channel_id = UCT2rZIAL-zNqeK1OmLLUa6g (which belongs to "Microsoft HoloLens"), I use the "channels" API for retrieve the uploads playlist id.
Here is the URL request for retrieve the "upload" playlist id from the channel_id previously mentioned:
https://www.googleapis.com/youtube/v3/channels?part=id%2Csnippet%2CcontentDetails&fields=items(contentDetails%2FrelatedPlaylists%2Fuploads%2Csnippet%2Flocalized)&id=UCT2rZIAL-zNqeK1OmLLUa6g&key=<YOUR_API_KEY>
Explanation:
part: set the snippet and contentDetails parts for retrieve the following:
fields: from the snippet part: (localized, description and title) and from the contentDetails part: (relatedPlayLists and uploads).
id: channel_id used in this request.
Here are the results from this request:
{
"items": [
{
"snippet": {
"localized": {
"title": "Microsoft HoloLens",
"description": "The official YouTube channel of Microsoft HoloLens. Transform your world with holograms. Visit HoloLens.com for more info."
}
},
"contentDetails": {
"relatedPlaylists": {
"uploads": "UUT2rZIAL-zNqeK1OmLLUa6g"
}
}
}
]
}
Check the value of the uploads property in the
contentDetails section. This value will be used in the next API request.
You can also check these results in the Google API Explorer demo I prepared for make this request.
Once retrieved the uploads value (as specified in previous lines), now it's time to use the "playlistItems" API for build the following URL:
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&playlistId=UUT2rZIAL-zNqeK1OmLLUa6g&fields=items(contentDetails(videoId%2CvideoPublishedAt)%2Csnippet%2Ftitle%2Cstatus)&maxResults=25&key=<YOUR_API_KEY>
Explanation:
part: set the snippet and contentDetails parts for retrieve the following:
fields: from the snippet part: (title and status) and from the contentDetails part: (videoId and videoPublishedAt).
playlistId: is the playlistId used in this request - (that is, the uploads value).
maxResults: set to 25.
Here are the results from this request:
{
"items": [
{
"snippet": {
"title": "Microsoft Windows Mixed Reality update | October 2018"
},
"contentDetails": {
"videoId": "00vnln25HBg",
"videoPublishedAt": "2019-01-04T17:43:47.000Z"
}
},
{
"snippet": {
"title": "How to use Spectator View for mobile devices"
},
"contentDetails": {
"videoId": "3fXlPw_FGLg",
"videoPublishedAt": "2018-10-15T17:13:42.000Z"
}
},
{
"snippet": {
"title": "Microsoft HoloLens: Visualizing the next mission to Mars."
},
"contentDetails": {
"videoId": "XVBbJ4EtAQY",
"videoPublishedAt": "2018-07-02T16:30:26.000Z"
}
},
{
"snippet": {
"title": "Microsoft HoloLens: Making mixed reality plug and play."
},
"contentDetails": {
"videoId": "QwXcSekZKWE",
"videoPublishedAt": "2018-06-25T23:25:55.000Z"
}
},
{
"snippet": {
"title": "Microsoft HoloLens | Windows Mixed Reality HMD Exerciser"
},
"contentDetails": {
"videoId": "RU3OMjq_Yic",
"videoPublishedAt": "2018-05-14T16:58:43.000Z"
}
}
]
}
I check the order of the items and they are in sorted by videoPublishedAt value (new to old).
You can also check these results in the try-it funcionality found in the YouTube Data API v3 - official documentation.1
1 For this case, I was unable to use the Google API Explorer (as I used in the first request) because I always got a "backend Error".
{
"error": {
"errors": [
{
"domain": "global",
"reason": "backendError",
"message": "Backend Error"
}
],
"code": 500,
"message": "Backend Error"
}
}
I think this is because the Google API explorer is outdated.
If anyone want to check it out, here is the demo.
I'm also using the playlist ID to get a list of videos, however mine do seem to be sorted by date from newest to oldest. Note that Youtube returns a page token that you can use to get the next 25 (or in my case 50) videos. I'm querying the API this way:
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&pageToken= not_used_for_first_query&fields=nextPageToken,items(snippet(publishedAt,title,desc ription,thumbnails(default(url)),resourceId(videoId)))&playlistId=uploads_playlist_id&maxResults=50&order=date&key=your_api_key
This gets back in JSON response:
The video title
Publish date
Video description
Youtube URL for video
Video unique ID
Video thumbnail
You can see my working example at https://www.scriptbarrel.com

Why is the Youtube API not displaying results for video IDs?

I'm new to basically all forms of programming, so forgive me if there's an obvious answer, but I was just trying to make a random video chooser by randomly adding characters to the Youtube API's search function under list, but when I run the API with either just id or id and snippet on, it shows this:
{
"kind": "youtube#searchListResponse",
"etag": "\"i don't know if I can post my etag"",
"regionCode": "CA",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 50
},
"items": [
]
}
.
Its hard to know exactly what you have searched on but by the looks of the result there is just no results for your request. YOu might want to try playing with the api here search.list
When you run it click Execute without OAuth not the authorize and execute button. It will return a random list of videos.
You can use the q parameter to do a text search on videos for example that like toys.

How to get "transcript" in youtube-api v3

I have started using v3 of the YouTube apis on an android device, using the java client library. Some videos that I am interested in have transcripts that I can access on the web interface (like educational videos). Is there a way to access the transcripts, if present, using the v3 apis?
Thanks
I had the same problem with this... and spent like a week looking for a solution until I hit this:
https://stackoverflow.com/questions/10036796/how-to-extract-subtitles-from-youtube-videos
Just do a GET request on: http://video.google.com/timedtext?lang={LANG}&v={VIDEOID}
You don't need any api/oauth/etc. to access this.
With API v3 you can first grab the available transcripts with the snippet:
https://www.googleapis.com/youtube/v3/captions?videoId=U1e2VNtEqm4&part=snippet&key=(my_api_key):
{
"kind": "youtube#captionListResponse",
"etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/aGHflncRxq1Uz6m1akhrOLUWUqU\"",
"items": [
{
"kind": "youtube#caption",
"etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/IC7rNKkn3SQNdovFwR6fEabUYnY\"",
"id": "TqXDnlamg84o4bX0q2oaHz4nfWZdyiZMOrcuWsSLyPc=",
"snippet": {
"videoId": "U1e2VNtEqm4",
"lastUpdated": "2016-01-25T21:50:27.142Z",
"trackKind": "standard",
"language": "en-GB",
"name": "",
"audioTrackType": "unknown",
"isCC": false,
"isLarge": false,
"isEasyReader": false,
"isDraft": false,
"isAutoSynced": false,
"status": "serving"
}
},
{
"kind": "youtube#caption",
"etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/5UP1qPkmq6mzTUaEVnFC8WqjFgU\"",
"id": "TqXDnlamg84o4bX0q2oaHw_Y53ilUWv6vMFbk0RL3XY=",
"snippet": {
"videoId": "U1e2VNtEqm4",
"lastUpdated": "2016-01-25T21:55:07.481Z",
"trackKind": "standard",
"language": "en-US",
"name": "",
"audioTrackType": "unknown",
"isCC": false,
"isLarge": false,
"isEasyReader": false,
"isDraft": false,
"isAutoSynced": false,
"status": "serving"
}
}
]
}
And then pick the transcript you want:
https://www.googleapis.com/youtube/v3/captions/id?id=TqXDnlamg84o4bX0q2oaHz4nfWZdyiZMOrcuWsSLyPc=
or
https://www.googleapis.com/youtube/v3/captions/TqXDnlamg84o4bX0q2oaHz4nfWZdyiZMOrcuWsSLyPc=
at which point you need provide an authorization key. Apparently a simple key isn't enough. Possibly because:
Quota impact: A call to this method has a quota cost of approximately 200 units.
Note the slight difference in the URLs (/caption/ versus /caption?).
All the lovely documentation is here:
https://developers.google.com/youtube/v3/docs/captions
I may be wrong, but I don't think there is yet a documented way to get the caption track via v3 of the API. If you're authenticating with oAuth2, however, your authentication will also be good for v2 of the API, so you could do a quick call to this feed:
http://gdata.youtube.com/feeds/api/videos/[VIDEOID]/captiondata/[CAPTION TRACKID]
to get the data you want. To retrieve a list of possible caption track IDs with v2 of the API, you access this feed:
https://gdata.youtube.com/feeds/api/videos/[VIDEOID]/captions
That feed request also accepts some optional parameters, including language, max-results, etc. For more details, along with a sample that shows the returned format of the caption track list, see the documentation at https://developers.google.com/youtube/2.0/developers_guide_protocol_captions#Retrieve_Caption_Set
Heres some code I wrote which grabs all the caption tracks from any youtube video without having to use the API. Just plug the video URL in the $video_url variable.
// get video id from url
$video_url = 'https://www.youtube.com/watch?v=kYX87kkyubk';
preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $video_url, $matches);
// get video info from id
$video_id = $matches[0];
$video_info = file_get_contents('http://www.youtube.com/get_video_info?&video_id='.$video_id);
parse_str($video_info, $video_info_array);
if (isset($video_info_array['caption_tracks'])) {
$tracks = explode(',', $video_info_array['caption_tracks']);
// print info for each track (including url to track content)
foreach ($tracks as $track) {
parse_str($track, $output);
print_r($output);
}
}
Probably the best way is using Youtube API 3. I'm trying it but you need an API key + OAuth 2.0 user. A fast solution is using captionsgrabber and parsing the returned HTML data.
Use example:
https://www.captionsgrabber.com/8302/get-captions.00.php?id=UJTY7ilwSq4
// Where the id is the youtube video id

Resources