Youtube api v3 get active streams for channels list - youtube-api

I'm trying get the currently active live streams for list of channels. I know, that there is search/list method, but it costs 100 units of api quota and only applicable for one channel per request. It's impossible to update stream avaibility frequently for large number of channels with total quota of 1M api units per day.
So, is there any other way, i can get active streams for channel or list of channels, avoiding "heavy" search method?

You can directly use Live Streaming API - LiveStreams:list, LiveStreams:list returns a list of video streams that match the API request parameters.
HTTP request:
GET https://www.googleapis.com/youtube/v3/liveStreams
Note that in every request needs authorizing access to provate user data. You need to implement OAuth 2.0.
Include onBehalfOfContentOwner parameter, this parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel.
HTTP response:
{
"kind": "youtube#liveStreamListResponse",
"etag": etag,
"nextPageToken": string,
"prevPageToken": string,
"pageInfo": {
"totalResults": integer,
"resultsPerPage": integer
},
"items": [
liveStream Resource
]
}
Here's a sample code snippet how to request liveStream resources:
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
.setApplicationName("youtube-cmdline-liststreams-sample")
.build();
// Create a request to list liveStream resources.
YouTube.LiveStreams.List livestreamRequest = youtube.liveStreams().list("id,snippet");
// Modify results to only return the user's streams.
livestreamRequest.setMine(true);
// Execute the API request and return the list of streams.
LiveStreamListResponse returnedListResponse = livestreamRequest.execute();
List<LiveStream> returnedList = returnedListResponse.getItems();
// Print information from the API response.
System.out.println("\n================== Returned Streams ==================\n");
for (LiveStream stream : returnedList) {
System.out.println(" - Id: " + stream.getId());
System.out.println(" - Title: " + stream.getSnippet().getTitle());
System.out.println(" - Description: " + stream.getSnippet().getDescription());
System.out.println(" - Published At: " + stream.getSnippet().getPublishedAt());
System.out.println("\n-------------------------------------------------------------\n");
}

Related

Youtube Reporting API returns video data but Youtube Data API does not for specific channel

I have this issue where a specific channel is not returning any videos on the Data-API (see response from API below):
{
"kind": "youtube#videoListResponse",
"etag": "YIUPVpqNjppyCWOZfL-19bLb7uk",
"items": [],
"pageInfo": {
"totalResults": 0,
"resultsPerPage": 0
}
}
In the meanwhile I can see data on its videos on Reporting API, both for Combined A2 and Basic A2 report types, like below (anonymized):
date,channel_id,video_id,live_or_on_demand,subscribed_status,country_code,views,comments,likes,dislikes,shares,watch_time_minutes,average_view_duration_seconds,average_view_duration_percentage,annotation_impressions,annotation_clickable_impressions,annotation_clicks,annotation_click_through_rate,annotation_closable_impressions,annotation_closes,annotation_close_rate,card_teaser_impressions,card_teaser_clicks,card_teaser_click_rate,card_impressions,card_clicks,card_click_rate,subscribers_gained,subscribers_lost,videos_added_to_playlists,videos_removed_from_playlists,red_views,red_watch_time_minutes
20221018,CHANNEL_ID,VIDEO_ID,on_demand,not_subscribed,FR,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
The request done to Data API has the following parts specified: snippet,contentDetails,statistics,id,topicDetails (independent of parts the request yields an empty answer as well)
Channel ID: UCs5DLbzGZJ559lKPP2pEWCw
Playlist ID: UUs5DLbzGZJ559lKPP2pEWCw
Tried calling Data API with third party token, with channel's token, checked on Reporting API (there is data there but not on Data API).
I expected: that videos are listed in Data API's PlaylistItems.list edge.

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 any Youtube channel's subscribed users list and their details using YouTube Analytics API?

I am trying to get any youtube channel's subscribed users list and their detail(analysis), like the XYZ channel has 45% male users subscriber and 55% female users subscriber, this channel was subscribed by this top 5 countries subscriber and the channel Audience Demography related information.
For this, I use YouTube Analytics API v3 and my URL is like
https://www.googleapis.com/youtube/v3/subscriptions?part=snippet,contentDetails,subscriberSnippet&key=APIKEY&id=CHANNELID
but this URL return below code in response
{
{
"kind": "youtube#SubscriptionListResponse",
"etag": "TOmVRCZpu2meG82Dv9k7Y-QQ8t888",
"pageInfo": {
"totalResults": 0,
"resultsPerPage": 5
},
"items": []
}
I don't know I'm right or wrong for the use of this URL for getting the above detail. I did read all the questions about youtube data API but I did not find my question's answer on those questions.
Thanks in advance.
According to the docs, if your intention is to obtain subscriptions info w.r.t. a given channel -- identified by its channel ID --, then you should use the parameter channelId:
channelId (string)
The channelId parameter specifies a YouTube channel ID. The API will only return that channel's subscriptions.
Therefore, do change your URL above to:
https://www.googleapis.com/youtube/v3/subscriptions?part=snippet,contentDetails,subscriberSnippet&key=APIKEY&channelId=CHANNELID.
The kind of data you are requesting falls under the private data of a channel. You can only access such data if you are the owner of that channel (by authorizing - Oauth2) or if the channel owner lets you access that data (after going through authorization) through a publicly available application.

Youtube API quota exceeded with 1 video

I try to insert a video in nodeJS to Youtube, and I got this error :
{ errors: [ { domain: 'youtube.quota',
reason: 'quotaExceeded',
message: 'The request cannot be completed because you have exceeded your quota.'
} ], code: 403, message: 'The request cannot be completed because
you have exceeded your quota.' }
EDIT : this is when I use Auth with an existing Token, I get token from https://developers.google.com/oauthplayground/ and use it in my code. I tried with different accounts, can't upload video but I can insert item in playlist for example.
Here is my code (nodeJS) :
var req = Youtube.videos.insert({
"resource": {
// Video title and description
"snippet": {
"title": "Test",
"description": "Test video upload via YouTube API"
},
"status": {
"privacyStatus": "private"
}
},
"part": "snippet,status,id",
"media": {
"body": fs.createReadStream('./test.mp4')
}
}, function (err, data) {
....
The video is 600 Ko... How can I see or update quotas ? I use OAuth auth, for example I can insert elements in my playlist with no problems, but I can't upload videos. Do I need something ?
Thanks.
Here is a reference of your error from the documentation.
About the quota:
The YouTube Data API uses a quota to ensure that developers use the
service as intended and do not create applications that unfairly
reduce service quality or limit access for others. All API requests,
including invalid requests, incur at least a one-point quota cost. You
can find the quota available to your application in the Developers
Console.
Projects that enable the YouTube Data API have a default quota
allocation of 1 million units per day, an amount sufficient for the
overwhelming majority of our API users. Default quota, which is
subject to change, helps us optimize quota allocations and scale our
infrastructure in a way that is more meaningful to our API users. You
can see your quota usage on the Usage tab for the API in the
Google Developer's Console.
Note: If you reach the quota limit, you can request additional quota on the Quotas tab in the Developer's Console.

How to create persistent livebroadcast?

I develop the mobile app with livestream feature and I need to get default livebroadcast with default livestream data.
When user didn't enable livestreams in his youtube account I show him message with link to https://www.youtube.com/live_streaming_signup .
After if user enabled livestreams in his youtube account I can't get default livebroadcast with broadcast type persistent.
My request url is: https://www.googleapis.com/youtube/v3/liveBroadcasts?part=contentDetails&mine=true&broadcastType=persistent&access_token=
My response is:
{
"kind": "youtube#liveBroadcastListResponse",
"etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/5WQLBG6RLCbLPgwsAs3o13sBM98\"",
"pageInfo": {
"totalResults": 0,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#liveBroadcast",
"etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/vyGp6PvFo4RvsFtPoIWeCReyIC8\""
}
]
}
Only after go to live dashboard page stream now I can got default livebroadcast with broadcast type persistent and then got livestream by default livebroadcast boundStremId
Why? How I can get default livebroadcast and default livestream without go to livestream dashboard?
I tried your query, and just like you, I can get 200 response, but I can only get 1 result. So the alternative way that I used to get the live broadcast is by using the Search: list under the DATA API. Here, you can use the eventType=live to get the live broadcast video.
GET https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&key={YOUR_API_KEY}
For the persistent broadcast, try to check this SO question if it can help you.
For more information check these related SO questions:
YouTube API live broadcast
How to get list of live video broadcasts using youtube api v3

Resources