0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SpotifyAPIのラッパーを色々試したけど、直接APIを叩いている件

Last updated at Posted at 2025-12-20

はじめに

この記事はQiita Advent Calendar 2025 / ひとりアドベントカレンダー 分野における ふぐおの配信関係多めひとり Advent Calendar 2025 の21日目の記事となります。

配信内で使用しているツールの中でのSpotify連携部分についてお話します。

試した(調べた)ライブラリ

Spotipy

個人的に一番クオリティーが高いなと感じたライブラリです。

内部でトークンの自動更新も行ってくれます。
ただ、Python製ということだけが個人的にネックでした。今使っているツールがNode.js製なので、わざわざこの機能のためにPythonスクリプトを走らせる必要があるからです。

特定の言語縛りではないのなら、このライブラリです。

Spotify Web API Node

spotify-web-api-nodeはNode.js製のSpotifyAPIラッパーです。
ただ、更新が5年以上止まっているのが気になります。

spotified

spotifiedもNode.js製のSpotifyAPIラッパーです。
こちらは定期的に更新されており、メンテナンスされている印象です。
ただし、私が使いたかった再生中のキューに曲を追加する機能にバグがあり、使用を見送りました。

spotify-web-api-ts-sdk

Spotify公式のTypeScript製SpotifyAPIラッパーです。
webアプリケーション向けに作られている印象で、Node.js環境で使うには少し工夫が必要そうです。
アクセストークンの認証の部分で結局、APIを直接叩く必要があり、使用を見送りました。

APIを直接叩く方法

リフレッシュトークンを取得する方法

今回はCLIツールでの運用なので、Authorization Code Flowを使います。用途によって、認証方式が変わるので、公式ドキュメントを参照してください。
SpotifyAPIにはアクセストークンとリフレッシュトークンの2種類のトークンがあります。
リフレッシュトークンの取得は以下の記事のように、リダイレクトされたURLの末尾をコピーしてくるのが簡単です。

アクセストークンの取得方法

const CLIENT_ID = 'あなたのClientID';
const CLIENT_SECRET = 'あなたのClientSecret';
const REFRESH_TOKEN = '取得済みのRefresh Token';

async function refreshMyToken(refreshToken: string): Promise<string> {
    const params = new URLSearchParams();
    params.append('grant_type', 'refresh_token');
    params.append('refresh_token', refreshToken);

    const authHeader = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64');

    const response = await fetch('https://accounts.spotify.com/api/token', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': `Basic ${authHeader}`
        },
        body: params
    });

    if (!response.ok) {
        const text = await response.text();
        throw new Error(`トークン更新失敗: ${text}`);
    }

    const data = await response.json();
    return data.access_token;
}

キューに曲を追加する方法

async function addToQueueRaw(accessToken: string, trackUri: string) {
    // クエリパラメータに uri を入れる必要があります
    const url = `https://api.spotify.com/v1/me/player/queue?uri=${encodeURIComponent(trackUri)}`;

    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${accessToken}`
        }
    });

    if (response.ok) {
        console.log("✅ キューに追加成功しました! (Status: 204)");
        return;
    }

    const errorText = await response.text();
    console.error(`❌ エラーが発生しました: ${response.status} ${response.statusText}`);
    console.error(`エラー内容: ${errorText}`);
}

実行コードの例

(async () => {
    try {
        const accessToken = await refreshMyToken(REFRESH_TOKEN);
        console.log("アクセストークン取得完了");
        await addToQueueRaw(accessToken, 'spotify:track:4iV5W9uYEdYUVa79Axb7Rh');

    } catch (e) {
        console.error("エラー:", e);
    }
})();

まとめ

そこまでガッツリAPIを叩くわけではないので、SDKなどを使わずに直接APIを叩く方法で十分でした。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?