user2474272
user2474272

Reputation: 415

How to get Youtube channel details using Youtube data API if channel has custom url

I would like to fetch details of a YouTube channel which has a custom URL, like https://www.youtube.com/c/pratiksinhchudasamaisawesome.

Custom channel URLs follow this format: https://www.youtube.com/c/{custom_channel_name}.

I can fetch the details of YouTube channels by Channel ID and username without any issues. Unfortunately, I need to use the custom channel URL which is the only time I encounter this issue.

I developed my app few months ago, and the custom channel URL was working up until a few days ago. Now, the YouTube data API does not return anything for the YouTube custom channel URL if I try get details using their custom name.

To get the details of this channel: https://www.youtube.com/user/thenewboston, for example, the request would be:

GET https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername=thenewboston&key={YOUR_API_KEY}

Response

200
- SHOW HEADERS -
{
 "kind": "youtube#channelListResponse",
 "etag": "\"zekp1FB4kTkkM-rWc1qIAAt-BWc/8Dz6-vPu69KX3yZxVCT3-M9YWQA\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 5
 },
 "items": [
  {

   "kind": "youtube#channel",
   "etag": "\"zekp1FB4kTkkM-rWc1qIAAt-BWc/KlQLDlUPRAmACwKt9V8V2yrOfEg\"",
   "id": "UCJbPGzawDH1njbqV-D5HqKw",
   "snippet": {
    "title": "thenewboston",
    "description": "Tons of sweet computer related tutorials and some other awesome videos too!",
    "publishedAt": "2008-02-04T16:09:31.000Z",
    "thumbnails": {
     "default": {
      "url": "https://yt3.ggpht.com/--n5ELY2uT-U/AAAAAAAAAAI/AAAAAAAAAAA/d9JvaIEpstw/s88-c-k-no-rj-c0xffffff/photo.jpg"
     },
     "medium": {
      "url": "https://yt3.ggpht.com/--n5ELY2uT-U/AAAAAAAAAAI/AAAAAAAAAAA/d9JvaIEpstw/s240-c-k-no-rj-c0xffffff/photo.jpg"
     },
     "high": {
      "url": "https://yt3.ggpht.com/--n5ELY2uT-U/AAAAAAAAAAI/AAAAAAAAAAA/d9JvaIEpstw/s240-c-k-no-rj-c0xffffff/photo.jpg"
     }
    },
    "localized": {
     "title": "thenewboston",
     "description": "Tons of sweet computer related tutorials and some other awesome videos too!"
    }
   }
  }
 ]
}

It works perfectly.

Now we have to get details of these channels:

Then we get:

GET https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername=annacavalli&key={YOUR_API_KEY}

Response

200
- SHOW HEADERS -
{
 "kind": "youtube#channelListResponse",
 "etag": "\"zekp1FB4kTkkM-rWc1qIAAt-BWc/TAiG4jjJ-NTZu7gPKn7WGmuaZb8\"",
 "pageInfo": {
  "totalResults": 0,
  "resultsPerPage": 5
 },
 "items": [
 ]
}

This can be easily reproduced using the API explorer.

Upvotes: 24

Views: 11954

Answers (8)

quanticle
quanticle

Reputation: 5020

The latest version of the YouTube API now allows you to query for channels by their custom URLs with the new forHandle parameter. So, now, all you have to do is send a GET to https://www.googleapis.com/youtube/v3/channels with a forHandle query parameter.

So for example, to get the channel information for the Google Developers channel, you'd send a GET to:

https://content-youtube.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&forHandle=GoogleDevelopers

Upvotes: 0

YodaCode
YodaCode

Reputation: 21

It is possible the get the channel ID by the video ID, that can help depends on the need fo your application.

Here are an example:

        $queryParams = [
            'id' => 'UcDjWCEvZLM'
        ];
        $response = $service->videos->listVideos('snippet', $queryParams)->getItems();
        $channelId = $response[0]->snippet['channelId'];
        $channelTitle = $response[0]->snippet['channelTitle'];

Upvotes: 1

Meryan
Meryan

Reputation: 1473

Here is the .NET approach to convert custom Channel name/URL to a ChannelId using search API as mentioned in the accepted answer.

        // https://www.youtube.com/c/TheQ_original/videos
        // they call custom URL ?
        // https://stackoverflow.com/questions/37267324/how-to-get-youtube-channel-details-using-youtube-data-api-if-channel-has-custom
        // https://developers.google.com/youtube/v3/docs/channels#snippet.customUrl
        // GET https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=annacavalli&type=channel&key={YOUR_API_KEY}

        // 
        /// <summary>
        /// Returns ChannelID from old "Custom Channel Name/URL"
        /// Support the following URLs format
        /// https://www.youtube.com/c/MakeYourOWNCreation
        /// </summary>
        /// <param name="ChannelName"></param>
        /// <returns></returns>
        // 20220701
        public async Task<string> CustomChannelNameToChannelId(String ChannelName)
        {
            var YoutubeService = YouTubeService();
            //
            List<YouTubeInfo> VideoInfos = new List<YouTubeInfo>();
            // 
            // -) Step1: Retrieve 1st page of channels info
            var SearchListRequest = YoutubeService.Search.List("snippet");
            SearchListRequest.Q = ChannelName;
            SearchListRequest.Type = "channel";
            //
            SearchListRequest.MaxResults = 50;
            // Call the search.list method to retrieve results matching the specified query term.
            var SearchListResponse = await SearchListRequest.ExecuteAsync();
            // According to the SO post the custom channel will be the first one
            var searchResult = SearchListResponse.Items[0];
            //
            // Return Channel Information, we care to obtain ChannelID
            return searchResult.Id.ChannelId;
        }

Upvotes: 0

jvhang
jvhang

Reputation: 777

As @jkondratowicz noted, there is no way to reliably get this from the API as small channels do not return at the top of the search results.

So here is a JS example of how to get the channel id by extracting it from the HTML channel page (h/t @Feign'):

export const getChannelIdForCustomUrl = async (customUrl: string) => {
  const page = await axios.get(`https://www.youtube.com/c/${customUrl}`)

  const chanId = page.data.match(/channelId":"(.*?)"/)[1]

  return chanId
}

Upvotes: 0

Long Vuong
Long Vuong

Reputation: 181

I'm assuming that only channels with videos uploaded by the channel owner will be of interest. This is accidentally convenient since my method doesn't work with 0 video channels anyway.

Given a channel's url, my method will get the beautifulsoup HTML object of that channel's videos tab, and scrape the HTML to find the unique channel id. It'll then reconstruct everything and give back the channel url with the unique channel id.

your_channel_url = 'Enter your channel url here'
channel_url = your_channel_url.strip("https://").strip("featured")
https = "https://"
channel_vids_tab = https + channel_url + '/videos'

import requests
from bs4 import BeautifulSoup

source = requests.get(channel_vids_tab).text
soup = BeautifulSoup(source, "html.parser")

a = soup.find('body').find('link')['href']
channel_id = a.split('/')[-1]

print(a)
print(channel_id)

This method bypass the headache of one channel having different /user and /c url (for example /user/vechz and /c/vechz vs /c/coreyms and /user/schafer5 leading to the same page). Though you need to manually enter the url at first, it can be easily automated.

I'm also fairly confident that if a channel has 0 videos, this line of thinking can also apply for the playlist created BY the channel owner, and only needs a little tweaking. But if there's 0 videos or playlist created by the channel ... who knows

Upvotes: 0

Matthew Wright
Matthew Wright

Reputation: 1525

Workaround

Expanding off of @jkondratowicz answer, using the search.list in combination with channels.list you can most of the time resolve the channel from the custom url value.

The channel resource has a property customUrl so if we take the channels from the search.list results and get that extra detail about them from the channels.list it is possible to try and match up the custom url value with the customUrl property.

A working JavaScript method here, just replace the api key with your own. Though it is still not perfect, this tries the first 50 channels returned. More could be done with paging and pageTokens.

function getChannel(customValue, callback) {
    const API_KEY = "your_api_key"
    $.ajax({
        dataType: "json",
        type: "GET",
        url: "https://www.googleapis.com/youtube/v3/search",
        data: {
            key: API_KEY,
            part: "snippet",
            q: customValue,
            maxResults: 50,
            order: 'relevance',
            type: 'channel'
        }
    }).done(function (res) {
        const channelIds = [];
        for (let i=0; i<res.items.length; i++) {
            channelIds.push(res.items[i].id.channelId);
        }

        $.ajax({
            dataType: "json",
            type: "GET",
            url: "https://www.googleapis.com/youtube/v3/channels",
            data: {
                key: API_KEY,
                part: "snippet",
                id: channelIds.join(","),
                maxResults: 50
            }
        }).done(function (res) {
            if (res.items) {
                for (let i=0; i<res.items.length; i++) {
                    const item = res.items[i];
                    if (item.snippet.hasOwnProperty("customUrl") && customValue.toLowerCase() === item.snippet.customUrl.toLowerCase()) {
                        callback(item);
                    }
                }
            }
        }).fail(function (err) {
            logger.err(err);
        });
    }).fail(function (err) {
        logger.err(err);
    });
}

A good example using it with https://www.youtube.com/c/creatoracademy.

getChannel('creatoracademy', function (channel) {
    console.log(channel);
});

However, it is still unreliable as it depends on if the channel comes back in the original search.list query. It seems possible that if the custom channel url is too generic that the actual channel may not come back in the search.list results. Though this method is much more reliable then depending on the first entry of search.list to be the right one as search results don't always come back in the same order.

Issue

There has been at least three feature requests to Google in the past year requesting for an additional parameter for this custom url value but they were all denied as being infeasible. Apparently it is too difficult to implement. It was also mentioned as not being on their roadmap.

Resources

Upvotes: 5

Veilleuse
Veilleuse

Reputation: 334

An alternative way is to use a parser (PHP Simple HTLM DOM parser, for the example below : PHP Simple HTML DOM Parser) :

<?php
$media_url = 'https://www.youtube.com/c/[Channel name]';

$dom = new simple_html_dom();
$html = $dom->load(curl_get($media_url));
if (null !== ($html->find('meta[itemprop=channelId]',0))) {
    $channelId = $html->find('meta[itemprop=channelId]',0)->content;
}
?>

(Using Youtube api's "search" method has a quota cost of 100)

Upvotes: 3

jkondratowicz
jkondratowicz

Reputation: 1301

Simplest solution, using API only, is to just use Search:list method of YouTube Data API. From what I can tell (mind you, this is from my own research, official docs say nothing on this subject!), if you search using the custom URL component, with "channel" result type filter and "relevance" (default) sorting, first result should be what you're looking for.

So the following query gets 16 results, with the first one being the one you're looking for. Same goes for all other custom channel URLs I tested, so I think this is the most reliable way of doing this.

GET https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=annacavalli&type=channel&key={YOUR_API_KEY}

The other idea is just scraping YouTube page at the custom URL, where you can find ChannelID in one of the meta tags in HTML code. But that's ineffective, unreliable and AFAIK in violation of YouTube terms of use.

Edit: Well, it returns no results for smaller channels, so it's not reliable at all.

Upvotes: 29

Related Questions