
📹 YouTube Data API v3: fetching video data with PHP (2026)
Why parse video data via API when you can just open the page?
Manually collecting information about dozens of videos takes hours. Title, duration, view count, publication date: copying all this by hand from YouTube is a guaranteed path to errors and burnout.
YouTube Data API v3 solves the problem programmatically. One HTTP request, and you get structured JSON with snippet, contentDetails, and statistics. No HTML parsing, no captchas.
In this tutorial: step-by-step instructions from creating an API key to a ready-to-use PHP script that extracts information about any YouTube video by its URL. The code is real, tested, with explanations for every line.
💡 Quick overview:
- Create an API key in Google Cloud Console and enable YouTube Data API v3
- Break down the
/videosendpoint structure and its part, id, and key parameters - Write a PHP function to extract video ID from any YouTube link
- Make a request via
file_get_contents()and parse the JSON response - Handle errors: invalid key, wrong ID, quota exceeded
- Look at an alternative: the ready-made
madcoda/php-youtube-apilibrary
Step 1: Obtaining a YouTube Data API key
To work with the API, you need a key. Here's the shortest path:
- Open Google Cloud Console and create a new project (or select an existing one).
- Go to APIs & Services → Library, find "YouTube Data API v3" and click Enable.
- Go to Credentials → Create Credentials → API Key.
- (Recommended) Restrict the key: in the API restrictions section, select YouTube Data API v3 so the key won't work with other Google services.
The key looks like a string such as AIzaSyD-... with 39 characters. Without it, the API returns a 403 error.
Daily quota is 10,000 units. One request to /videos costs 1 unit. For testing and small projects, this is more than enough. If you're planning production-level load, request a quota increase in the same Console section.
Step 2: API endpoint and its parameters
URL for getting video information:
1 GET https://www.googleapis.com/youtube/v3/videos
Parameters are passed as query string:
Parameter | Required | Description |
|---|---|---|
| Yes | Comma-separated list of fields: snippet, contentDetails, statistics, status, topicDetails, etc. |
| Yes | YouTube video ID (11 characters, e.g., |
| Yes | Your API key |
| No | Language for text fields (e.g., |
| No | Number of results (1-50, default is 5) |
Three main part values that cover most scenarios:
- snippet: basic information: title, description, channelId, channelTitle, publishedAt, thumbnails (set of thumbnail URLs at different resolutions), tags, categoryId.
- contentDetails: characteristics: duration (in ISO 8601 format, e.g.,
PT4M13S), dimension (2d/3d), definition (sd/hd), caption (whether subtitles exist). - statistics: numbers: viewCount, likeCount, commentCount.
Important note: the dislikeCount field in statistics has been disabled since December 2021, the API always returns 0. The favoriteCount field is also deprecated (always 0 since August 2015). Don't rely on them in your code.
Step 3: Extracting video ID from URL
Before calling the API, you need to extract the video ID from the link. YouTube has several URL formats:
- Standard:
https://www.youtube.com/watch?v=1ejTKov_Sm4 - Short:
https://youtu.be/1ejTKov_Sm4 - Embed:
https://www.youtube.com/embed/1ejTKov_Sm4 - With parameters:
https://www.youtube.com/watch?v=1ejTKov_Sm4&t=120
A simple PHP function handles all these variants:
1 /** 2 * Extracts video ID from YouTube URL. 3 * Supports formats: watch?v=, youtu.be/, /embed/ 4 * 5 * @param string $url YouTube video URL 6 * @return string|null Video ID (11 characters) or null on error 7 */ 8 function getYouTubeVideoId(string $url): ?string 9 { 10 $parsed = parse_url($url); 11 12 // Short link youtu.be/VIDEO_ID 13 if (isset($parsed['host']) && str_contains($parsed['host'], 'youtu.be')) { 14 return ltrim($parsed['path'], '/') ?: null; 15 } 16 17 // Standard link watch?v=VIDEO_ID 18 if (isset($parsed['query'])) { 19 parse_str($parsed['query'], $params); 20 if (!empty($params['v'])) { 21 return $params['v']; 22 } 23 } 24 25 // Embed link /embed/VIDEO_ID 26 if (isset($parsed['path']) && str_starts_with($parsed['path'], '/embed/')) { 27 return substr($parsed['path'], 7); 28 } 29 30 return null; 31 } 32 33 // Usage example 34 $videoUrl = 'https://www.youtube.com/watch?v=1ejTKov_Sm4'; 35 $videoId = getYouTubeVideoId($videoUrl); 36 echo $videoId; // 1ejTKov_Sm4
The function uses only built-in PHP capabilities: parse_url() breaks the URL into components, parse_str() parses the query string into an array. No external dependencies.
Step 4: API request and response parsing
Putting it all together. We build the URL by substituting the ID and key, make a GET request, and decode the JSON:
1 <?php 2 3 $apiKey = 'AIzaSyD-YOUR_KEY'; 4 $videoUrl = 'https://www.youtube.com/watch?v=1ejTKov_Sm4'; 5 $videoId = getYouTubeVideoId($videoUrl); 6 7 if (!$videoId) { 8 die('Failed to extract video ID from URL.'); 9 } 10 11 $endpoint = sprintf( 12 'https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=%s&key=%s', 13 $videoId, 14 $apiKey 15 ); 16 17 // Option with file_get_contents (requires allow_url_fopen = On in php.ini) 18 $context = stream_context_create([ 19 'http' => [ 20 'timeout' => 10, 21 'ignore_errors' => true, // do not crash on HTTP errors 22 ], 23 ]); 24 25 $response = @file_get_contents($endpoint, false, $context); 26 27 if ($response === false) { 28 die('Network request failed. Check your connection or use cURL.'); 29 } 30 31 $data = json_decode($response); 32 33 if (json_last_error() !== JSON_ERROR_NONE) { 34 die('API response is not JSON. The key might be invalid.'); 35 } 36 37 // API returns error in error field, not HTTP status 38 if (isset($data->error)) { 39 die('API Error: ' . $data->error->message); 40 } 41 42 if (empty($data->items)) { 43 die('No video found with this ID.'); 44 } 45 46 $video = $data->items[0]; 47 48 echo 'Title: ' . $video->snippet->title . PHP_EOL; 49 echo 'Channel: ' . $video->snippet->channelTitle . PHP_EOL; 50 echo 'Published: ' . $video->snippet->publishedAt . PHP_EOL; 51 echo 'Duration: ' . $video->contentDetails->duration . PHP_EOL; 52 echo 'Views: ' . number_format($video->statistics->viewCount ?? 0) . PHP_EOL; 53 echo 'Likes: ' . number_format($video->statistics->likeCount ?? 0) . PHP_EOL; 54 echo 'Comments: ' . number_format($video->statistics->commentCount ?? 0) . PHP_EOL; 55 56 // Max resolution thumbnail URL 57 if (isset($video->snippet->thumbnails->maxres)) { 58 echo 'Thumbnail: ' . $video->snippet->thumbnails->maxres->url . PHP_EOL; 59 }
The code is noticeably more robust than a bare file_get_contents() from a draft version. Added: ID extraction check, network error handling, JSON validation, response to Google API error (the error field), empty response check, and ?? fallback operator for optional statistics fields.
cURL as an alternative
If the allow_url_fopen directive is disabled on your hosting, file_get_contents() won't work. In that case, use cURL:
1 $ch = curl_init(); 2 curl_setopt_array($ch, [ 3 CURLOPT_URL => $endpoint, 4 CURLOPT_RETURNTRANSFER => true, 5 CURLOPT_TIMEOUT => 10, 6 CURLOPT_FOLLOWLOCATION => true, 7 ]); 8 $response = curl_exec($ch); 9 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 10 curl_close($ch); 11 12 if ($httpCode !== 200 || $response === false) { 13 die('Request failed. HTTP code: ' . $httpCode); 14 }
Ready-made library: madcoda/php-youtube-api
Writing a wrapper manually for production is extra work. For projects that need regular API interaction rather than a one-time fetch, there's madcoda/php-youtube-api, a lightweight PHP wrapper with no external dependencies. Installation:
1 composer require madcoda/php-youtube-api
Usage:
1 $youtube = new Madcoda\Youtube(['key' => 'YOUR_KEY']); 2 $video = $youtube->getVideoInfo('1ejTKov_Sm4'); 3 4 echo $video->snippet->title; 5 echo $video->statistics->viewCount;
The library handles routine tasks: pagination, retry requests, formatting duration from ISO 8601 to a readable format. For one-off scripts, it's overkill; for a working service, it's justified.
The video guide above clearly shows the entire process: from enabling the API in the console to the first successful request. We recommend watching it before writing code: 15 minutes of video saves an hour of reading documentation.

⁉️🤔 Frequently asked questions
How much does using YouTube Data API cost?
The API itself is free. You only pay with quota: 10,000 units per day for each project. A request to
/videoscosts 1 unit, so you can get data about 10,000 videos daily without spending a cent. For commercial projects with load above the threshold, Google offers a quota increase request form; they approve it with adequate justification. YouTube Data API has no separate paid tiers.
How does YouTube Data API v3 differ from HTML page parsing?
The API returns structured JSON with a documented schema. When fields change, Google publishes a deprecation notice several months in advance. HTML parsing breaks with any page redesign, requires browser emulation, and is explicitly prohibited by section 3.2 of YouTube's Terms of Service.
Can I get data about a private video?
With an API key, only public videos. For access to private, unlisted, and restricted videos, OAuth 2.0 with owner permission is required. Technically it's the same /videos endpoint, but with an access token instead of a key.
How do I get my YouTube channel ID?
The most reliable way: YouTube Studio → Settings → Channel → Advanced settings. There, the YouTube channel ID is shown as is, without any API requests. Alternatively: call
/channels?part=id&mine=truewith an OAuth token. For channels with custom usernames, the/channels?part=id&forUsername=NAMEmethod only works for those created before 2014.
What should I do when I get a "quotaExceeded" error?
The daily quota resets at 00:00 Pacific Time (UTC-8). Temporary solution: cache responses on your side (file, Redis). For a permanent increase: Google Cloud Console → IAM & Admin → Quotas → YouTube Data API v3 → requests per day → Edit Quota.
Where to apply YouTube Data API: final summary
We've covered the full cycle: API key, endpoint parameter breakdown, video ID extraction from URL, GET request, and JSON response parsing. The result is a working PHP script that retrieves the title, statistics, duration, and thumbnails of any public video in a second.
Where to go next:
- Video cards on a website. Integrate the script into a WordPress backend (
save_posthook) or Laravel, and when adding a YouTube link, video information is pulled automatically. - Competitor monitoring. Once a day, collect
viewCountandlikeCountfor a list of channels, and your dynamics table is ready. - Automatic import. If you run a video blog on your own site, fetch
snippet.titleandsnippet.descriptionas a draft text description for embedding.
YouTube Data API v3 is a mature, stable, and free tool. Having mastered the basic call from this tutorial, you open the door to dozens of other methods: search, playlists, comments, subscriptions. 🔗 Official YouTube Data API v3 documentation



