Back to all posts

How to Scrape YouTube Video Data - The Easy Way

Jonathan Geiger
YouTube APIVideo StatisticsData ExtractionYouTube ScrapingVideo Analytics

Need to extract YouTube video statistics programmatically? Whether you're building video analytics tools, content monitoring systems, or SEO research platforms, getting reliable YouTube video data is crucial.

In this guide, we'll show you the easiest way to scrape YouTube video data using the YouTube Stats API - no complex scraping infrastructure required.

What Data Can You Extract?

The YouTube Stats API provides comprehensive video information:

  • Video Metadata - Title, description, and video URL
  • Engagement Metrics - Views, likes, and comment counts
  • Channel Information - Channel name and channel link
  • Performance Data - Real-time statistics for any public video
  • YouTube Shorts Support - Works with both regular videos and Shorts

The Easy Way: YouTube Stats API

The simplest and most reliable method is using the YouTube Stats API. Here's why:

No Infrastructure Needed - No need to manage API keys, quotas, or OAuth
Always Up-to-Date - API automatically handles YouTube changes
Fast & Reliable - Get video data in seconds with 99.9% uptime
Simple Integration - Just one API call with a YouTube URL
Structured Data - Clean JSON response ready for your application

API Endpoint

https://api.socialkit.dev/youtube/stats

Parameters

ParameterTypeRequiredDescription
urlstringYesYouTube video URL (regular or Shorts)
access_keystringYesYour API access key

Example Request

GET https://api.socialkit.dev/youtube/stats?access_key=<your-access-key>&url=https://youtube.com/watch?v=dQw4w9WgXcQ

Example Response

{
  "success": true,
  "data": {
    "url": "https://youtube.com/watch?v=dQw4w9WgXcQ",
    "title": "Rick Astley - Never Gonna Give You Up (Official Video)",
    "channelName": "Rick Astley",
    "channelLink": "https://youtube.com/channel/UCuAXFkgsw1L7xaCfnd5JJOw",
    "views": 1428567890,
    "likes": 16234567,
    "comments": 4567890
  }
}

Code Examples

JavaScript / Node.js

const axios = require('axios');

async function getYouTubeVideoStats(videoUrl, accessKey) {
  try {
    const response = await axios.get('https://api.socialkit.dev/youtube/stats', {
      params: {
        access_key: accessKey,
        url: videoUrl
      }
    });
    
    return response.data;
  } catch (error) {
    console.error('Error fetching YouTube video stats:', error);
    throw error;
  }
}

// Usage
const videoUrl = 'https://youtube.com/watch?v=dQw4w9WgXcQ';
const accessKey = 'your-access-key';

getYouTubeVideoStats(videoUrl, accessKey)
  .then(data => {
    console.log('Title:', data.data.title);
    console.log('Views:', data.data.views.toLocaleString());
    console.log('Likes:', data.data.likes.toLocaleString());
    console.log('Channel:', data.data.channelName);
  });

Python

import requests

def get_youtube_video_stats(video_url, access_key):
    endpoint = 'https://api.socialkit.dev/youtube/stats'
    
    params = {
        'access_key': access_key,
        'url': video_url
    }
    
    response = requests.get(endpoint, params=params)
    response.raise_for_status()
    
    return response.json()

# Usage
video_url = 'https://youtube.com/watch?v=dQw4w9WgXcQ'
access_key = 'your-access-key'

data = get_youtube_video_stats(video_url, access_key)

print(f"Title: {data['data']['title']}")
print(f"Views: {data['data']['views']:,}")
print(f"Likes: {data['data']['likes']:,}")
print(f"Channel: {data['data']['channelName']}")

PHP

<?php

function getYouTubeVideoStats($videoUrl, $accessKey) {
    $endpoint = 'https://api.socialkit.dev/youtube/stats';
    
    $url = $endpoint . '?' . http_build_query([
        'access_key' => $accessKey,
        'url' => $videoUrl
    ]);
    
    $response = file_get_contents($url);
    return json_decode($response, true);
}

// Usage
$videoUrl = 'https://youtube.com/watch?v=dQw4w9WgXcQ';
$accessKey = 'your-access-key';

$data = getYouTubeVideoStats($videoUrl, $accessKey);

echo "Title: " . $data['data']['title'] . "\n";
echo "Views: " . number_format($data['data']['views']) . "\n";
echo "Likes: " . number_format($data['data']['likes']) . "\n";
echo "Channel: " . $data['data']['channelName'] . "\n";

cURL

curl -X GET "https://api.socialkit.dev/youtube/stats?access_key=your-access-key&url=https://youtube.com/watch?v=dQw4w9WgXcQ"

Use Cases

1. Video Performance Tracker

Monitor video performance over time:

async function trackVideoPerformance(videoUrl, accessKey) {
  const data = await getYouTubeVideoStats(videoUrl, accessKey);
  
  const performance = {
    timestamp: new Date().toISOString(),
    title: data.data.title,
    views: data.data.views,
    likes: data.data.likes,
    comments: data.data.comments,
    engagementRate: ((data.data.likes + data.data.comments) / data.data.views * 100).toFixed(2)
  };
  
  // Save to database
  await saveToDatabase(performance);
  
  return performance;
}

2. Competitor Analysis Tool

Compare multiple videos' performance:

def analyze_competitors(video_urls, access_key):
    results = []
    
    for url in video_urls:
        data = get_youtube_video_stats(url, access_key)
        
        results.append({
            'title': data['data']['title'],
            'channel': data['data']['channelName'],
            'views': data['data']['views'],
            'likes': data['data']['likes'],
            'engagement_rate': (data['data']['likes'] / data['data']['views'] * 100) if data['data']['views'] > 0 else 0
        })
    
    # Sort by views
    return sorted(results, key=lambda x: x['views'], reverse=True)

# Usage
competitor_videos = [
    'https://youtube.com/watch?v=video1',
    'https://youtube.com/watch?v=video2',
    'https://youtube.com/watch?v=video3'
]

analysis = analyze_competitors(competitor_videos, 'your-access-key')
for video in analysis:
    print(f"{video['title']}: {video['views']:,} views")

3. Viral Content Detector

Identify trending videos by engagement rate:

async function detectViralContent(videoUrls, accessKey) {
  const viralThreshold = 0.05; // 5% engagement rate
  
  const results = await Promise.all(
    videoUrls.map(url => getYouTubeVideoStats(url, accessKey))
  );
  
  return results
    .filter(data => {
      const engagementRate = (data.data.likes + data.data.comments) / data.data.views;
      return engagementRate > viralThreshold;
    })
    .map(data => ({
      title: data.data.title,
      views: data.data.views,
      likes: data.data.likes,
      url: data.data.url
    }));
}

4. Channel Performance Dashboard

Aggregate statistics for multiple videos from a channel:

def calculate_channel_performance(video_urls, access_key):
    total_views = 0
    total_likes = 0
    total_comments = 0
    videos = []
    
    for url in video_urls:
        data = get_youtube_video_stats(url, access_key)
        
        total_views += data['data']['views']
        total_likes += data['data']['likes']
        total_comments += data['data']['comments']
        
        videos.append({
            'title': data['data']['title'],
            'views': data['data']['views']
        })
    
    return {
        'total_videos': len(videos),
        'total_views': total_views,
        'total_likes': total_likes,
        'total_comments': total_comments,
        'avg_views_per_video': total_views / len(videos) if videos else 0,
        'overall_engagement_rate': (total_likes / total_views * 100) if total_views > 0 else 0,
        'top_video': max(videos, key=lambda x: x['views']) if videos else None
    }

Response Data Explained

Video Information

  • title - Full video title
  • url - Canonical YouTube video URL
  • channelName - Name of the channel that published the video
  • channelLink - Direct link to the channel

Engagement Metrics

  • views - Total view count
  • likes - Total likes (dislikes are no longer public on YouTube)
  • comments - Total number of comments

Calculating Engagement Rate

const engagementRate = ((likes + comments) / views * 100).toFixed(2);

Supported URL Formats

The API accepts various YouTube URL formats:

  • https://youtube.com/watch?v=VIDEO_ID
  • https://www.youtube.com/watch?v=VIDEO_ID
  • https://youtu.be/VIDEO_ID
  • https://youtube.com/shorts/VIDEO_ID (YouTube Shorts)
  • https://www.youtube.com/watch?v=VIDEO_ID&t=123s (with timestamp)

Error Handling

Always implement proper error handling in production:

async function getYouTubeVideoStatsWithRetry(videoUrl, accessKey, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await axios.get('https://api.socialkit.dev/youtube/stats', {
        params: { access_key: accessKey, url: videoUrl }
      });
      
      if (response.data.success) {
        return response.data;
      }
      
      throw new Error('API returned unsuccessful response');
    } catch (error) {
      console.error(`Attempt ${i + 1} failed:`, error.message);
      
      if (i === maxRetries - 1) {
        throw error;
      }
      
      // Wait before retrying (exponential backoff)
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
    }
  }
}

Batch Processing

Process multiple videos efficiently:

import asyncio
import aiohttp

async def get_video_stats_async(session, video_url, access_key):
    endpoint = 'https://api.socialkit.dev/youtube/stats'
    params = {'access_key': access_key, 'url': video_url}
    
    async with session.get(endpoint, params=params) as response:
        return await response.json()

async def batch_process_videos(video_urls, access_key):
    async with aiohttp.ClientSession() as session:
        tasks = [
            get_video_stats_async(session, url, access_key)
            for url in video_urls
        ]
        return await asyncio.gather(*tasks)

# Usage
video_urls = ['url1', 'url2', 'url3', ...]
results = asyncio.run(batch_process_videos(video_urls, 'your-access-key'))

Pricing

The YouTube Stats API is included in all SocialKit plans:

  • Free: 20 credits (20 video lookups)
  • Basic: $13/month (2,000 credits)
  • Pro: $27/month (10,000 credits)
  • Ultimate: $79/month (50,000 credits)

Each API request costs 1 credit. View full pricing →

Alternative: Build Your Own Scraper

Want to build your own YouTube video scraper? It's possible but challenging:

Challenges

  1. YouTube Data API Quotas - Official API has strict daily quotas (10,000 units/day)
  2. Complex Authentication - Requires OAuth setup and API key management
  3. Rate Limiting - Easy to hit rate limits with official API
  4. Quota Costs - Different operations cost different quota amounts
  5. HTML Scraping Issues - YouTube's HTML structure changes frequently

Using YouTube Data API v3

// Requires setting up Google Cloud project and OAuth
const { google } = require('googleapis');

async function getVideoStatsOfficial(videoId, apiKey) {
  const youtube = google.youtube({
    version: 'v3',
    auth: apiKey
  });
  
  try {
    const response = await youtube.videos.list({
      part: 'snippet,statistics',
      id: videoId
    });
    
    const video = response.data.items[0];
    
    return {
      title: video.snippet.title,
      channelName: video.snippet.channelTitle,
      views: parseInt(video.statistics.viewCount),
      likes: parseInt(video.statistics.likeCount),
      comments: parseInt(video.statistics.commentCount)
    };
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

Why Use SocialKit API Instead?

  • No Quotas - Process unlimited videos based on your plan
  • Simpler - No OAuth setup or Google Cloud project needed
  • Consistent Costs - 1 credit per request, predictable pricing
  • No Rate Limits - Higher throughput for bulk processing
  • Better DX - Simple REST API vs complex Google API setup

Complete YouTube Data Toolkit

Beyond video statistics, you might need other YouTube data:

YouTube APIs:

Free YouTube Tools:

Frequently Asked Questions

Can I get historical view data?

The API returns current stats. To track growth over time, you'll need to store snapshots periodically in your own database.

Does this work with private videos?

No, the API only works with public YouTube videos. Private or unlisted videos cannot be accessed.

Can I get dislike counts?

No, YouTube removed public dislike counts in 2021. Only like counts are available.

How often is the data updated?

The API returns real-time data directly from YouTube, so it's always current.

Does this work with YouTube Shorts?

Yes! The API fully supports both regular YouTube videos and YouTube Shorts.

Related Resources: