npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

spotify-api-lib

v1.1.0

Published

A modern, TypeScript-first wrapper for the Spotify Web API with organized endpoint categories and full type safety

Downloads

19

Readme

Spotify Web API TypeScript Library

A modern, TypeScript-first wrapper for the Spotify Web API with organized endpoint categories and full type safety.

Features

  • 🎯 Full TypeScript Support - Complete type definitions for all Spotify API responses
  • 🏗️ Organized Structure - Endpoints grouped by category (playlists, tracks, albums, etc.)
  • 🔧 Modern ES6+ - Built with modern JavaScript features
  • 📦 Dual Package - Supports both ESM and CommonJS
  • 🚀 Zero Dependencies - Only uses axios as peer dependency
  • 🎵 Complete Coverage - All major Spotify Web API endpoints

Installation

npm install spotify-api-lib
# or
yarn add spotify-api-lib

Peer Dependency:

npm install axios

Quick Start

import SpotifyApi from 'spotify-api-lib';

// Initialize with access token
const spotify = new SpotifyApi('your_access_token');

// Use organized endpoint groups
const playlists = await spotify.playlists.getUserPlaylists();
const album = await spotify.albums.getById('album_id');
const tracks = await spotify.tracks.getSavedTracks();

API Reference

Constructor

new SpotifyApi(accessToken?: string)

Endpoint Categories

Playlists

spotify.playlists.getUserPlaylists()
spotify.playlists.getById(playlistId)
spotify.playlists.getTracks(playlistId, options?)
spotify.playlists.create(userId, details)
spotify.playlists.addTracks(playlistId, trackUris)

Albums

spotify.albums.getById(albumId)
spotify.albums.getTracks(albumId, options?)
spotify.albums.getSavedAlbums(options?)
spotify.albums.saveAlbums(albumIds)

Tracks

spotify.tracks.getById(trackId)
spotify.tracks.getSavedTracks(options?)
spotify.tracks.saveTracks(trackIds)
spotify.tracks.getAudioFeatures(trackIds)

Artists

spotify.artists.getById(artistId)
spotify.artists.getTopTracks(artistId, market?)
spotify.artists.getAlbums(artistId, options?)
spotify.artists.getRelatedArtists(artistId)

Search

spotify.search.search(query, types, options?)
spotify.search.searchTracks(query, options?)
spotify.search.searchAlbums(query, options?)
spotify.search.searchArtists(query, options?)

Player

spotify.player.getCurrentTrack()
spotify.player.getPlaybackState()
spotify.player.play(options?)
spotify.player.pause()
spotify.player.next()
spotify.player.previous()

User

spotify.user.getProfile()
spotify.user.getTopTracks(options?)
spotify.user.getTopArtists(options?)

Authentication

This library handles API requests but doesn't manage OAuth flow. You need to obtain access tokens through Spotify's OAuth 2.0 flow.

Example with PKCE (recommended for client-side apps):

// After OAuth flow, initialize with token
const spotify = new SpotifyApi(accessToken);

// Update token when refreshed
spotify.setAccessToken(newAccessToken);

TypeScript Support

All Spotify API responses are fully typed:

import SpotifyApi, { SpotifyTrack, SpotifyAlbum, SpotifyPlaylist } from 'spotify-api-lib';

const spotify = new SpotifyApi(token);

// Fully typed responses
const track: SpotifyTrack = await spotify.tracks.getById('track_id');
const album: SpotifyAlbum = await spotify.albums.getById('album_id');
const playlists: SpotifyPlaylist[] = await spotify.playlists.getUserPlaylists();

Error Handling

The library throws errors for failed API requests:

try {
  const track = await spotify.tracks.getById('invalid_id');
} catch (error) {
  if (error.response?.status === 404) {
    console.log('Track not found');
  } else if (error.response?.status === 401) {
    console.log('Invalid or expired token');
  }
}

Advanced Usage

Direct HTTP Client Access

import { SpotifyHttpClient } from 'spotify-api-lib';

const client = new SpotifyHttpClient(accessToken);
const response = await client.get('/me/playlists');

Custom Requests

const spotify = new SpotifyApi(token);

// Access underlying HTTP client for custom requests
const customData = await spotify.httpClient.get('/custom/endpoint');

Rate Limiting

The library doesn't implement rate limiting. Spotify's API has rate limits, so implement appropriate delays in your application:

// Example: Add delay between requests
async function fetchMultipleAlbums(albumIds: string[]) {
  const albums = [];
  for (const id of albumIds) {
    albums.push(await spotify.albums.getById(id));
    await new Promise(resolve => setTimeout(resolve, 100)); // 100ms delay
  }
  return albums;
}

Examples

Get User's Top Artists and Tracks

const spotify = new SpotifyApi(accessToken);

const [topArtists, topTracks] = await Promise.all([
  spotify.user.getTopArtists({ limit: 10, time_range: 'medium_term' }),
  spotify.user.getTopTracks({ limit: 10, time_range: 'medium_term' })
]);

console.log('Top Artists:', topArtists.items.map(a => a.name));
console.log('Top Tracks:', topTracks.items.map(t => t.name));

Create and Populate a Playlist

const user = await spotify.user.getProfile();
const playlist = await spotify.playlists.create(user.id, {
  name: 'My New Playlist',
  description: 'Created with spotify-api-lib',
  public: false
});

const trackUris = ['spotify:track:4iV5W9uYEdYUVa79Axb7Rh', 'spotify:track:1301WleyT98MSxVHPZCA6M'];
await spotify.playlists.addTracks(playlist.id, trackUris);

Search and Save Albums

const searchResults = await spotify.search.searchAlbums('Random Access Memories', { limit: 5 });
const album = searchResults.albums.items[0];

if (album) {
  await spotify.albums.saveAlbums([album.id]);
  console.log(`Saved album: ${album.name} by ${album.artists[0].name}`);
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details.

Related