Developer Guide

YouTube Data API: Search Videos, Channels & Playlists Programmatically

By Serpent API Team · · 11 min read

Why YouTube Data Matters

YouTube is the second-largest search engine in the world, processing over 500 million searches per day. For developers building content tools, marketing platforms, research applications, or media monitoring systems, YouTube data is not optional — it is a primary data source that reveals what people are watching, what topics are trending, and which creators are gaining influence.

Serpent API provides YouTube endpoints that wrap Google's YouTube Data API v3, giving you access to video search, video details, and channel details through the same API key and billing system you use for web, news, and image search. No separate Google API key management, no quota tracking, no OAuth setup — just HTTP requests and structured JSON responses.

This guide covers every YouTube endpoint available through Serpent API, with complete code examples in both Node.js and Python, along with practical use cases and best practices.

Available Endpoints

Serpent API offers three YouTube-specific endpoints:

Endpoint Method Description Cost (Scale/1K)
/api/youtube/search GET Search for videos, channels, or playlists $0.11
/api/youtube/video GET Get detailed info for specific videos $0.11
/api/youtube/channel GET Get channel info and statistics $0.11

All three endpoints use the same apiKey parameter for authentication and are billed from your standard Serpent API credit balance.

Searching for Videos

The /api/youtube/search endpoint lets you search YouTube's entire catalog of videos. The default search type is "video," so the simplest possible request just needs a query and your API key.

Basic Video Search

# Python — Search YouTube videos
import requests

response = requests.get("https://apiserpent.com/api/youtube/search", params={
    "q": "machine learning tutorial 2026",
    "type": "video",
    "maxResults": 10,
    "apiKey": "your_api_key"
})

data = response.json()
for video in data["results"]:
    print(f"Title: {video['title']}")
    print(f"Channel: {video['channelTitle']}")
    print(f"Published: {video['publishedAt']}")
    print(f"URL: https://youtube.com/watch?v={video['videoId']}")
    print(f"Thumbnail: {video['thumbnail']}")
    print()

Response Fields

Each video result includes the following fields:

Getting Video Details

Once you have a video ID (from search results or any other source), you can fetch comprehensive details using the /api/youtube/video endpoint. This returns much richer data than search results, including statistics, duration, tags, and more.

// Node.js — Get video details
const axios = require('axios');

async function getVideoDetails(videoId) {
  const { data } = await axios.get('https://apiserpent.com/api/youtube/video', {
    params: {
      id: videoId,
      apiKey: 'your_api_key'
    }
  });

  const video = data.results[0];
  console.log(`Title: ${video.title}`);
  console.log(`Views: ${Number(video.viewCount).toLocaleString()}`);
  console.log(`Likes: ${Number(video.likeCount).toLocaleString()}`);
  console.log(`Comments: ${Number(video.commentCount).toLocaleString()}`);
  console.log(`Duration: ${video.duration}`);
  console.log(`Published: ${video.publishedAt}`);
  console.log(`Channel: ${video.channelTitle}`);
  console.log(`Tags: ${video.tags?.join(', ') || 'None'}`);
  console.log(`Category: ${video.categoryId}`);

  return video;
}

getVideoDetails('dQw4w9WgXcQ');

Statistics You Can Retrieve

Batch Video Details

You can pass multiple video IDs in a single request by comma-separating them: id=videoId1,videoId2,videoId3. This counts as a single API call, making it very efficient for bulk video analysis.

Getting Channel Details

The /api/youtube/channel endpoint returns comprehensive channel information including subscriber counts, total video counts, and cumulative view counts.

# Python — Get channel details
import requests

response = requests.get("https://apiserpent.com/api/youtube/channel", params={
    "id": "UC_x5XG1OV2P6uZZ5FSM9Ttw",   # Google Developers channel
    "apiKey": "your_api_key"
})

channel = response.json()["results"][0]
print(f"Channel: {channel['title']}")
print(f"Description: {channel['description'][:100]}...")
print(f"Subscribers: {int(channel['subscriberCount']):,}")
print(f"Total Videos: {int(channel['videoCount']):,}")
print(f"Total Views: {int(channel['viewCount']):,}")
print(f"Created: {channel['publishedAt']}")
print(f"Thumbnail: {channel['thumbnail']}")

Channel Data Fields

Searching for Channels and Playlists

The search endpoint supports three types: video (default), channel, and playlist. To search for channels instead of videos, set type=channel.

// Node.js — Search for channels
const axios = require('axios');

async function findChannels(query) {
  const { data } = await axios.get('https://apiserpent.com/api/youtube/search', {
    params: {
      q: query,
      type: 'channel',
      maxResults: 5,
      apiKey: 'your_api_key'
    }
  });

  data.results.forEach(ch => {
    console.log(`${ch.channelTitle} (${ch.channelId})`);
    console.log(`  ${ch.description.substring(0, 80)}...`);
    console.log();
  });
}

findChannels('javascript tutorials');

Playlist Search

Searching for playlists works the same way with type=playlist. Playlist results include the playlist title, channel that created it, description, and playlist ID which you can use to fetch the full list of videos.

# Python — Search for playlists
response = requests.get("https://apiserpent.com/api/youtube/search", params={
    "q": "python for beginners complete course",
    "type": "playlist",
    "maxResults": 5,
    "apiKey": "your_api_key"
})

for playlist in response.json()["results"]:
    print(f"Playlist: {playlist['title']}")
    print(f"Channel: {playlist['channelTitle']}")
    print(f"URL: https://youtube.com/playlist?list={playlist['playlistId']}")
    print()

Advanced Filtering and Sorting

The search endpoint supports several parameters for narrowing and sorting results:

Parameter Values Description
type video, channel, playlist Type of resource to search for
maxResults 1–50 Number of results per request
order relevance, date, viewCount, rating Sort order for results
publishedAfter ISO 8601 datetime Only return content published after this date
publishedBefore ISO 8601 datetime Only return content published before this date
regionCode ISO 3166-1 alpha-2 (e.g., US, GB) Restrict results to a specific country

Example: Recent High-View Videos

# Find the most viewed videos about AI published this month
response = requests.get("https://apiserpent.com/api/youtube/search", params={
    "q": "artificial intelligence",
    "type": "video",
    "order": "viewCount",
    "publishedAfter": "2026-03-01T00:00:00Z",
    "maxResults": 10,
    "apiKey": "your_api_key"
})

Practical Use Cases

1. Content Research and Ideation

Search for videos on your topic, sort by view count, and analyze which angles and formats perform best. Look at video titles, descriptions, and tags to understand what resonates with audiences. Use the video details endpoint to compare engagement metrics (likes, comments) across different content approaches.

2. Competitive Analysis

Monitor competitor channels by fetching their channel details regularly. Track subscriber growth, video publishing frequency, and cumulative view counts over time. Search for your competitors' brand names to find videos mentioning them and understand their presence on the platform.

3. Influencer Discovery

Search for channels in your niche, then use the channel details endpoint to evaluate them by subscriber count, video count, and total views. Calculate average views per video (total views / video count) to identify channels with engaged audiences that might be undervalued for sponsorship or partnership opportunities.

4. Trend Monitoring

Schedule regular searches for industry keywords with order=date and publishedAfter set to the last check. This creates a running feed of new YouTube content in your space, surfacing trending topics and emerging creators before they go mainstream.

5. Market Research

Analyze the video landscape around a product category or industry term. How many videos exist? What are the average view counts? Which channels dominate? Are audiences engaging through comments? This data informs content strategy, advertising decisions, and market sizing.

6. Video SEO

For content creators, search for your target keywords and analyze the top-ranking videos. What titles do they use? How long are the videos (via the duration field)? What tags do they include? Use this data to optimize your own video titles, descriptions, and tags for better YouTube search visibility.

Pricing

All YouTube endpoints are priced identically across Serpent API's tier structure:

Tier Qualification Price per 1,000 requests
Default All paid accounts $0.20
Growth $50+ total spend $0.16
Scale $200+ total spend $0.11

YouTube endpoints are also available on the free tier (100 searches included with no credit card required), making it easy to test the API before committing.

Complete Node.js Examples

Video Research Tool

const axios = require('axios');

const API_KEY = 'your_api_key';
const BASE = 'https://apiserpent.com/api/youtube';

async function researchTopic(topic) {
  // Step 1: Search for top videos
  const searchRes = await axios.get(`${BASE}/search`, {
    params: { q: topic, type: 'video', maxResults: 10, order: 'relevance', apiKey: API_KEY }
  });

  const videoIds = searchRes.data.results.map(v => v.videoId).join(',');

  // Step 2: Get detailed stats for all videos in one request
  const detailsRes = await axios.get(`${BASE}/video`, {
    params: { id: videoIds, apiKey: API_KEY }
  });

  // Step 3: Analyze
  const videos = detailsRes.data.results;
  const totalViews = videos.reduce((sum, v) => sum + parseInt(v.viewCount || 0), 0);
  const avgViews = Math.round(totalViews / videos.length);

  console.log(`\nTopic: "${topic}"`);
  console.log(`Top ${videos.length} videos — Avg views: ${avgViews.toLocaleString()}\n`);

  videos
    .sort((a, b) => parseInt(b.viewCount) - parseInt(a.viewCount))
    .forEach((v, i) => {
      console.log(`${i + 1}. ${v.title}`);
      console.log(`   Views: ${parseInt(v.viewCount).toLocaleString()} | ` +
                  `Likes: ${parseInt(v.likeCount || 0).toLocaleString()} | ` +
                  `Comments: ${parseInt(v.commentCount || 0).toLocaleString()}`);
      console.log(`   Channel: ${v.channelTitle} | Duration: ${v.duration}`);
      console.log();
    });
}

researchTopic('react server components tutorial');

Complete Python Examples

Channel Comparison Tool

import requests

API_KEY = "your_api_key"
BASE = "https://apiserpent.com/api/youtube"

def compare_channels(channel_ids):
    """Compare multiple YouTube channels side by side."""
    channels = []
    for cid in channel_ids:
        resp = requests.get(f"{BASE}/channel", params={
            "id": cid,
            "apiKey": API_KEY
        })
        ch = resp.json()["results"][0]
        channels.append({
            "name": ch["title"],
            "subscribers": int(ch.get("subscriberCount", 0)),
            "videos": int(ch.get("videoCount", 0)),
            "views": int(ch.get("viewCount", 0)),
            "avg_views": int(ch.get("viewCount", 0)) // max(int(ch.get("videoCount", 1)), 1),
            "created": ch.get("publishedAt", "")[:10]
        })

    # Sort by subscribers
    channels.sort(key=lambda x: x["subscribers"], reverse=True)

    print(f"{'Channel':<30} {'Subscribers':>15} {'Videos':>10} {'Avg Views/Video':>18}")
    print("-" * 75)
    for ch in channels:
        print(f"{ch['name']:<30} {ch['subscribers']:>15,} {ch['videos']:>10,} {ch['avg_views']:>18,}")

# Compare tech education channels
compare_channels([
    "UCW5YeuERMmlnqo4oq8vwUpg",  # The Net Ninja
    "UC8butISFwT-Wl7EV0hUK0BQ",  # freeCodeCamp
    "UCvjgXvBlISQQhFBJET9sXEw",  # Academind
])

Trending Video Monitor

import requests
from datetime import datetime, timedelta

API_KEY = "your_api_key"

def find_trending(keyword, days_back=7):
    """Find trending videos published in the last N days."""
    since = (datetime.utcnow() - timedelta(days=days_back)).strftime("%Y-%m-%dT00:00:00Z")

    resp = requests.get("https://apiserpent.com/api/youtube/search", params={
        "q": keyword,
        "type": "video",
        "order": "viewCount",
        "publishedAfter": since,
        "maxResults": 10,
        "apiKey": API_KEY
    })

    print(f"\nTrending videos for '{keyword}' (last {days_back} days):\n")
    for v in resp.json()["results"]:
        print(f"  {v['title']}")
        print(f"  Channel: {v['channelTitle']} | Published: {v['publishedAt'][:10]}")
        print(f"  https://youtube.com/watch?v={v['videoId']}")
        print()

find_trending("AI coding assistant", days_back=7)

Getting Started

To start using the YouTube endpoints:

  1. Sign up at apiserpent.com and get your API key (100 free searches included)
  2. Choose your endpoint: /api/youtube/search for discovering content, /api/youtube/video for detailed stats, or /api/youtube/channel for channel analysis
  3. Send a GET request with your query parameters and API key
  4. Parse the JSON response — the format is consistent and well-documented

All YouTube endpoints are available on the free tier, so you can test with real data before adding credits. For a complete reference of all parameters and response formats, see our API documentation. For a more comprehensive look at YouTube data possibilities, check our YouTube API complete guide.

Try Serpent API Free

100 free searches included. No credit card required. Start pulling YouTube data in minutes.

Get Your Free API Key

Explore: YouTube API · Social Media API · Pricing · Try in Playground