LoginSignup
5
3

More than 3 years have passed since last update.

Spotify APIでアーティストを指定して楽曲一覧をPythonで取得する

Posted at

嵐さんがサブスクリプション解禁したため、Spotify APIを使って楽曲情報を取得しました。

こちらの記事を一部参考にしています。
Spotify APIで楽曲情報やアーティスト情報を取得してみた

Spotify APIに登録

API利用のためにClient IDとSeclet Clientが必要なので取得する。

Spotifyのアカウントを取得していない場合はサイトから取得。
その後、Spotify for developersにてSpotifyアカウントでログイン。

Dashboardに移動し、「CREARE A CLIENT ID」より
・App or Hardware Name:アプリケーション名
・App or Hardware Description:説明文
・What are you building?:利用用途?
を入力すると、Client IDとSeclet Clientが取得できる。

アーティストIDを取得する

今回は直接アーティストIDを指定する。

Spotifyよりアーティストを検索。
詳細からアーティストリンクをコピー。artistの後ろ22桁の英数字がID。

楽曲情報を取得する

取得したClient ID、Seclet Client、アーティストIDを利用し、情報を取得する。

はじめにSpotify APIのライブラリspotipyをインストール。

pip install spotipy

一覧を取得します。
今回はタイトルと発売日と楽曲IDを取得する。

artist_songs.py
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import sys
import pprint

client_id = '取得したClient ID'
client_secret = '取得したClient Secret'
artist_id = '取得したいアーティストID'

# 認証を行う
client_credentials_manager = spotipy.oauth2.SpotifyClientCredentials(client_id, client_secret)
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

# アーティストに紐づく楽曲一覧を取得する
# album_type:‘album’, ‘single’, ‘appears_on’, ‘compilation’から選択可能
# country:発売国
# limit:取得する楽曲数
results = spotify.artist_albums(artist_id, album_type='single', country='JP', limit=20)

# ほしい情報を配列で取得する
artist_songs = []
for song in results['items'][:len(results)]:
    data = [
        '曲名:'+ song['name'], 
        '発売日:'+ song['release_date'], 
        'id:'+ song['id']]
    artist_songs.append(data)
pprint.pprint(artist_songs)

実行すると下記の通り。

[['曲名:Monster', '発売日:2010-05-19', 'id:0rDRRzBNKrzfgBa64kg0iF'],
 ['曲名:truth', '発売日:2008-08-20', 'id:3uVtXUio0J76jVElcXYHbP'],
 ['曲名:Happiness', '発売日:2007-09-05', 'id:5ydLlz0lePqmscLjd0Kw9I'],
 ['曲名:Love so sweet', '発売日:2007-02-21', 'id:5Vc35N1lqdE7xzwpEtwrBz'],
 ['曲名:A・RA・SHI', '発売日:1999-11-03', 'id:39X0fGQUhTkwg43DcSzZs7']]

今回の例は現在5曲のみ解禁されている嵐さんなので、limitの設定しなくてもいいかもしれません。
楽曲ごとのIDを取得できたので次は楽曲情報を取得していろいろ遊ぼうと思います。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3