Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8886

Spotify Web API を Node.js で弄ってみる

$
0
0

Spotify Web API を Node.js で弄ってみる

Spotify に Web API があるのを知ったので node.js で試してみた手順まとめ。

Web API Tutorial

Web API Tutorialを参考にすすめていく事にします。

Dashboard を有効にする。

Dashboardにアクセスして Spotify アカウントでログインして Dashboard を有効にする。下のような画面が表示されるはず。
スクリーンショット 2019-10-30 9.08.08.png

アプリ作成

"CREATE AN APP" を押して各 必須 項目をうめる。
Redirect URIshttp://localhost:8888/を登録する。
スクリーンショット 2019-10-30 9.11.21.png

Client ID / Client Secret を確認する

スクリーンショット 2019-10-30 9.28.50.png

認証トークンを取得する

web-api-auth-examples
Spotifyから提供されている認証サンプルのコードで認証トークンを取得する。

  1. authorization_code
git clone https://github.com/spotify/web-api-auth-examples
cd web-api-auth-examples
npm install
  1. clone 後に authorization_code/app.js の クライアントIDなどを書き換える。
    redirect_urihttp://localhost:8888
cd authorization_code
open app.js

〜
var client_id = 'CLIENT_ID'; // Your client id
var client_secret = 'CLIENT_SECRET'; // Your secret
var redirect_uri = 'REDIRECT_URI'; // Your redirect uri
〜
  1. 実行して ブラウザで localhost:8888 にアクセスする。 node app.js

スクリーンショット 2019-10-30 10.03.40.png

  1. Log in with Spotifyにアクセスして認証トークンを取得する。 スクリーンショット 2019-10-30 10.12.54.png

認証が成功すると localhost:8888codeパラーメタ付きでリダイレクトされる。
この codeパラメータの値が 認証トークン です。

Spotify Web API Node

Spotify Web API Node
node.js から Spotify Web API に アクセスするためのライブラリがあったので試してみます。

var SpotifyWebApi = require('spotify-web-api-node');

const authorizationCode = 'AQCYDgG5bNJ_...';

// credentials are optional
var spotifyApi = new SpotifyWebApi({
  clientId: '10ca96700c...',
  clientSecret: 'e8e5940c...',
  redirectUri: 'http://localhost:8888'
});

spotifyApi
  .authorizationCodeGrant(authorizationCode)
  .then(function(data) {
    console.log('Retrieved access token', data.body['access_token']);
    spotifyApi.setAccessToken(data.body['access_token']);
    return spotifyApi.searchTracks('Love');
  })
  .then(function(data) {
    console.log('I got ' + data.body.tracks.total + ' results!');

    var firstPage = data.body.tracks.items;
    console.log(
      'The tracks in the first page are.. (popularity in parentheses)'
    );

    firstPage.forEach(function(track, index) {
      console.log(index + ': ' + track.name + ' (' + track.popularity + ')');
    });
  })
  .catch(function(err) {
    console.log('Something went wrong:', err.message);
  });

実行成功すると LOVEで検索した トラック一覧が表示されます。
スクリーンショット 2019-10-30 10.22.41.png

参考

音楽系API(主に音楽配信サービス)まとめ

水曜日 #nijuni朝活

毎週 水曜日に nijuni朝活 やってます。 この Qiita も 朝活中に 作ったものです。


Viewing all articles
Browse latest Browse all 8886

Trending Articles