Spotify Web API を利用してアーティストのカタログ情報を取得する

Spotify Web APIを利用してアーティストのカタログ情報を取得することができる。フォロワー数、ジャンル、人気度といった詳細な情報を得ることができる。

下記はSpotify Web APIを利用してアーティストのカタログ情報を取得するコードの例。


class SpotifyApiClient
{
  private $rootEndpoint = 'https://api.spotify.com/v1/';

  private $accessToken;

  public function __construct($ACCESS_TOKEN)
  {
    $this->accessToken = $ACCESS_TOKEN;
  }

  public function get($path, array $queryParams)
  {
    $url = $this->rootEndpoint . $path;

    if (!empty($queryParams))
      $url .= '?' . http_build_query($queryParams);

    $response = $this->execCurlGET($url);
    sleep(1);

    return json_decode($response, true);
  }

  private function execCurlGET($url)
  {
    $cmd = 'curl' .
           " -H 'Authorization: Bearer {$this->accessToken}'" .
           " '$url'";

    echo "# $cmd\n";

    return shell_exec($cmd);
  }
}


$tokenFile = 'token_new.json';
$token = json_decode(file_get_contents($tokenFile), true);
$client = new SpotifyApiClient($token['access_token']);

$artistId = '64tJ2EAv1R6UaZqc4iOCyj'; // YOASOBI
$response = $client->get("artists/$artistId", []);
var_dump($response);

アーティストのカタログ情報は、パスのパラメータ id にアーティストIDを指定し、下記のURLに対してGETリクエストを送信すれば良い。

https://api.spotify.com/v1/artists/{id}

APIリクエスト実行後、レスポンスデータの followers キー下に hreftotal キーがあり、total キーの値がフォロワー数を指す。href キーには、フォロワーの詳細情報を得るためのWeb APIのエンドポイントが入るが、現時点でまだサポートされていないため、値は常に null となる。

レスポンスデータの genres キーには、アーティストに関連付けられたジャンルのリストが保持されている。

レスポンスデータにある popularity キーは、アーティストの人気度を示すもので、この人気度はアーティストの全ての曲の人気度から計算される。0 から 100 までの値が入り、100 が最も人気があることを示す。