sociallinks.dev

બ્લોગ / ડેવલપર ગાઇડ

હેન્ડલ પરથી YouTube channel ID કેવી રીતે મેળવવું (અને ઊલટું)

ક્રિએટર પોતાની YouTube ચેનલ @handle તરીકે શેર કરે છે, પણ YouTube Data API માં લગભગ બધું channel ID થી ઓળખાય છે. જો તમે માત્ર હેન્ડલ રાખો, તો નામ બદલાતાં તમારા રેકોર્ડ તૂટે છે; જો માત્ર ID રાખો, તો યુઝરને તેઓ ઓળખે તે નામ બતાવી શકતા નથી. આ માર્ગદર્શિકા બતાવે છે કે એક API call થી હેન્ડલને channel ID માં કેવી રીતે ફેરવવું, એકસાથે 50 ID પરથી હેન્ડલ કેવી રીતે મેળવવાં, જૂનાં /user/ અને /c/ URL નું શું કરવું, અને default quota ની અંદર કેવી રીતે રહેવું.

હેન્ડલ, channel ID અને જૂનાં નામ

YouTube ચેનલ સુધી ચાર પ્રકારના identifier થી પહોંચી શકાય. તેમાંથી માત્ર એક જ સ્થિર રહેવાની ખાતરી છે.

IdentifierઉદાહરણURL રૂપનોંધ
Channel IDUC_x5XG1OV2P6uZZ5FSM9Ttwyoutube.com/channel/UC...ચેનલ ઓળખવા YouTube જે ID વાપરે છે. Case-sensitive. તેને તમારી primary key તરીકે વાપરો.
હેન્ડલ@GoogleDevelopersyoutube.com/@GoogleDevelopersયુનિક, case-sensitive નહીં, અને માલિક YouTube Studio માં તેને બદલી શકે.
જૂનું usernameGoogleDevelopersyoutube.com/user/GoogleDevelopersજૂની username વ્યવસ્થામાંથી. API ના forUsername filter થી ઉકેલી શકાય.
જૂનું custom URLGoogleDevelopersyoutube.com/c/GoogleDevelopersજૂનાં વ્યક્તિગત URL, જે YouTube મુજબ કામ કરતાં રહે છે. કોઈ API filter તેમને ઉકેલતું નથી.

Channel ID ને key તરીકે રાખો અને હેન્ડલને display value તરીકે રાખો જે તમે રિફ્રેશ કરો. આ માર્ગદર્શિકાનો બાકીનો ભાગ યુઝરે જે આપ્યું હોય ત્યાંથી એ ID સુધી પહોંચવા વિશે છે.

API key બનાવો અને quota સમજો

  1. Step 1Google Cloud project બનાવો

    Google Cloud console માં project બનાવો કે હાલનો પસંદ કરો.

  2. Step 2YouTube Data API v3 ચાલુ કરો

    APIs and services ખોલો, library માં YouTube Data API v3 શોધો અને project માટે enable કરો.

  3. Step 3API key બનાવો

    Credentials હેઠળ API key બનાવો. હેન્ડલ કે ID થી channels.list જેવા જાહેર ચેનલ ડેટા માટે માત્ર key જોઈએ, OAuth નહીં. Key ને YouTube Data API સુધી મર્યાદિત કરો.

  4. Step 4Key ને કોડની બહાર રાખો

    તેને environment variable માં મૂકો, ઉદાહરણ તરીકે YOUTUBE_API_KEY, અને runtime પર વાંચો. નીચેનાં ઉદાહરણો બરાબર એ જ કરે છે.

  5. Step 5તમારો quota તપાસો

    Console માં API નું Quotas પેજ તમારી દૈનિક ફાળવણી અને વપરાશ બતાવે છે.

Google ના દસ્તાવેજ મુજબ મહત્વની સંખ્યાઓ:

તેથી default quota દિવસના લગભગ 10,000 હેન્ડલ lookups આવરે છે, અને 50 ગણા સુધી ID lookups, કારણ કે એક call એ જ એક unit માં ID થી 50 ચેનલ લાવી શકે.

forHandle થી હેન્ડલ પરથી channel ID

channels.list બરાબર એક filter સ્વીકારે છે. forHandle filter YouTube હેન્ડલ લે છે, અને reference કહે છે કે value આગળ @ ચિહ્ન લગાવી શકાય, તેથી GoogleDevelopers અને @GoogleDevelopers બંને ચાલે. તમને માત્ર ID જોઈએ ત્યારે part=id માગો; જવાબ નાનો આવે છે અને ખર્ચ એ જ રહે છે.

cURL

curl -s "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=@GoogleDevelopers&key=$YOUTUBE_API_KEY"

નીચેનું Node ઉદાહરણ request ને એક helper, listChannels, માં લપેટે છે, જે માર્ગદર્શિકાનો બાકીનો ભાગ ફરી વાપરે છે. કંઈ મેળ ન ખાય ત્યારે તે ખાલી યાદી આપે છે અને ખોટી key કે ખતમ થયેલા quota જેવી સાચી ભૂલો પર error ફેંકે છે.

Node.js

const API = "https://www.googleapis.com/youtube/v3/channels";
async function listChannels(params) {
  const key = process.env.YOUTUBE_API_KEY;
  if (!key) throw new Error("Set YOUTUBE_API_KEY");
  const url = new URL(API);
  url.search = new URLSearchParams({ ...params, key }).toString();
  const res = await fetch(url, { signal: AbortSignal.timeout(10_000) });
  const data = await res.json();
  if (!res.ok) {
    const reason = data.error?.errors?.[0]?.reason;
    if (reason === "channelNotFound") return [];
    throw new Error(`YouTube API ${res.status} ${reason ?? ""}: ${data.error?.message}`);
  }
  return data.items ?? []; // no match: items is empty or missing
}

/** "@GoogleDevelopers" or "GoogleDevelopers" -> "UC_x5XG1OV2P6uZZ5FSM9Ttw" or null */
export async function channelIdFromHandle(handle) {
  const items = await listChannels({ part: "id", forHandle: handle.trim() });
  return items[0]?.id ?? null;
}

/** Legacy username from a youtube.com/user/<name> URL -> channel ID or null */
export async function channelIdFromUsername(username) {
  const items = await listChannels({ part: "id", forUsername: username.trim() });
  return items[0]?.id ?? null;
}

/** Any number of channel IDs -> Map(id -> { title, customUrl }) */
export async function channelsById(ids) {
  const unique = [...new Set(ids)];
  const found = new Map();
  for (let i = 0; i < unique.length; i += 50) {
    const batch = unique.slice(i, i + 50);
    const items = await listChannels({ part: "snippet", id: batch.join(","), maxResults: "50" });
    for (const ch of items) {
      found.set(ch.id, { title: ch.snippet.title, customUrl: ch.snippet.customUrl ?? null });
    }
  }
  return found; // IDs missing from the map were not found
}

Python

import os

import requests

API = "https://www.googleapis.com/youtube/v3/channels"


def list_channels(**params):
    key = os.environ.get("YOUTUBE_API_KEY")
    if not key:
        raise RuntimeError("Set YOUTUBE_API_KEY")
    response = requests.get(API, params={**params, "key": key}, timeout=10)
    data = response.json()
    if not response.ok:
        errors = data.get("error", {}).get("errors") or [{}]
        reason = errors[0].get("reason")
        if reason == "channelNotFound":
            return []
        raise RuntimeError(f"YouTube API {response.status_code} {reason}: {data.get('error', {}).get('message')}")
    return data.get("items", [])  # no match: items is empty or missing


def channel_id_from_handle(handle):
    """'@GoogleDevelopers' or 'GoogleDevelopers' -> 'UC_x5XG1OV2P6uZZ5FSM9Ttw' or None"""
    items = list_channels(part="id", forHandle=handle.strip())
    return items[0]["id"] if items else None


def channel_id_from_username(username):
    """Legacy username from a youtube.com/user/<name> URL -> channel ID or None"""
    items = list_channels(part="id", forUsername=username.strip())
    return items[0]["id"] if items else None


def channels_by_id(ids):
    """Any number of channel IDs -> {id: {"title", "customUrl"}}; missing IDs were not found"""
    unique = list(dict.fromkeys(ids))
    found = {}
    for i in range(0, len(unique), 50):
        batch = unique[i:i + 50]
        for ch in list_channels(part="snippet", id=",".join(batch), maxResults=50):
            found[ch["id"]] = {
                "title": ch["snippet"]["title"],
                "customUrl": ch["snippet"].get("customUrl"),
            }
    return found

URL માંથી કોઈ પણ percent-encoding decode કર્યા પછી, યુઝરે લખ્યાં હોય તેવાં જ હેન્ડલ પાસ કરો. હેન્ડલ માત્ર ASCII નહીં, ઘણી લિપિના અક્ષરો વાપરી શકે, અને URLSearchParams તથા requests બંને તમારા માટે parameter encode કરે છે.

જૂનાં usernames અને /c/ custom URL

ક્રિએટરના bio અને સ્પ્રેડશીટમાંની જૂની લિંક ઘણી વાર હેન્ડલ પહેલાંનાં રૂપમાંથી એક વાપરે છે.

Channel ID પરથી હેન્ડલ, એકસાથે 50

ઊલટી દિશામાં id filter વપરાય છે, જે channel ID ની comma થી અલગ કરેલી યાદી લે છે. part=snippet માગો અને snippet.customUrl વાંચો. ઉપરનું channelsById ID ના ડુપ્લિકેટ દૂર કરે છે, તેમને 50 ના ટુકડામાં મોકલે છે, અને ID પ્રમાણેનો map આપે છે. Map માં ન દેખાતાં ID મળ્યાં નથી, ડિલીટ થયાં છે કે API ને દેખાતાં નથી.

Not found, errors અને caching

કંઈ મેળ ન ખાય તેવું lookup error નથી. forHandle અને forUsername માટે જવાબમાં ફક્ત items નથી હોતી, તેથી ખાલી કે ગેરહાજર items array તપાસો. channels.list માટે દસ્તાવેજિત errors આ છે:

Error નું કારણHTTPક્યારે થાયશું કરવું
200 જવાબમાં items નથી200હેન્ડલ કે username અસ્તિત્વમાં નથીnull આપો; miss ને થોડા સમય માટે cache કરો
channelNotFound404id parameter માંની ચેનલ મળતી નથીઉપરના helpers ની જેમ not found ગણો
invalidCriteria400Request માં એકથી વધુ filterforHandle, forUsername કે id માંથી બરાબર એક મોકલો
channelForbidden403ચેનલ request ને support નથી કરતી કે તે યોગ્ય રીતે authorized નથીLog કરો અને ચેનલ છોડી દો
quotaExceeded403તમારા project એ દૈનિક quota વાપરી નાખ્યોરોકાઓ અને Pacific Time ની મધ્યરાત્રિ પછી ફરી પ્રયાસ કરો, કે વધુ quota માગો
badRequest (API key not valid)400ગેરહાજર કે ખોટી keyConfiguration સુધારો; ફરી પ્રયાસ ન કરો

Quota અને latency બચાવવા પરિણામ cache કરો, પણ ડેટા રાખવા અંગેના YouTube ના નિયમોનું પાલન કરો. YouTube API Services Developer Policies (વિભાગ III.E.4) કહે છે કે non-authorized API ડેટા વધુમાં વધુ 30 કૅલેન્ડર દિવસ રાખી શકાય, પછી તેને ડિલીટ કે રિફ્રેશ કરવો પડે. નાના અક્ષરના હેન્ડલથી key થયેલું, 30 દિવસથી ઘણા ઓછા TTL વાળું cache મોટાભાગનો ફાયદો આપે છે:

Node.js cache

import { channelIdFromHandle } from "./youtube.mjs";

const TTL_MS = 7 * 24 * 60 * 60 * 1000; // refresh well inside YouTube's 30-day limit
const cache = new Map(); // lowercase handle -> { id, at }

export async function cachedChannelId(handle) {
  const key = handle.trim().replace(/^@/, "").toLowerCase();
  const hit = cache.get(key);
  if (hit && Date.now() - hit.at < TTL_MS) return hit.id;
  const id = await channelIdFromHandle(handle);
  cache.set(key, { id, at: Date.now() }); // caches misses (null) too
  return id;
}

Production માં આ જ logic Redis માં કે expires_at કૉલમવાળા database ટેબલમાં મૂકો, અને misses ને hits કરતાં ટૂંકો TTL આપો જેથી નવું બનેલું હેન્ડલ ઝડપથી પકડાય.

API key વિનાનો વિકલ્પ: ચેનલ પેજ વાંચવું

જાહેર ચેનલ પેજના HTML માં channel ID હોય છે. https://www.youtube.com/@GoogleDevelopers માટેની request હાલમાં એવું પેજ આપે છે જેની <link rel="canonical"> https://www.youtube.com/channel/UC_x5XG1OV2P6uZZ5FSM9Ttw તરફ જાય છે, અને /c/ તથા /user/ પેજ માટે પણ એવું જ છે, જેથી અનુમાન વિના /c/ નામ ઉકેલવાની આ એકમાત્ર રીત છે.

Node.js

// Unofficial fallback: reads the public channel page. Fragile, prefer the API.
export async function channelIdFromPage(handle) {
  const url = `https://www.youtube.com/@${encodeURIComponent(handle.replace(/^@/, ""))}`;
  const res = await fetch(url, {
    headers: { "Accept-Language": "en-US" },
    signal: AbortSignal.timeout(10_000),
  });
  if (!res.ok) return null;
  const html = await res.text();
  const match = html.match(/<link rel="canonical" href="https:\/\/www\.youtube\.com\/channel\/(UC[A-Za-z0-9_-]{22})"/);
  return match?.[1] ?? null;
}

Python

import re
from urllib.parse import quote

import requests

CANONICAL = re.compile(r'<link rel="canonical" href="https://www\.youtube\.com/channel/(UC[A-Za-z0-9_-]{22})"')


def channel_id_from_page(handle):
    """Unofficial fallback: reads the public channel page. Fragile, prefer the API."""
    url = "https://www.youtube.com/@" + quote(handle.lstrip("@"), safe="._-")
    response = requests.get(url, headers={"Accept-Language": "en-US"}, timeout=10)
    if not response.ok:
        return None
    match = CANONICAL.search(response.text)
    return match.group(1) if match else None

આનો ઓછો ઉપયોગ કરો અને માત્ર જ્યાં API મદદ ન કરી શકે ત્યાં. તે બિનસત્તાવાર અને નાજુક છે:

રીતોની સરખામણી

રીતઇનપુટખર્ચફાયદાગેરફાયદા
forHandle સાથે channels.listહેન્ડલ, @ સાથે કે વિનાહેન્ડલ દીઠ 1 unitસત્તાવાર, ચોક્કસ મેળ, કોઈ પણ હેન્ડલ માટે ચાલેCall દીઠ એક હેન્ડલ
forUsername સાથે channels.listજૂનું /user/ નામનામ દીઠ 1 unitસત્તાવાર, ચોક્કસ મેળમાત્ર જૂનાં usernames માટે
id સાથે channels.list50 સુધી channel ID50 ID દીઠ 1 unitસત્તાવાર, batched, title અને customUrl આપેcustomUrl ગેરહાજર હોઈ શકે
search.listમુક્ત લખાણDefault રીતે દિવસની 100 calls ની અલગ મર્યાદાનામથી ચેનલ શોધેક્રમબદ્ધ અનુમાન, ચોક્કસ નહીં; નાની મર્યાદા
ચેનલ પેજની canonical લિંકકોઈ પણ ચેનલ URL, /c/ સહિતAPI quota નહીંKey વિના ચાલે; /c/ નામ ઉકેલેબિનસત્તાવાર, નાજુક, block થઈ શકે, શરતો સાથે ટકરાઈ શકે

મોટાભાગની પ્રોડક્ટ માટે યોગ્ય રચના સાદી છે: forHandle થી હેન્ડલ ઉકેલો, channel ID રાખો, id filter થી 50 ના batch માં હેન્ડલ રિફ્રેશ કરો, અને ભાગ્યે જ આવતી /c/ લિંક માટે પેજવાળો વિકલ્પ flag પાછળ રાખો. જો તમને બીજાં પ્લેટફોર્મ પરનાં ક્રિએટરનાં એકાઉન્ટ પણ જોઈએ, તો sociallinks.dev એક API છે જે એક Instagram, TikTok, YouTube કે X પ્રોફાઇલ URL લે છે અને ક્રિએટરનાં બીજાં પ્લેટફોર્મ પરનાં એકાઉન્ટ, દરેક મેળ માટે confidence score અને પુરાવા સાથે આપે છે.

વારંવાર પૂછાતા પ્રશ્નો

forHandle ને હેન્ડલ આપતી વખતે @ જોઈએ?

ના. channels.list reference કહે છે કે forHandle value આગળ @ ચિહ્ન લગાવી શકાય, અને GoogleDevelopers તથા @GoogleDevelopers બંને ઉદાહરણ તરીકે આપે છે.

હેન્ડલ lookup કેટલો quota વાપરે છે?

એક unit. દરેક channels.list call 1 unit લે છે, અને default ફાળવણી દિવસના 10,000 units છે, જે Pacific Time ની મધ્યરાત્રિએ reset થાય છે. અમાન્ય requests પણ ઓછામાં ઓછો 1 unit લે છે.

શું એક call માં ઘણાં હેન્ડલ શોધી શકાય?

ના. forHandle એક જ હેન્ડલ લે છે. માત્ર id filter comma થી અલગ કરેલી યાદી સ્વીકારે છે, તેથી ઊલટી દિશા (ID પરથી હેન્ડલ) batch કરો અને આગળની દિશા cache કરો.

શું channel ID ક્યારેય બદલાય છે?

Channel ID એ identifier છે જે YouTube ચેનલને અનન્ય રીતે ઓળખવા વાપરે છે. હેન્ડલ કે title બદલવાથી તે બદલાતું નથી. તેથી જ તે યોગ્ય primary key છે. હેન્ડલ, title અને custom URL બધાં બદલાઈ શકે.

snippet.customUrl ખાલી કેમ આવે છે?

YouTube ની પોતાની revision history નોંધે છે તેમ, દરેક ચેનલ પાસે custom URL નથી. Field ને વૈકલ્પિક ગણો અને /channel/UC... URL બતાવવાનો વિકલ્પ રાખો.

પરિણામ કેટલો સમય cache કરી શકાય?

YouTube ની Developer Policies રાખેલા API ડેટાને ડિલીટ કે રિફ્રેશ કરતા પહેલાં 30 કૅલેન્ડર દિવસ સુધી મર્યાદિત કરે છે. Hits માટે એક અઠવાડિયું કે ઓછો TTL, અને misses માટે તેથી ટૂંકો, તમને તેની અંદર સારી રીતે રાખે છે.

ક્રિએટરના એકાઉન્ટ શોધો