YouTube Data API v3を利用してチャンネルの国情報を取得する

なぜか日本語版の公式ドキュメントには記載されていないが、英語版を確認すると、APIを利用してYouTubeチャンネルに関連付けられた国情報を取得できることが分かる。

channels リソースには brandingSettings プロパティがある。このプロパティ内の brandingSettings.channel.country プロパティにはチャンネルに関連付けられた国名コードが入っている。
※後述するが、snippet.country プロパティを参照しても良い。ただし、この値は brandingSettings.channel.country プロパティにセットした値が入っているだけのもの。

APIリクエストを行って、このプロパティを取得するコードの例が下記。


require_once '/path/to/google-api-php-client/vendor/autoload.php';

$client = new Google_Client();
$client->setDeveloperKey("_API_KEY_");
$youtube = new Google_Service_YouTube($client);

$channelIds = [
  "UC_x5XG1OV2P6uZZ5FSM9Ttw", // Google Developers
  "UCrXUsMBcfTVqwAS7DKg9C0Q", // YouTube Japan
];

$params = [
  'id' => implode(",", $channelIds)
];

$response = $youtube->channels->listChannels('brandingSettings', $params);

foreach ($response['items'] as $i => $item)
{
  echo "#$i\n";
  echo "id     : {$item['id']}\n";
  echo "title  : {$item['brandingSettings']['channel']['title']}\n";
  echo "country: {$item['brandingSettings']['channel']['country']}\n\n";
}

listChannels() メソッドを使ってAPIリクエストを行う。part 引数には brandingSettings を指定し、フィルタのパラメータには、id パラメータに取得したいチャンネルIDを指定する。カンマ区切りで複数のIDを指定することができる。

そして、APIレスポンスとして返ってきたデータの中にある brandingSettings.channel.country プロパティの値を取得する。値は文字列で国名コードを表すものが入っている。

ただし、チャンネルによっては、brandingSettings.channel.country プロパティの値がセットされていないようで、NULL 値の場合がある。


次に、snippet.country プロパティを参照するバージョンのコードが下記。snippet.country プロパティの値には brandingSettings.channel.country プロパティにセットした値と同じものが入る。コードも、プロパティ名を変更するだけで本質的に違いはない。


require_once '/path/to/google-api-php-client/vendor/autoload.php';

$client = new Google_Client();
$client->setDeveloperKey("_API_KEY_");
$youtube = new Google_Service_YouTube($client);

$channelIds = [
  "UC_x5XG1OV2P6uZZ5FSM9Ttw", // Google Developers
  "UCrXUsMBcfTVqwAS7DKg9C0Q", // YouTube Japan
];

$params = [
  'id' => implode(",", $channelIds)
];

$response = $youtube->channels->listChannels('snippet', $params);

foreach ($response['items'] as $i => $item)
{
  echo "#$i\n";
  echo "id     : {$item['id']}\n";
  echo "title  : {$item['snippet']['title']}\n";
  echo "country: {$item['snippet']['country']}\n\n";
}