YouTube Data API¶
Collect data from YouTube with the Data API v3 through the google-api-python-client SDK: search videos by keyword, look up a channel, fetch statistics for videos, and download the comments of a video. The four sections share one API client and are meant to be run in order.
Setup. Install google-api-python-client and python-dotenv. Create an
API key in the Google Cloud console
with the YouTube Data API v3 enabled, and put it in a .env file next to the
notebook:
YOUTUBE_API_KEY=your-key
Never commit the .env file. In Google Colab there is no .env file, so set
the value with os.environ["YOUTUBE_API_KEY"] = "..." in a cell you delete
before sharing, or use Colab's Secrets panel.
Every request costs quota. The default is 100 search().list calls per day,
plus 10,000 units per day for every other read at 1 unit each. Every page
of results counts again. The quota resets at midnight Pacific time.
Reference: YouTube Data API v3.
Build the client¶
import os
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from dotenv import load_dotenv
load_dotenv()
youtube_api_key = os.getenv("YOUTUBE_API_KEY")
youtube = build("youtube", "v3", developerKey=youtube_api_key)
Search videos¶
Search videos by keyword with search().list, filter by publication date, and read the first page of results. Searches have their own budget of 100 calls per day, so use them sparingly.
request = youtube.search().list(
part="snippet",
maxResults=25,
q="cat",
publishedAfter="2025-09-05T00:00:00Z"
)
response = request.execute()
type(response)
response.keys()
Output:
dict_keys(['kind', 'etag', 'nextPageToken', 'regionCode', 'pageInfo', 'items'])
items holds the results; nextPageToken and pageInfo describe the page.
response['nextPageToken']
Output:
'CBkQAA'
Pass this back as pageToken in the next search().list call to get the following 25 results. Each of those calls uses another of the 100 daily searches.
response['pageInfo']
Output:
{'totalResults': 1000000, 'resultsPerPage': 25}
totalResults is an estimate, capped at one million. You cannot page through all of it: search stops returning pages after roughly 500 results.
response['items'][0]
One result, trimmed, with the video and channel replaced by placeholders:
{'kind': 'youtube#searchResult',
'etag': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'id': {'kind': 'youtube#video', 'videoId': 'XxXxXxXxXxX'},
'snippet': {'publishedAt': '2026-08-30T14:23:32Z',
'channelId': 'UCxxxxxxxxxxxxxxxxxxxxxx',
'title': 'A cat video #cats',
'description': '',
'thumbnails': {'default': {'url': 'https://i.ytimg.com/vi/XxXxXxXxXxX/default.jpg',
'width': 120,
'height': 90},
'medium': {...},
'high': {...}},
'channelTitle': 'Example Channel',
'liveBroadcastContent': 'none',
'publishTime': '2026-08-30T14:23:32Z'}}
A search result carries only this snippet: no view counts, no duration, no tags. Collect the videoId values and call videos().list with them when you need those. id['kind'] can also be youtube#channel or youtube#playlist unless you set type="video".
Channel information¶
Look up a channel by handle with channels().list and read its statistics and metadata.
request = youtube.channels().list(
part="contentDetails,id,localizations,snippet,statistics,status,topicDetails",
forHandle="MissingSemester"
)
response = request.execute()
response.keys()
response['items'][0]
Output, trimmed. The envelope is the same shape (kind, etag, pageInfo, items); the channel record is inside items:
{'kind': 'youtube#channel',
'etag': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'id': 'UCuXy5tCgEninup9cGplbiFw',
'snippet': {'title': 'Missing Semester',
'description': 'Classes teach you all about advanced topics within CS, ...',
'customUrl': '@missingsemester',
'publishedAt': '2019-01-29T03:39:58Z',
'thumbnails': {...},
'localized': {...},
'country': 'US'},
'contentDetails': {'relatedPlaylists': {'likes': '',
'uploads': 'UUuXy5tCgEninup9cGplbiFw'}},
'statistics': {'viewCount': '3785044',
'subscriberCount': '122000', # rounded to 3 significant digits
'hiddenSubscriberCount': False,
'videoCount': '38'},
'topicDetails': {'topicIds': [...],
'topicCategories': ['https://en.wikipedia.org/wiki/Technology', ...]},
'status': {'privacyStatus': 'public',
'isLinked': True,
'longUploadsStatus': 'longUploadsUnspecified',
'madeForKids': False}}
contentDetails['relatedPlaylists']['uploads'] is the channel's uploads playlist. Calling playlistItems().list on that ID pages through every video the channel has published at 1 quota unit per page — the cheap way to get video IDs, because each search page uses one of the 100 daily searches.
Video information¶
Fetch metadata and statistics for one or more videos by ID with videos().list. Up to 50 IDs fit in one call, separated by commas.
request = youtube.videos().list(
part="snippet,statistics,contentDetails,status",
id="Z56Jmr9Z34Q,kgII-YWo3Zw",
maxResults=25,
)
response = request.execute()
response.keys()
response['pageInfo']
response['items']
Output, trimmed. There is no nextPageToken this time: both requested videos fit on one page, and pageInfo says {'totalResults': 2, 'resultsPerPage': 2}.
[{'kind': 'youtube#video',
'etag': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'id': 'Z56Jmr9Z34Q',
'snippet': {'publishedAt': '2020-02-02T03:40:08Z',
'channelId': 'UCuXy5tCgEninup9cGplbiFw',
'title': 'Lecture 1: Course Overview + The Shell (2020)',
'description': 'You can find the lecture notes and exercises for this lecture at ...',
'thumbnails': {...},
'channelTitle': 'Missing Semester',
'tags': ['mit', 'lecture', 'tools', 'command-line', 'shell', 'unix', 'linux'],
'categoryId': '28',
'liveBroadcastContent': 'none',
'localized': {...},
'defaultLanguage': 'en',
'defaultAudioLanguage': 'en'},
'contentDetails': {'duration': 'PT48M17S', # ISO 8601: 48 min 17 s
'dimension': '2d',
'definition': 'hd',
'caption': 'true',
'licensedContent': False,
'contentRating': {},
'projection': 'rectangular'},
'status': {'uploadStatus': 'processed',
'privacyStatus': 'public',
'license': 'creativeCommon',
'embeddable': True,
'publicStatsViewable': True,
'madeForKids': False},
'statistics': {'viewCount': '826950',
'likeCount': '13883',
'favoriteCount': '0',
'commentCount': '398'}},
{...}] # the second requested video, same shape
Every count in statistics is a string; convert before doing math. Fields can also be absent: likeCount disappears when the uploader hides likes, commentCount when comments are turned off.
Video comments¶
Download the top-level comments of a video and their replies with commentThreads().list, one page at a time. Pass nextPageToken back as pageToken for the next page.
request = youtube.commentThreads().list(
part="id,replies,snippet",
videoId="Z56Jmr9Z34Q",
maxResults=25
)
response = request.execute()
response.keys()
response['nextPageToken']
Output:
'Z2V0X25ld2VzdF9maXJzdC0tQ2dnSWdBUVZGN2ZST0JJRkNJa2dHQUFTQlFpSElDQVlBUklGQ0ln...'
Same job as the search token, just longer. Pass it back as pageToken to get the next 25 threads; comment pages cost 1 quota unit each.
response['pageInfo']
response['items']
One thread, trimmed, with the commenter replaced by a placeholder:
[{'kind': 'youtube#commentThread',
'etag': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'id': 'Ugxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'snippet': {'channelId': 'UCuXy5tCgEninup9cGplbiFw',
'videoId': 'Z56Jmr9Z34Q',
'topLevelComment': {'kind': 'youtube#comment',
'etag': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'id': 'Ugxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'snippet': {'channelId': 'UCuXy5tCgEninup9cGplbiFw',
'videoId': 'Z56Jmr9Z34Q',
'textDisplay': 'I wish someone showed me this in my first year of college.',
'textOriginal': 'I wish someone showed me this in my first year of college.',
'authorDisplayName': '@example_user',
'authorProfileImageUrl': 'https://yt3.ggpht.com/...',
'authorChannelUrl': 'http://www.youtube.com/@example_user',
'authorChannelId': {'value': 'UCxxxxxxxxxxxxxxxxxxxxxx'},
'canRate': True,
'viewerRating': 'none',
'likeCount': 1,
'publishedAt': '2025-05-16T14:30:09Z',
'updatedAt': '2025-05-16T14:30:09Z'}},
'canReply': True,
'totalReplyCount': 0,
'isPublic': True}},
{...},
...] # 25 threads on this page
textDisplay is HTML: entities are escaped and timestamps become <a> tags. textOriginal is the plain text the commenter wrote — use that one. A thread with totalReplyCount > 0 carries up to 5 replies under a replies key; page through the rest with comments().list.