How to get youtube channel id using channel custom name? - youtube-api

My question is very similar to this one,
I want to get channel id using channel custom name.
The answer on the question mentioned above which is:
GET https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=annacavalli&type=channel&key={YOUR_API_KEY}
doesn't work on small channels, for ex. when I run it with this channel: https://www.youtube.com/AnnaShearerfashionfettish it returns nothing.

It's very easy, using curl and grep.
Command
channel_name='DOVASYNDROMEYouTubeOfficial' #change this as you like
curl --silent "https://www.youtube.com/c/${channel_name}/videos" |\
grep -o -P '(?<=canonical" href="https://www.youtube.com/channel/)[^"]*'
Output
UCq15_9MvmxT1r2-LLjtkokg

I didn't find a direct way to do this. I did a GET request to get the channel page HTML and parse it.
I used Jsoup to parse the html response.
val doc = Jsoup.parseBodyFragment(body)
val links = doc.select("link[rel=canonical]")
val channelUrl = links.first().attributes().get("href")

Did you try
https://www.googleapis.com/youtube/v3/channels?part=snippetforUsername={username}&key={your key}
Remember to change {your key} to your API key, and {username} to the desired username.

Related

Get channel ID from channel name with Youtube Data API [duplicate]

It seems Youtube has gotten rid of /channel/XXXX urls on their page, its now /c/username? with username NOT really being a "username". For example
https://www.youtube.com/c/lukemiani
Running a lookup via
https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername=lukemiani&key=...
returns no results.
I've got a bunch of non-technical users who've been trained to look for /channel/x or /user/x and input the correct thing into my app. Now that /channel is gone how do I (or they) translate /c/x to a channel id?
I'm looking for an API solution, not a view source and reverse engineer code solution.
According to the official support staff, a given channel may have associated an URL of form:
https://www.youtube.com/c/CUSTOM_NAME.
In such a case, the respective channel's customUrl property is CUSTOM_NAME.
Now, your problem may be reformulated as follows:
Given a CUSTOM_NAME for which the URL above points to an existing channel, is there a procedure that is able to produce -- by making use of YouTube Data API -- that channel's ID, such that the respective procedure to be DTOS-compliant (i.e. the procedure works by not scraping the HTML text obtained from the respective custom URL)?
The short answer to the above question is no, there's none. (Please have a look at my answer and the attached comments I gave recently to a similar question).
The longer answer would be the following: yes, it can be imagined an algorithm that solves the problem, but only partially (since there's no guarantee that it'll always give positive results).
Here is the algorithm:
Call the Search.list API endpoint with the following parameters:
q=CUSTOM_NAME,
type=channel, and
maxResults=10.
Extract from the result set obtained the channel IDs (these IDs are located at items[].id.channelId);
For each channel ID in the list obtained at step 2:
Invoke Channels.list API endpoint for to obtain the channel's associated customUrl property (if any);
If the obtained customUrl is equal with CUSTOM_NAME, then stop the algorithm yielding the current channel ID; otherwise, continue executing the current loop;
Stop the algorithm by yielding channel ID not found.
Due to the fuzzy nature of the result sets provided by the Search.list endpoint, one cannot exclude the possibility that there could actually exist custom URLs (i.e. URLs of the form above that are pointing to existing channels) for which this algorithm is not able to yield the ID of the associated channel.
A final note: the Channels.list endpoint accepts its id parameter to be a comma-separated list of channel IDs. Therefore, one may easily modify the algorithm above such that instead of N invocations (N <= 10) of Channels.list endpoint to have only one.
An implementation of the algorithm above in Python language, using Google's APIs Client Library for Python:
def find_channel_by_custom_url(
youtube, custom_url, max_results = 10):
resp = youtube.search().list(
q = custom_url,
part = 'id',
type = 'channel',
fields = 'items(id(kind,channelId))',
maxResults = max_results
).execute()
assert len(resp['items']) <= max_results
ch = []
for item in resp['items']:
assert item['id']['kind'] == 'youtube#channel'
ch.append(item['id']['channelId'])
if not len(ch):
return None
resp = youtube.channels().list(
id = ','.join(ch),
part = 'id,snippet',
fields = 'items(id,snippet(customUrl))',
maxResults = len(ch)
).execute()
assert len(resp['items']) <= len(ch)
for item in resp['items']:
url = item['snippet'].get('customUrl')
if url is not None and \
caseless_equal(url, custom_url):
assert item['id'] is not None
return item['id']
return None
where the function caseless_equal used above is due to this SO answer.
I posted here a simple Python3 script that encompasses the function find_channel_by_custom_url above into a standalone program. Your custom URL applied to this script yields the expected result:
$ python3 youtube-search.py \
--custom-url lukemiani \
--app-key ...
UC3c8H4Tlnm5M6pXsVMGnmNg
$ python3 youtube-search.py \
--user-name lukemiani \
--app-key ...
youtube-search.py: error: user name "lukemiani": no associated channel found
Note that you have to pass to this script your application key as argument to the command line option --app-key (use --help for brief help info).
You can do that in python, or with any http request library, by requesting the link and parsing the response for the channel ID. The channel id is in the canonical link tag that handles the redirection:
import requests
import re
url = "https://www.youtube.com/shroud"
r = requests.get(url, allow_redirects=True)
print(re.search(r'(?<=<link rel="canonical" href="https:\/\/www\.youtube\.com\/channel\/)(-?\w+)*(?=">)', r.text).group(0))
# Returns UCoz3Kpu5lv-ALhR4h9bDvcw

How to convert YouTube channel URL's to channel ID's? [duplicate]

It seems Youtube has gotten rid of /channel/XXXX urls on their page, its now /c/username? with username NOT really being a "username". For example
https://www.youtube.com/c/lukemiani
Running a lookup via
https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername=lukemiani&key=...
returns no results.
I've got a bunch of non-technical users who've been trained to look for /channel/x or /user/x and input the correct thing into my app. Now that /channel is gone how do I (or they) translate /c/x to a channel id?
I'm looking for an API solution, not a view source and reverse engineer code solution.
According to the official support staff, a given channel may have associated an URL of form:
https://www.youtube.com/c/CUSTOM_NAME.
In such a case, the respective channel's customUrl property is CUSTOM_NAME.
Now, your problem may be reformulated as follows:
Given a CUSTOM_NAME for which the URL above points to an existing channel, is there a procedure that is able to produce -- by making use of YouTube Data API -- that channel's ID, such that the respective procedure to be DTOS-compliant (i.e. the procedure works by not scraping the HTML text obtained from the respective custom URL)?
The short answer to the above question is no, there's none. (Please have a look at my answer and the attached comments I gave recently to a similar question).
The longer answer would be the following: yes, it can be imagined an algorithm that solves the problem, but only partially (since there's no guarantee that it'll always give positive results).
Here is the algorithm:
Call the Search.list API endpoint with the following parameters:
q=CUSTOM_NAME,
type=channel, and
maxResults=10.
Extract from the result set obtained the channel IDs (these IDs are located at items[].id.channelId);
For each channel ID in the list obtained at step 2:
Invoke Channels.list API endpoint for to obtain the channel's associated customUrl property (if any);
If the obtained customUrl is equal with CUSTOM_NAME, then stop the algorithm yielding the current channel ID; otherwise, continue executing the current loop;
Stop the algorithm by yielding channel ID not found.
Due to the fuzzy nature of the result sets provided by the Search.list endpoint, one cannot exclude the possibility that there could actually exist custom URLs (i.e. URLs of the form above that are pointing to existing channels) for which this algorithm is not able to yield the ID of the associated channel.
A final note: the Channels.list endpoint accepts its id parameter to be a comma-separated list of channel IDs. Therefore, one may easily modify the algorithm above such that instead of N invocations (N <= 10) of Channels.list endpoint to have only one.
An implementation of the algorithm above in Python language, using Google's APIs Client Library for Python:
def find_channel_by_custom_url(
youtube, custom_url, max_results = 10):
resp = youtube.search().list(
q = custom_url,
part = 'id',
type = 'channel',
fields = 'items(id(kind,channelId))',
maxResults = max_results
).execute()
assert len(resp['items']) <= max_results
ch = []
for item in resp['items']:
assert item['id']['kind'] == 'youtube#channel'
ch.append(item['id']['channelId'])
if not len(ch):
return None
resp = youtube.channels().list(
id = ','.join(ch),
part = 'id,snippet',
fields = 'items(id,snippet(customUrl))',
maxResults = len(ch)
).execute()
assert len(resp['items']) <= len(ch)
for item in resp['items']:
url = item['snippet'].get('customUrl')
if url is not None and \
caseless_equal(url, custom_url):
assert item['id'] is not None
return item['id']
return None
where the function caseless_equal used above is due to this SO answer.
I posted here a simple Python3 script that encompasses the function find_channel_by_custom_url above into a standalone program. Your custom URL applied to this script yields the expected result:
$ python3 youtube-search.py \
--custom-url lukemiani \
--app-key ...
UC3c8H4Tlnm5M6pXsVMGnmNg
$ python3 youtube-search.py \
--user-name lukemiani \
--app-key ...
youtube-search.py: error: user name "lukemiani": no associated channel found
Note that you have to pass to this script your application key as argument to the command line option --app-key (use --help for brief help info).
You can do that in python, or with any http request library, by requesting the link and parsing the response for the channel ID. The channel id is in the canonical link tag that handles the redirection:
import requests
import re
url = "https://www.youtube.com/shroud"
r = requests.get(url, allow_redirects=True)
print(re.search(r'(?<=<link rel="canonical" href="https:\/\/www\.youtube\.com\/channel\/)(-?\w+)*(?=">)', r.text).group(0))
# Returns UCoz3Kpu5lv-ALhR4h9bDvcw

How to fetch top 10 channel with youtube api

Hello I'm am now on a project that using YouTube api,
I am bit of stuck on how to fetch top 10 channel of a content owner at YouTube by using their api.
Right now what i am doing is that i need to loop all the channel i had and sort it by their views.
loop {
$analytics = $youtube->reports->query('contentOwner==$content_id', $start_date , $end_date , 'views,comments,likes,dislikes,estimatedMinutesWatched,averageViewDuration,shares,estimatedRevenue,estimatedAdRevenue,monetizedPlaybacks,adImpressions',array('filters'=> $id ,'max-results'=>$max_result));
}
It is fine but as it need to loop all the channel it takes quite some time. Is there any other way to fetch top 10 channel directly ?
By the way, is there any other way to by pass user consent?
problem solved after i do a lot of try and error,
youtube provide an api explorer for developer to test query parameter right away.
as i explain in the question i had successfully able to fetch/retrieve the data for a channel by using loop.
actually i can just put every channel id with comma to retrieve all the channel i manage.
before PHP example
loop {
$id = 'channel==' . $id;
$analytics = $youtube->reports->query('contentOwner==$content_id', $start_date , $end_date , 'views,comments,likes,dislikes,estimatedMinutesWatched,averageViewDuration,shares,estimatedRevenue,estimatedAdRevenue,monetizedPlaybacks,adImpressions',array('filters'=> $id ,'max-results'=>$max_result));
}
new or solved php example
$id = 'channel==' . implode(',', $id);
$analytics = $youtube->reports->query('contentOwner==$content_id', $start_date , $end_date,'views,comments,likes,dislikes,estimatedMinutesWatched,averageViewDuration,shares,estimatedRevenue,estimatedAdRevenue,monetizedPlaybacks,adImpressions',array('filters'=> $id ,'max-results'=>$max_result));
youtube already give the documentation on how to use their api, but i think it is quite hard to understand. Therefore i am able to use the api only when i do alot of try and error.
Thank you.

How can I get a channel ID from YouTube?

I'm trying to retrive the data from my channel using the YouTube Data API V3.
For that I need my channel ID.
I've tried to find my channel ID from my YouTube account, and I failed in every single way.
If anyone have a single tip for me, I would be incredible glad.
This is the URL that I'm using to retrieve the data:
https://www.googleapis.com/youtube/v3/channels?id=fjTOrCPnAblTngWAzpnlMA&key={YOUR_API_KEY}&part=snippet,contentDetails,statistics
The ID is for the channel ID, and the key, I'm replacing the {YOUR_API_KEY} with my API KEY generated at my Google API console.
My channel ID is not:
- klauskkpm
- klausmachado
- klausmachado#gmail.com
- fjTOrCPnAblTngWAzpnlMA
My channel is: http://www.youtube.com/user/klauskkpm
To obtain the channel id you can view the source code of the channel page and find either data-channel-external-id="UCjXfkj5iapKHJrhYfAF9ZGg" or "externalId":"UCjXfkj5iapKHJrhYfAF9ZGg".
UCjXfkj5iapKHJrhYfAF9ZGg will be the channel ID you are looking for.
An easy answer is, your YouTube Channel ID is UC + {YOUR_ACCOUNT_ID}.
To be sure of your YouTube Channel ID or your YouTube account ID, access the advanced settings at your settings page
And if you want to know the YouTube Channel ID for any channel, you could use the solution #mjlescano gave.
https://www.googleapis.com/youtube/v3/channels?key={YOUR_API_KEY}&forUsername={USER_NAME}&part=id
If this could be of any help, some user marked it was solved in another topic right here.
You can get the channel ID with the username (in your case "klauskkpm") using the filter "forUsername", like this:
https://www.googleapis.com/youtube/v3/channels?key={YOUR_API_KEY}&forUsername=klauskkpm&part=id
More info here: https://developers.google.com/youtube/v3/docs/channels/list
At any channel page with "user" url for example http://www.youtube.com/user/klauskkpm, without API call, from YouTube UI, click a video of the channel (in its "VIDEOS" tab) and click the channel name on the video. Then you can get to the page with its "channel" url for example https://www.youtube.com/channel/UCfjTOrCPnAblTngWAzpnlMA.
I just found the simplest way to find the channel ID of any YouTube channel !!
Step 1: Play a video of that channel.
Step 2: Click the channel name under that video.
Step 3: Look at the browser address bar.
June 2021 edition.
Right click and view page source.
Search for "externalId", the value follows.
Source: comment by Daniel 2017.
Alternative: run this JavaScript in console:
ytInitialData.metadata.channelMetadataRenderer.externalId
An alternative to get youtube channel ID by channel url without API:
function get_youtube_channel_ID($url){
$html = file_get_contents($url);
preg_match("'<meta itemprop=\"channelId\" content=\"(.*?)\"'si", $html, $match);
if($match && $match[1])
return $match[1];
}
As of 2022-06-23:
Open Chrome Dev Tools (F12), and in the "Elements" tab, within the source code pane, depending on URL type:
A. For channel URLs of type: www.youtube.com/c/<channel_name>:
Search for either:
"externalId" - next to it there will be the channel_ID
"channelUrl" - next to it there will be: https://www.youtube.com/channel/<channel_ID>
or run in the console:
ytInitialData.metadata.channelMetadataRenderer.externalId
(credit: https://stackoverflow.com/a/68063136/624597)
B. For video URLs of type: www.youtube.com/watch?v=<video_ID>:
Search for either:
"externalId" - next to it there will be the channel_ID
"externalChannelId" - next to it there will be the channel_ID
"ownerProfileUrl" - next to it there will be: https://www.youtube.com/channel/<channel_ID>
or run in the console:
ytInitialPlayerResponse.microformat.playerMicroformatRenderer.externalChannelId
Channel id with the current youtube version is obtained very easily if you login to YouYube website and select 'My channel'
Your channel ID will be displayed on the address bar of your browser
https://www.youtube.com/account_advanced now provides both channel and user ids. See also https://developers.google.com/youtube/v3/guides/working_with_channel_ids .
2017 Update: Henry's answer may be a little off the mark here. If you look for data-channel-external-id in the source code you may find more than one ID, and only the first occurrence is actually correct. Get the channel_id used in <link rel="alternate" type="application/rss+xml" title="RSS" href="https://www.youtube.com/feeds/videos.xml?channel_id=<VALUE_HERE"> instead.
To obtain the channel id you can do the following request which gives you the channel id and playlist id.
https://www.googleapis.com/youtube/v3/channels?part=contentDetails%2C+statistics%2Csnippet&mine=true&key={YOUR_API_KEY}
mine parameter means the current authorized user
as u said channel id is prefixed with UC+{your account id} which you get while login, you can use this one also without requesting the above url you can directly call the channel api with your google id and just prefix with UC
https://www.googleapis.com/youtube/v3/channels?part=contentDetails%2C+statistics%2Csnippet&id=UC{your account id}&key={YOUR_API_KEY}
Apparently there is a channelId attribute in video page's source code;
To get Channel id
Ex: Apple channel ID
Select any of the video in that channel
Select iPhone - Share photos (video)
Now click on channel name Apple bottom of the video.
Now you will get channel id in browser url
Here this is Apple channel id : UCE_M8A5yxnLfW0KghEeajjw
Try to search for regular expression UC[-_0-9A-Za-z]{21}[AQgw] in source code. This ID is presented even if channel has non-ASCII characters in URL:
Here is screenshot of internal viewer/editor of Midnight Commander, it has regexp search:
Alternatives to get the channel URL with its ID.
With a CSS selector by searching the channel homepage source code:
body > link[rel="canonical"]
or with JS via the console:
document.querySelector('body > link[rel="canonical"]').href
Another method to find the ID of a channel that is not yours is to go to the channel page and press the red "Subscribe" button.
Then use the Chrome's Inspector tools Network tab and look for the POST request issued by the subscribe action. In the payload of this request you will find the channel id:
You can unsubscribe immediately after subscribing.
Now in 2023, typing this in console should work:
document.querySelectorAll('[itemprop="channelId"]')[0].content

How to get Apple App IDs from given bundle ID?

I have a list of Apple app bundleIds (e.g. com.facebook.Facebook). What I am ultimately trying to achieve is to enrich this data with iTunes metadata, which is available via the iTunes Search API: http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html
I can get the specific information for a specific app if I know the app id (technically, the "trackId"), like so:
http://itunes.apple.com/lookup?id=284882215 (284882215 being the trackId for the Facebook app)
However, I cannot use the bundleId in the same way. How can I systematically retrieve the app id (aka trackId) given the bundleId?
This should work:
curl https://itunes.apple.com/lookup\?bundleId\=com.facebook.Facebook
In the results you should see things like:
"trackViewUrl": "https:\/\/itunes.apple.com\/us\/app\/facebook\/id284882215?mt=8&uo=4",
"bundleId": "com.facebook.Facebook",
"trackId": 284882215,
Based on David Richardson's answer, here's my slightly modified version that uses jq to parse the JSON and extract just the App ID:
$ myApp=WireGuard
$ bID=$(mdls -name kMDItemCFBundleIdentifier -r "/Applications/${myApp}.app")
$ curl -s "https://itunes.apple.com/lookup?bundleId=${bID}" | jq -r '.results[0].trackId'
1451685025

Resources