はじめに
前回の記事↓
Spotify Web APIのApp作成とアクセストークンの取得 ― ReactでWebアプリ開発〈3〉
前回の記事で、準備段階であるアクセストークンの取得が完了したので、今回はSpotify Web APIを使用して実際に音楽情報を取得してみようと思います。
アルバムやトラック、ユーザ情報などを取得できるエンドポイントがそれぞれありますが、今回はClient Credential Flow(詳細は前回の記事を参照)で取得したアクセストークンのみで取得できる情報、すなわちユーザの認証・認可を必要としない情報の取得のみを行っていきます。
基本的には、公式ドキュメントに沿って取得しています。(ただし、ポッドキャスト情報やオーディオブック情報といった曲以外の情報の取得は今回は省きました。)
ソースコード
データ取得のためのJavaScriptコードは以下の通りです。Node.js上で実行できます。
const fs = require('fs');
// アクセストークンの取得
async function getAccessToken() {
const client_id = YOUR_CLIENT_ID;
const client_secret = YOUR_CLIENT_SECRET;
const response = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Authorization': 'Basic ' + Buffer.from(client_id + ':' + client_secret).toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'grant_type': 'client_credentials'
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
}
// 取得したアクセストークンは'token.json'に保存
async function getValidAccessToken() {
if (fs.existsSync('token.json')) {
const {get_date, access_token, expires_in} = JSON.parse(fs.readFileSync('token.json'));
if (Date.now() - get_date < expires_in * 1000) {
return access_token;
}
}
// 有効期限切れの場合、再取得&保存
const get_date = Date.now();
const data = await getAccessToken();
fs.writeFileSync('token.json', JSON.stringify({...data, get_date}));
return data.access_token;
}
async function getSpotifyData(endpoint) {
try {
const token = await getValidAccessToken();
// Spotify Web APIへのリクエストを送る
const response = await fetch(`https://api.spotify.com/v1${endpoint}`, {
headers: { 'Authorization': 'Bearer ' + token }
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}
getSpotifyData('/albums/0ETFjACtuP2ADo6LFhL6HN').then(
(data) => {
// 取得したデータの処理
}
);
取得したアクセストークンはtoken.jsonファイルに取得時刻とともに保存しています。有効期限が切れた場合は再取得します。
getSpotifyData()関数の引数を変更することで、https://api.spotify.com/v1以下の様々なエンドポイントにアクセスできます。async関数なので、then()で戻り値のデータを処理するコールバック関数を渡しています。(初めにawaitを使おうとしたところ、『Node.jsではトップレベルでawaitと使えない』とのエラーが出てしまいました…。async関数の中でのみ使えるそうです。)
それでは、以下でデータの取得と、取得結果の主なプロパティの表示を順に行っていきます。
Spotify IDの取得
アルバムやトラックの情報を取得する際、エンドポイントにアルバムIDやトラックIDといったSpotify IDを指定する必要があります。
Spotify IDの取得の仕方は以下の通りです。
- Spotifyのアプリ(デスクトップ版やブラウザ版など)で目的とするアルバムやトラック、アーティストのページに行く。
- 「シェア > リンクをコピー」を選択
- リンクのURLの末尾(クエリ文字列
?si=f0b...は無視)をコピーhttps://open.spotify.com/intl-ja/track/4fUKE8EULjQdHF4zb0M8FO?si=566bc412940344da→4fUKE8EULjQdHF4zb0M8FO
アルバム
アルバム情報を取得
/albums/{id}(公式ドキュメント)
- クエリ文字列
market=JPを付与することで、日本で取得可能なコンテンツのみの表示も可能(これ以降のほとんどのエンドポイントも同様です)
getSpotifyData('/albums/0ETFjACtuP2ADo6LFhL6HN').then(
(data) => {
console.log(`トラック総数: ${data.total_tracks}`);
console.log(`アルバムURL: ${data.external_urls.spotify}`);
console.log(`画像URL(widest): ${data.images[0].url}`);
console.log(`アルバム名: ${data.name}`);
console.log(`リリース日: ${data.release_date}`);
console.log(`アーティスト: ${data.artists[0].name}`);
console.log('トラック一覧:');
data.tracks.items.forEach((item) => console.log(`${item.track_number}, ${item.name}`));
}
);
トラック総数: 17
アルバムURL: https://open.spotify.com/album/0ETFjACtuP2ADo6LFhL6HN
画像URL(widest): https://i.scdn.co/image/ab67616d0000b273dc30583ba717007b00cceb25
アルバム名: Abbey Road (Remastered)
リリース日: 1969-09-26
アーティスト: The Beatles
トラック一覧:
1, Come Together - Remastered 2009
2, Something - Remastered 2009
3, Maxwell's Silver Hammer - Remastered 2009
4, Oh! Darling - Remastered 2009
5, Octopus's Garden - Remastered 2009
6, I Want You (She's So Heavy) - Remastered 2009
7, Here Comes The Sun - Remastered 2009
8, Because - Remastered 2009
9, You Never Give Me Your Money - Remastered 2009
10, Sun King - Remastered 2009
11, Mean Mr Mustard - Remastered 2009
12, Polythene Pam - Remastered 2009
13, She Came In Through The Bathroom Window - Remastered 2009
14, Golden Slumbers - Remastered 2009
15, Carry That Weight - Remastered 2009
16, The End - Remastered 2009
17, Her Majesty - Remastered 2009
複数のアルバム情報を取得
/albums(公式ドキュメント)
- 複数のアルバムIDをコンマ区切りで
idsパラメータに指定(最大20)
// 最大20
const albumIds = [
'2Se4ZylF9NkFGD92yv1aZC','2vnJKtGjZXRUg0mYPZ3HGH','6AccmjV8Q5cEUZ2tvS8s6c',
'3IPhWIXHOAhS2npnq6FiCG','2cUpAOlQjV5uSjkWj5bEQY','468ZwCchVtzEbt9BHmXopb',
'00BBpx0gG4KfQtxSJBPKUZ','4LH4d3cOWNNsVw41Gqt2kv','0bCAjiUamIFqKJsekOYuRw',
'3b4E89rxzZQ9zkhgKpj8N4','5Dbax7G8SWrP9xyzkOvy2F','1yMenUMOx7BpfTDuVQs99y',
'2jF5PAfwy1IFCJs4zBnedu','5F0IQXuHfTV7SBvZVnXERl','0yU7VItpGPmPcvKmwLg0JT'
];
getSpotifyData(`/albums?ids=${albumIds.join(',')}`).then(
(data) => {
console.log('アルバム一覧:')
data.albums.forEach(
(item) => console.log(`${item.name} (${item.release_date})`)
);
}
);
アルバム一覧:
The Piper at the Gates of Dawn (1967-08-05)
A Saucerful of Secrets (1968-06-29)
More (1969-07-27)
Ummagumma (1969-10-25)
Atom Heart Mother (1970-10-05)
Meddle (1971-11-11)
Obscured by Clouds (1972-06-03)
The Dark Side of the Moon (1973-03-01)
Wish You Were Here (1975-09-12)
Animals (1977-01-23)
The Wall (1979-11-30)
The Final Cut (1983-03-21)
A Momentary Lapse of Reason (1987-09-08)
The Division Bell (1994)
The Endless River (2014-11-10)
アルバムトラックを取得
/albums/{id}/tracks(公式ドキュメント)
limit、offsetを指定可能
// limit, offset設定可能
getSpotifyData('/albums/0ETFjACtuP2ADo6LFhL6HN/tracks?limit=10&offset=6').then(
(data) => {
console.log('トラック一覧:')
data.items.forEach(
(item) => console.log(`${item.track_number}, ${item.name}`)
);
}
);
トラック一覧:
7, Here Comes The Sun - Remastered 2009
8, Because - Remastered 2009
9, You Never Give Me Your Money - Remastered 2009
10, Sun King - Remastered 2009
11, Mean Mr Mustard - Remastered 2009
12, Polythene Pam - Remastered 2009
13, She Came In Through The Bathroom Window - Remastered 2009
14, Golden Slumbers - Remastered 2009
15, Carry That Weight - Remastered 2009
16, The End - Remastered 2009
新しくリリースされたアルバムを取得
/browse/new-releases(公式ドキュメント)
limit、offsetを指定可能
getSpotifyData('/browse/new-releases?limit=5').then(
(data) => {
console.log('アルバム一覧:')
console.log('-'.repeat(85));
data.albums.items.forEach(
(item) => {
console.log(`アルバム名: ${item.name}`);
console.log(`アルバムURL: ${item.external_urls.spotify}`);
console.log(`画像URL(widest): ${item.images[0].url}`);
console.log(`リリース日: ${item.release_date}`);
console.log(`アーティスト: ${item.artists[0].name}`);
console.log('-'.repeat(85));
}
);
}
);
アルバム一覧:
-------------------------------------------------------------------------------------
アルバム名: 猫にジェラシー
アルバムURL: https://open.spotify.com/album/10bxrO3VcayVLsFF30JFxO
画像URL(widest): https://i.scdn.co/image/ab67616d00001e02cd66af9ef8a18ce254e14c87
リリース日: 2024-09-11
アーティスト: Aimyon
-------------------------------------------------------------------------------------
アルバム名: ジャンヌ・ダルクによろしく
アルバムURL: https://open.spotify.com/album/4Nf7lVjQa2vi4Ad18oqiD4
画像URL(widest): https://i.scdn.co/image/ab67616d00001e028123ec76fb94a5e310884e6e
リリース日: 2024-09-09
アーティスト: サザンオールスターズ
-------------------------------------------------------------------------------------
アルバム名: Are you serious?
アルバムURL: https://open.spotify.com/album/1VkcEVXoIxaOXyfgw28DYi
画像URL(widest): https://i.scdn.co/image/ab67616d00001e02825b35649e3a80d846151c59
リリース日: 2024-09-11
アーティスト: Awich
-------------------------------------------------------------------------------------
アルバム名: WHERE DO WE GO
アルバムURL: https://open.spotify.com/album/6GkIf5MU4sXwa1rHurNVAc
画像URL(widest): https://i.scdn.co/image/ab67616d00001e02f0b1bc180e6f64d777026b22
リリース日: 2024-09-09
アーティスト: JO1
-------------------------------------------------------------------------------------
アルバム名: 新しい恋人達に
アルバムURL: https://open.spotify.com/album/4c4t1NAsAzMmLrSV1HH1hQ
画像URL(widest): https://i.scdn.co/image/ab67616d00001e02ffa28db6f848685c4ef0fe7f
リリース日: 2024-09-11
アーティスト: back number
-------------------------------------------------------------------------------------
アーティスト
アーティスト情報を取得
/artists/{id}(公式ドキュメント)
getSpotifyData('/artists/7Mo0nFEU6E8fGI0P2u7MOl').then(
(data) => {
console.log(`アーティストURL: ${data.external_urls.spotify}`);
console.log(`フォロワー数: ${data.followers.total}`);
console.log(`ジャンル: ${data.genres.join(', ')}`);
console.log(`画像URL(widest): ${data.images[0].url}`);
console.log(`アーティスト名: ${data.name}`);
}
);
アーティストURL: https://open.spotify.com/artist/7Mo0nFEU6E8fGI0P2u7MOl
フォロワー数: 583451
ジャンル: j-pop, japanese singer-songwriter
画像URL(widest): https://i.scdn.co/image/ab67616d0000b27396c8fcdb7975c2a17172eacf
アーティスト名: Yutaka Ozaki
複数のアーティスト情報を取得
/artists(公式ドキュメント)
- 複数のアーティストIDをコンマ区切りで
idsパラメータに指定(最大50)
// 最大50
const artistIds = [
'4x1nvY2FN8jxqAFA0DA02H','4STHEaNw4mPZ2tzheohgXB',
'7FIoB5PHdrMZVC3q2HE5MS','6DbJi8AcN5ANdtvJcwBSw8'
];
getSpotifyData(`/artists?ids=${artistIds.join(',')}`).then(
(data) => {
console.log('アーティスト一覧:')
data.artists.forEach(
(item) => console.log(`${item.name} (Followers: ${item.followers.total})`)
);
}
);
アーティスト一覧:
John Lennon (Followers: 6130776)
Paul McCartney (Followers: 4866817)
George Harrison (Followers: 2721761)
Ringo Starr (Followers: 967983)
アーティストのアルバムを取得
/artists/{id}/albums(公式ドキュメント)
limit、offsetを指定可能include_groupsパラメータで、アルバムの種類(album,single,appears_on,compilation)をコンマ区切りで指定可能。(appears_onは、他アーティストの作品も含めて、指定したアーティストが参加した作品全てを返すようです。)
// include_groups設定可能
getSpotifyData('/artists/1lYT0A0LV5DUfxr6doRP3d/albums?include_groups=compilation').then(
(data) => {
console.log('コンピレーションアルバム一覧:')
data.items.forEach(
(item) => console.log(`${item.name} (${item.release_date})`)
);
}
);
アルバム一覧:
Collection (2010-08-30)
Discover The Stone Roses (2008-07-25)
The Remixes (2000-11-21)
Turns Into Stone (1992-07-20)
Turns Into Stone (1992-07-20)
アーティストの人気トラックを取得
/artists/{id}/top-tracks(公式ドキュメント)
(ここで気づいたのですが、preview_urlは権利関係の問題があるのか、取得できないものもありました。その場合、認証済みのアクセストークンだと取得できました。(ユーザの地域情報などが関係しているのかも?))
// preview_urlは権利関係で認証が必要な場合アリ?
getSpotifyData('/artists/1nJvji2KIlWSseXRSlNYsC/top-tracks?market=JP').then(
(data) => {
console.log('人気トラック:')
data.tracks.forEach(
(item, index) => console.log(`${index + 1}. ${item.name} (${item.preview_url})`)
);
}
);
人気トラック:
1. Sunday Morning (undefined)
2. Pale Blue Eyes (undefined)
3. Femme Fatale (undefined)
4. After Hours (undefined)
5. I'll Be Your Mirror (undefined)
6. Oh! Sweet Nuthin' - 2015 Remaster (https://p.scdn.co/mp3-preview/15b552f995a2dc4ae6667c1d064c7b6e25145dad?cid=6adc70b663fe4d53ad2f40d3d8742594)
7. Rock & Roll - Full Length Version; 2015 Remaster (https://p.scdn.co/mp3-preview/c2c340fe345d619727b768059847807f35df175b?cid=6adc70b663fe4d53ad2f40d3d8742594)
8. I'm Waiting For The Man (undefined)
9. Sweet Jane - Full Length Version; 2015 Remaster (https://p.scdn.co/mp3-preview/14ede6c42e624a9bfcbd32accdb95a353c6b87d0?cid=6adc70b663fe4d53ad2f40d3d8742594)
10. Venus In Furs (undefined)
関連アーティストを取得
/artists/{id}/related-artists
(公式ドキュメント)
limitは設定不可(返ってくる数は20で固定のようです。)
// limitなし
getSpotifyData('/artists/7AC976RDJzL2asmZuz7qil/related-artists').then(
(data) => {
console.log('Yesの類似アーティスト:')
data.artists.forEach(
(item) => console.log(`${item.name} (${item.external_urls.spotify})`)
);
}
);
Yesの類似アーティスト:
Emerson, Lake & Palmer (https://open.spotify.com/artist/0nCiidE5GgDrc5kWN3NZgZ)
Jethro Tull (https://open.spotify.com/artist/6w6z8m4WXX7Tub4Rb6Lu7R)
Rick Wakeman (https://open.spotify.com/artist/0mkcYaXUbJUs5mJointuzB)
King Crimson (https://open.spotify.com/artist/7M1FPw29m5FbicYzS2xdpi)
Gentle Giant (https://open.spotify.com/artist/1hrQ50kU6hMQBVLatqUqnO)
Jon Anderson (https://open.spotify.com/artist/2iptQ8hQmUa7kZocEBHt7u)
Asia (https://open.spotify.com/artist/1bdytLV3FPjyhfrb6BhMej)
Camel (https://open.spotify.com/artist/3Uz6jx81OY2J5K8Z4wmy2P)
Genesis (https://open.spotify.com/artist/3CkvROUTQ6nRi9yQOcsB50)
Focus (https://open.spotify.com/artist/0ifzzRKdmtgaHy9cfnnyCR)
Rush (https://open.spotify.com/artist/2Hkut4rAAyrQxRdof7FVJq)
Steve Hackett (https://open.spotify.com/artist/4vs7NIU7kZc2Efh6yOGKEZ)
The Moody Blues (https://open.spotify.com/artist/5BcZ22XONcRoLhTbZRuME1)
The Alan Parsons Project (https://open.spotify.com/artist/2m62cc253Xvd9qYQ8d2X3d)
Peter Gabriel (https://open.spotify.com/artist/7C4sUpWGlTy7IANjruj02I)
Anderson Bruford Wakeman Howe (https://open.spotify.com/artist/2XTWgA3XVWe1N4qWBTNQei)
Kansas (https://open.spotify.com/artist/2hl0xAkS2AIRAu23TVMBG1)
Frank Zappa (https://open.spotify.com/artist/6ra4GIOgCZQZMOaUECftGN)
Van Der Graaf Generator (https://open.spotify.com/artist/02frazNrWgZCxUEf4UTfHt)
Steve Howe (https://open.spotify.com/artist/6W7XIO8Ua1RIisnSf0QIoI)
ジャンル
ジャンルのリストを取得
/recommendations/available-genre-seeds(公式ドキュメント)
おすすめ(recommendations)を取得する際に使用可能なジャンルのリストです。
// recommendationsに使用可能なジャンルパラメータ
getSpotifyData('/recommendations/available-genre-seeds').then(
(data) => {
let str = '';
data.genres.forEach((item, index) => {
str += item + ', '
if (index % 10 === 9 || index === data.genres.length - 1) {
console.log(str);
str = '';
}
});
}
);
acoustic, afrobeat, alt-rock, alternative, ambient, anime, black-metal, bluegrass, blues, bossanova,
brazil, breakbeat, british, cantopop, chicago-house, children, chill, classical, club, comedy,
country, dance, dancehall, death-metal, deep-house, detroit-techno, disco, disney, drum-and-bass, dub,
dubstep, edm, electro, electronic, emo, folk, forro, french, funk, garage,
german, gospel, goth, grindcore, groove, grunge, guitar, happy, hard-rock, hardcore,
hardstyle, heavy-metal, hip-hop, holidays, honky-tonk, house, idm, indian, indie, indie-pop,
industrial, iranian, j-dance, j-idol, j-pop, j-rock, jazz, k-pop, kids, latin,
latino, malay, mandopop, metal, metal-misc, metalcore, minimal-techno, movies, mpb, new-age,
new-release, opera, pagode, party, philippines-opm, piano, pop, pop-film, post-dubstep, power-pop,
progressive-house, psych-rock, punk, punk-rock, r-n-b, rainy-day, reggae, reggaeton, road-trip, rock,
rock-n-roll, rockabilly, romance, sad, salsa, samba, sertanejo, show-tunes, singer-songwriter, ska,
sleep, songwriter, soul, soundtracks, spanish, study, summer, swedish, synth-pop, tango,
techno, trance, trip-hop, turkish, work-out, world-music,
プレイリスト
プレイリスト情報を取得
/playlists/{playlist_id}(公式ドキュメント)
- 返ってくる情報が多いためか、
fieldsパラメータで取得情報のフィルタリングが可能
// fieldsで取得情報の選択可能
getSpotifyData('/playlists/37i9dQZF1DZ06evO3ZVhBv?fields=images,description,name,tracks.items.track(external_urls.spotify,name,album.name)').then(
(data) => {
console.log(`プレイリスト名: ${data.name}`);
console.log(`プレイリスト説明: ${data.description}`);
console.log(`プレイリスト画像: ${data.images[0].url}`);
console.log('トラック一覧:')
console.log('-'.repeat(85));
data.tracks.items.forEach(
(item) => {
console.log(`トラック名: ${item.track.name}`);
console.log(`URL: ${item.track.external_urls.spotify}`)
console.log(`アルバム: ${item.track.album.name}`);
console.log('-'.repeat(85));
}
);
}
);
プレイリスト名: This Is Syd Barrett
プレイリスト説明: This is Syd Barrett. The essential tracks, all in one playlist.
プレイリスト画像: https://thisis-images.spotifycdn.com/37i9dQZF1DZ06evO3ZVhBv-default.jpg
トラック一覧:
-------------------------------------------------------------------------------------
トラック名: Golden Hair
URL: https://open.spotify.com/track/3xZXSvOu4VDti8XXtFQOZF
アルバム: The Madcap Laughs
-------------------------------------------------------------------------------------
トラック名: Baby Lemonade
URL: https://open.spotify.com/track/2LGG2a9oUGJEwL3gzpbzAd
アルバム: Barrett
-------------------------------------------------------------------------------------
トラック名: Religious Experience (feat. Syd Barrett) (Singing a Song in the Morning)
URL: https://open.spotify.com/track/5aT7WtkgE3nkKQxtW9xWSs
アルバム: Joy Of A Toy
-------------------------------------------------------------------------------------
トラック名: Bob Dylan Blues - 2010 Remaster
URL: https://open.spotify.com/track/3jhwafaDF2N0Z0PoekWygE
アルバム: An Introduction To Syd Barrett
-------------------------------------------------------------------------------------
トラック名: Terrapin
URL: https://open.spotify.com/track/07QZXkXxtkjlm1GPxfH4gt
アルバム: The Madcap Laughs
-------------------------------------------------------------------------------------
トラック名: Dominoes
URL: https://open.spotify.com/track/2iQ2fs3joNeOhBMsxjw3x6
アルバム: Barrett
-------------------------------------------------------------------------------------
...
注目のプレイリストを取得
/browse/featured-playlists(公式ドキュメント)
limit、offsetを指定可能
getSpotifyData('/browse/featured-playlists?limit=5').then(
(data) => {
console.log(`${data.message} (total: ${data.playlists.total})`);
data.playlists.items.forEach(
(item, index) => {
console.log(`\n${index + 1}. ${item.name}`);
console.log(item.description);
}
);
}
);
Popular Playlists (total: 100)
1. Tokyo Super Hits!
The hottest hits in Japan right now. 日本のポップシーンを彩る最新ベスト50。Cover: なとり & imase
2. 令和ポップス
2019年に幕を開けた令和。ストリーミングや動画サイトでのバイラルが影響力を増し、社会情勢や価値観が激動している"ニューノーマル"な時代のポップミュージック。
3. This Is Mrs. GREEN APPLE
2015年にメジャーデビューしたロックバンド、Mrs.GREEN APPLEのオールタイム・ベスト。
4. Hot Hits Japan: 洋楽&邦楽ヒッツ
世界中のトレンドと日本の最新ヒット曲をまとめてお届けします。Cover: LISA & ROSALÍA
5. This Is back number
back numberのオール・タイム・ベスト。
指定されたカテゴリのプレイリストを取得
/browse/categories/{category_id}/playlists(公式ドキュメント)
limit、offsetを指定可能category_idパラメータに設定できるカテゴリは別のエンドポイント/browse/categories(Get Several Browse Categories | Spotify for Developers)で取得可能
// カテゴリ一覧は'/browse/categories'で取得可能
getSpotifyData('/browse/categories/dinner/playlists?limit=5').then(
(data) => {
console.log(`${data.message} (total: ${data.playlists.total})`);
data.playlists.items.forEach(
(item, index) => {
console.log(`\n${index + 1}. ${item.name}`);
console.log(item.description);
}
);
}
);
Cooking & Dining (total: 19)
1. ディズニー・ジャズ
誰もが知るディズニーの名曲達。Jazz初心者にも聴きやすい楽曲を中心に選曲。
2. Bossa Nova Dinner
Soundtrack your cozy dinner with bossa nova jazz.
3. Kitchen Swagger
Gettin' figgy with it, bana-na-na-nanana
4. Feel Good Dinner
An uplifting yet tasteful dinner playlist with a guaranteed feel good vibe.
5. Dinner Jazz
The gentle sound of some of the greatest voices and instrumentalists in Jazz.
Your Jazz dinner soundtrack.
プレイリストのカバー画像を取得
/playlists/{playlist_id}/images(公式ドキュメント)
getSpotifyData('/playlists/37i9dQZF1DWWGFQLoP9qlv/images').then(
(data) => {
console.log(`プレイリスト画像URL: ${data[0].url}`);
}
);
プレイリスト画像URL: https://i.scdn.co/image/ab67706f000000038c659b97eb3df5bfd03137fa
検索
アイテムの検索
/search(公式ドキュメント)
limit、offsetを指定可能qパラメータで検索語句を指定。album:やartist:、year:などでフィルタリングが可能。ドキュメントには書いてありませんが、引用符で完全一致検索も可能のようです。typeパラメータで検索対象のタイプをコンマ区切りで指定可能。(album,artist,playlist,track,show,episode,audiobook)
// ""(完全一致)が使える
getSpotifyData(('/search?q=Me artist:"The Beatles"&type=album,track,artist&limit=10&market=JP')).then(
(data) => {
console.log('-'.repeat(85));
for (const key in data) {
console.log(`Search Results [${key}] (total: ${data[key].total})`);
data[key].items.forEach(
(item) => {
let str = item.name;
if (item.artists?.[0].name) {
str += ` (${item.artists?.[0].name}`;
if (item.album?.name) str += `, "${item.album?.name}"`;
str += ')'
}
console.log(str);
}
);
console.log('-'.repeat(85));
}
}
);
-------------------------------------------------------------------------------------
Search Results [albums] (total: 12)
Please Please Me (Remastered) (The Beatles)
From Me To You (The Beatles Complete On Ukulele)
Love Me Do (Remix) (The Beatles Are Back)
Love Me Do (The Beatles Reloved)
Love Me Do (The Beatles Are Back)
Love Me Do (The Beatles Complete On Ukulele)
Can't Buy Me Love (The Beatles Complete On Ukulele)
Please Please Me (The Beatles Complete On Ukulele)
Please Please Me (The Beatles Complete On Ukulele)
Love Me Do (The Beatles)
-------------------------------------------------------------------------------------
Search Results [artists] (total: 1)
Memphis Loves The Beatles Studio Band
-------------------------------------------------------------------------------------
Search Results [tracks] (total: 100)
Love Me Do - Remastered 2009 (The Beatles, "Please Please Me (Remastered)")
Twist And Shout - Remastered 2009 (The Beatles, "Please Please Me (Remastered)")
Can't Buy Me Love - Remastered 2009 (The Beatles, "A Hard Day's Night (Remastered)")
Mean Mr Mustard - Remastered 2009 (The Beatles, "Abbey Road (Remastered)")
I Saw Her Standing There - Remastered 2009 (The Beatles, "Please Please Me (Remastered)")
Don't Let Me Down - Remastered 2009 (The Beatles, "The Beatles 1967 - 1970 (Remastered)")
Please Please Me - Remastered 2009 (The Beatles, "Please Please Me (Remastered)")
From Me To You - 2023 Mix (The Beatles, "The Beatles 1962 – 1966 (2023 Edition)")
Love Me Do - Mono / Remastered (The Beatles, "1 (Remastered)")
Do You Want To Know A Secret - Remastered 2009 (The Beatles, "Please Please Me (Remastered)")
-------------------------------------------------------------------------------------
トラック
トラック情報を取得
/tracks/{id}(公式ドキュメント)
getSpotifyData('/tracks/4vziJcnB2Qyi9o4nIRUeN7').then(
(data) => {
console.log(`トラック名: ${data.name}`);
console.log(`URL: ${data.external_urls.spotify}`);
console.log(`アルバム名: ${data.album.name} (${data.album.release_date})`);
console.log(`アーティスト名: ${data.artists[0].name}`);
}
);
トラック名: Now And Then
URL: https://open.spotify.com/track/4vziJcnB2Qyi9o4nIRUeN7
アルバム名: Now And Then (2023-11-02)
アーティスト名: The Beatles
複数のトラック情報を取得
/tracks(公式ドキュメント)
- 複数のトラックIDをコンマ区切りで
idsパラメータに指定(最大50)
// 最大50
const trackIds = [
'21YxK0klhpfLW8budkJaMF','50mL6pbI0uI6YX1xbSer7g','3N8p0hzXZ0EF0OoDGFh5G9',
'6guf5rr036GUC94cF4725F','7j5Q3zhjvpQvMeoPSZwdsa','6WPGAupim73K9XQL4iIefZ',
'5hsT7bcfNJZ4JgxQ75zXRo','4TOMI010Sd4ZAX4aZ5TS85','5vxuXTCpJEcegbB6WZWyLQ',
'2foOeJLKSvepjHEkb4NR8N','3DYnqG3jqB1bijSKsJzuzG','3bUNyRrTFJDd4mqvUcb1Aa'
];
getSpotifyData(`/tracks?ids=${trackIds.join(',')}`).then(
(data) => {
console.log('トラック一覧:')
data.tracks.forEach(
(item) => console.log(`${item.name} (${item.artists[0].name}, "${item.album.name}")`)
);
}
);
トラック一覧:
Lust For Life (Iggy Pop, "Lust For Life")
Deep Blue Day - Remastered 2005 (Brian Eno, "Apollo")
Trainspotting (Primal Scream, "Vanishing Point (Expanded Edition)")
Atomic (Sleeper, "Inbetweener - The Best of Sleeper")
Temptation (New Order, "Substance")
Nightclubbing (Iggy Pop, "The Idiot")
Sing - 2012 Remaster (Blur, "Leisure")
Perfect Day (Lou Reed, "Transformer")
Dark & Long - Dark Train / Remastered 2014 (Underworld, "A Collection 2")
Think About the Way (Ice Mc, "Ice 'n' Green")
Mile End - From 'Trainspotting' Original Motion Picture Soundtrack (Pulp, "Different Class / Deluxe Edition")
Born Slippy (Nuxx) - Radio Edit (Underworld, "Born Slippy (Nuxx) [Radio Edit]")
トラックの特徴量を取得
/audio-features/{id}(公式ドキュメント)
getSpotifyData('/audio-features/5MWfv4F84sJhScYq18yqbN').then(
(data) => {
console.log('特徴量:');
for (const key in data) {
typeof data[key] === 'number' && console.log(`${key}: ${data[key]}`);
}
}
);
特徴量:
danceability: 0.24
energy: 0.546
key: 2
loudness: -10.026
mode: 1
speechiness: 0.0548
acousticness: 0.0898
instrumentalness: 0.00648
liveness: 0.0898
valence: 0.429
tempo: 181.373
duration_ms: 388667
time_signature: 4
複数のトラックの特徴量を取得
/audio-features(公式ドキュメント)
- 複数のトラックIDをコンマ区切りで
idsパラメータに指定(最大100)
const trackIds = [
'5MWfv4F84sJhScYq18yqbN', '5RPiBNQVmuEm7YlVVotrLa', '6AhZVsDudTq5KdJ5LbE32f'
];
getSpotifyData(`/audio-features?ids=${trackIds.join(',')}`).then(
(data) => {
console.log('Acousticness:');
data.audio_features.forEach(
(item, index) => console.log(`${index}. ${item.acousticness}`)
);
}
);
Acousticness:
0. 0.0898
1. 0.351
2. 0.687
トラックの分析情報を取得
/audio-analysis/{id}(公式ドキュメント)
- 特徴量よりもより詳細なトラックの分析情報。詳細かつ情報量が膨大過ぎて、正直、扱うのが難しい気がします。
getSpotifyData('/audio-analysis/71LsKf3xISiOlY1mj7FFPP').then(
(data) => {
console.log(`サンプル数: ${data.track.num_samples}`);
}
);
サンプル数: 3628254
条件を指定しておすすめを取得
/recommendations(公式ドキュメント)
limitを指定可能- シード値となるアーティスト(
seed_artists)、ジャンル(seed_genres)、トラック(seed_tracks)をそれぞれコンマ区切りで指定(全て合計して5つまで) - 特徴量によるフィルタリングも可能(
min_energy、max_energy、target_energyなど)
getSpotifyData('/recommendations?seed_genres=techno&seed_tracks=1bWvunARtOgGA78p1a8W1O&min_energy=0.8&limit=5').then(
(data) => {
console.log('おすすめ一覧:');
console.log('-'.repeat(85));
data.tracks.forEach(
(item, index) => {
console.log(`${index + 1}. ${item.name} (${item.artists[0].name}, "${item.album.name}")`);
console.log(`URL: ${item.external_urls.spotify}`);
console.log(`プレビュー: ${item.preview_url}`);
console.log('-'.repeat(85));
}
);
}
);
おすすめ一覧:
-------------------------------------------------------------------------------------
1. We'll Be Coming Back (feat. Example) (Calvin Harris, "18 Months")
URL: https://open.spotify.com/track/7B1Dl3tXqySkB8OPEwVvSu
プレビュー: https://p.scdn.co/mp3-preview/6e203c4db9b8d807282a610240d980d3f5f60a72?cid=6adc70b663fe4d53ad2f40d3d8742594
-------------------------------------------------------------------------------------
2. Serenity (Popof, "Serenity")
URL: https://open.spotify.com/track/1kDqntrhTIOeFyuQAJfTs0
プレビュー: https://p.scdn.co/mp3-preview/d6ccfcdf4eff5f3dbb7dc54d27b5145fc029b8aa?cid=6adc70b663fe4d53ad2f40d3d8742594
-------------------------------------------------------------------------------------
3. Tsunami (DVBBS, "Tsunami")
URL: https://open.spotify.com/track/2xMS1khdU5FHX1KEiNTVdi
プレビュー: null
-------------------------------------------------------------------------------------
4. A Day In The Radio (Plus-Tech Squeeze Box, "FAKEVOX")
URL: https://open.spotify.com/track/6m510niRjEWVZHDHnloMXO
プレビュー: https://p.scdn.co/mp3-preview/05e3f7d38812b2c59fd0adf70780dc95aa3f6bd7?cid=6adc70b663fe4d53ad2f40d3d8742594
-------------------------------------------------------------------------------------
5. Lovecraft (Adam Beyer, "The Color Out of Space")
URL: https://open.spotify.com/track/3cXFOC8LAtFNmMSgUuokBy
プレビュー: null
-------------------------------------------------------------------------------------
おわりに
Spotify Web APIの使い方を一通り学べたので、次回からWebアプリの制作に入っていきます。
次回の記事↓
