YouTube Data API via PHP

I used PHP to write programs that call YouTube Data API. Here are typical steps I will go through when I have to use it again in a new VPS from a hosting company.

Step 1: Download and Install Composer

Composer is an application-level package manager for the PHP programming language.

Step 2: Download Google PHP Client

Create a new folder for your project (say youtube-programs). Within the folder create a file named composer.json with the following content.

{
  "require": {
    "google/apiclient": "^2.15.0"
  }
}

Then, run the command "composer update", which will download files for Google APIs Client Library for PHP. Here is the link to google-api-php-client.

Step 3: Create an example PHP file for testing

To test the YouTube Data API to Search YouTube videos, create a new file example.php and paste below code in it.

<?php
/**
 * Sample PHP code for youtube.search.list
 * See instructions for running these code samples locally:
 * https://developers.google.com/explorer-help/guides/code_samples#php
 */

require_once __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();
$client->setDeveloperKey('YOUR_API_KEY');
$service = new Google_Service_YouTube($client);

$queryParams = [
    'maxResults' => 25,
    'q' => 'YOUR_SEARCH_TERM'
];

$response = $service->search->listSearch('snippet', $queryParams);
print_r($response);

Step 4: Obtain a Google API Developer Key

In order to run our example program, you need to abtain a developer key and put it in the line that has "YOUR_API_KEY".

  1. Go to Google Cloud Console. Sign in with your Google account.
  2. You need to activate the Google Cloud service if your account never uses it.
  3. You may want to create a new project for obtaining a developer key.
  4. Go to "APIs and Services", then "Enabled APIs and Services".
  5. Select "YouTube Data API v3" and enable it.
  6. Click "Create Credentials", then select "Public data".
  7. You should see the key generated for you, but you need to make it having a green tick.
  8. Go back and click "Edit API Key", then "Set an application restriction" to "IP addresses". Enter the IP address of the machine you are going to call YouTube Data API.
  9. Finally, test the key with the above example PHP program.

Step 5: Explore how to use YouTube Data API

You are now able to make API calls for YouTube Ddata API. Go to this: YouTube Data API Reference, to explore yourself. Here is the link to a common used function: Search: list. It returns a collection of search results that match the query parameters specified in the API request. You can check more example code there by clicking on the tag icon to get code details.