• Stars
    star
    312
  • Rank 131,664 (Top 3 %)
  • Language
    TypeScript
  • License
    Other
  • Created over 1 year ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Typescript SDK for the Spotify Web API with types for returned data.

Spotify Web API SDK - TypeScript

This is a JavaScript/TypeScript SDK for the Spotify Web API.

Requirements

Because this SDK uses fetch both in Node and the Browser, and ESM, we require the following:

  • Node 18.0.0 or higher
  • A modern, version infinite, browser

The package contains both an ESM and CommonJS build, so you can use it in both Node and the Browser.

Using this in your project

npm install @spotify/web-api-ts-sdk

Running the example app

First install the dependencies:

npm install

Create a .env file in the example directory with your client_id and redirect url:

VITE_SPOTIFY_CLIENT_ID=your_spotify_client_id_for_tests
VITE_REDIRECT_TARGET=http://localhost:3000

To run the app:

npm run start

Creating a client instance

Creating an instance of the SDK is easy, and can be done in a number of ways depending on which form of authentication you want to use.

import { SpotifyApi } from '@spotify/web-api-ts-sdk';

// Choose one of the following:
const sdk = SpotifyApi.withUserAuthorization("client-id", "https://localhost:3000", ["scope1", "scope2"]);
const sdk = SpotifyApi.withClientCredentials("client-id", "secret", ["scope1", "scope2"]);

Each of these factory methods will return a SpotifyApi instance, which you can use to make requests to the Spotify Web API.

Once you have an authenticated instance of the SDK, you can make requests to the Spotify Web API by using the methods exposed on the client instance of the API. Types are embedded in the package, so if you're using Visual Studio Code or other compatible IDEs, you should get intellisense and type checking by default.

const items = await sdk.search("The Beatles", ["artist"]);

console.table(items.artists.items.map((item) => ({
    name: item.name,
    followers: item.followers.total,
    popularity: item.popularity,
})));

Authentication Methods

  • Authorization Code Flow with PKCE
  • Client Credentials Flow
  • Implicit Grant Flow
  • Mixed Server and Client Side Authentication

We do auto-token refresh when expired and a refresh token is available.

Picking an Authentication Method

If you're building a browser based application, you should use Authorization Code Flow with PKCE. This is the most secure way to authenticate your users and handles the redirection from your app to Spotify and back. Your server side code will not have access to the Spotify API with user access scopes, but you can use the SDK to perform client side requests with the users access token.

Calling any of the methods on the SDK will automatically perform any redirects/refreshes that are necessary.

const sdk = SpotifyApi.withUserAuthorization("client-id", "https://localhost:3000", ["scope1", "scope2"]);
const user = await sdk.currentUser.profile()

If you're building a server side application, you should use Client Credentials Flow, and is the correct choice when you have both your Client ID and Client Secret available. This flow is not available in the browser (as you should not embed your Client Secret in Client Side web applications), so should only be used from Node.js.

Mixed Server and Client Side Authentication is a special case, and is covered in the section below. This is useful if you want to perform requests with a users access token from your server side code.

Mixed Server and Client Side Authentication

There's capabilities in the client if you want to interact with Spotify from your Node.js server, but perform a client side Authorization Code Flow with PKCE. You might want to do this if you want your server side SDK instance to be authorized "as a specific user" to interact with user data.

You'll need to do three things.

  1. Perform Authorization Code Flow with PKCE using some special helper functions
  2. Expose a URL from your Node.js application that accepts a token post-back
  3. Initilise an instance of the SDK with the posted-back token

Setup:

Client Side

SpotifyApi.performUserAuthorization("client-id", "https://localhost:3000", ["scope1", "scope2"], "https://your-backend-server.com/accept-user-token");
// Alternatively if you want to perform your own custom post-back
SpotifyApi.performUserAuthorization("client-id", "https://localhost:3000", ["scope1", "scope2"], (accessToken) => { /* do postback here */ });

These functions will work as usual, triggering a client side redirect to grant permissions, along with verifying the response and performing token exchange.

Server Side

const { SpotifyApi } = require("@spotify/web-api-ts-sdk");

const express = require('express');
const bodyParser = require('body-parser'); 
const app = express();
 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

let sdk;

app.post('/accept-user-token', (req, res) => {
    let data = req.body;
    sdk = SpotifyApi.withAccessToken("client-id", data); // SDK now authenticated as client-side user
}); 
 
app.listen(3000, () => {
  console.log('Example app listening on port 3000!')
});

Check out our blog post for more examples using ES Modules or CommonJS

Extensibility

All of the constructors support a configuration object that lets you override the default behavior of the SDK.

Our defaults look like this, and each of the properties is optional, and can be overridden.

const defaultConfig: SdkConfiguration = {
    fetch: (req: RequestInfo | URL, init: RequestInit | undefined) => fetch(req, init),
    beforeRequest: (_: string, __: RequestInit) => { },
    afterRequest: (_: string, __: RequestInit, ___: Response) => { },
    deserializer: new DefaultResponseDeserializer(),
    responseValidator: new DefaultResponseValidator(),
    errorHandler: new NoOpErrorHandler(),
    redirectionStrategy: new DocumentLocationRedirectionStrategy(),
    cachingStrategy: isBrowser
        ? new LocalStorageCachingStrategy()
        : new InMemoryCachingStrategy()
};

As a general rule, this options should be overridden when you create your instance of the client, and you probably won't have to change any of them unless you have some very specific requirements.

You can provide the options like this, to any of the constructors or static initilisation methods:

const opts = {
    fetch: (req, init) => {
        console.log("Called via my custom fetch!");
        return fetch(req, init);
    }
}

const sdk = SpotifyApi.withUserAuthorization("client-id", "https://callback", ["scope1"], opts);

All the below examples are in TypeScript, but the same method signatures all apply to JavaScript - just without the Type information.

Extensibility - fetch

You can override the default Fetch implementation by passing in a function that takes a RequestInfo and RequestInit and returns a Promise<Response>. By default, we use the browser and nodes built in fetch implementation.

const opts = {
    fetch: (req, init) => {
        // Do something with the request
        return fetch(req, init);
    }
}

Extensibility - beforeRequest and afterRequest

You can override the default beforeRequest and afterRequest callbacks by passing in functions that take a RequestInfo and RequestInit and return nothing. By default, we do nothing.

You can use these functions to implement custom instrumentation, logging, or other functionality.

const opts = {
    beforeRequest: (req, init) => {
        console.log("Called before the request is made");
    },
    afterRequest: (req, init, res) => {
        console.log("Called after the request is made");
    }
}

Extensibility - deserializer

You can override the default deserializer by passing in a class that implements the IResponseDeserializer interface. By default, we use the DefaultResponseDeserializer class.

To implement your own, you need to provide an object with the following method signature:

async deserialize<TReturnType>(response: Response): Promise<TReturnType> {
    // Implement your custom deserialization logic here
}

You'll probably never need to do this unless you feel the need to add custom logging around deserialization behaviour or wish to customise the default objects returned during serialization failures.

Extensibility - responseValidator

You can override the default response validator by passing in a class that implements the IValidateResponses interface. By default, we use the DefaultResponseValidator class.

Our default impelementation validates the following:

  • The response status code is in the 200 range
  • Errors are thrown for 400 and 500 range status codes
  • Non-200 response codes throw errors with the API response body inside of them

If you need to customise this behaviour, replace the implementation like this:

export default class MyResponseValidator implements IValidateResponses {
    public async validateResponse(response: Response): Promise<void> {
        // Something here
    }
}

Extensibility - errorHandler

You can override the default error handler by passing in a class that implements the IHandleErrors interface. By default, we use the NoOpErrorHandler class which... does nothing!

If you need to customise this behaviour, replace the implementation like this:

export default class MyErrorHandler implements IHandleErrors {
    public async handleErrors(error: any): Promise<boolean> {
        return false;
    }
}

If you return true from your error handler, the SDK will not throw an error, and treat it as handleed, returning null from the request that triggered it. Returning false will re-throw the original error after your handler has run.

Extensibility - redirectionStrategy

You can override the default redirection strategy by passing in a class that implements the IRedirect interface. By default, we use the DocumentLocationRedirectionStrategy class.

export default class DocumentLocationRedirectionStrategy implements IRedirectionStrategy {
    public async redirect(targetUrl: string | URL): Promise<void> {
        document.location = targetUrl.toString();
    }

    public async onReturnFromRedirect(): Promise<void> {
    }
}

You might want to override this behaviour if you use a client side framework like React or Vue and you need to record some state, or trigger some operation before the redirect for oAuth / token exchange happens. For example - you might want to add something to localStorage that you can read back when the user returns to the application.

Extensibility - cachingStrategy

You can override the default caching strategy by passing in a class that implements the ICache interface. By default, we use the LocalStorageCachingStrategy class.

interface ICachingStrategy {
    getOrCreate<T>(cacheKey: string, createFunction: () => Promise<T & ICachable & object>): Promise<T & ICachable>;
    get<T>(cacheKey: string): T & ICachable | null;
    setCacheItem<T>(cacheKey: string, item: T & ICachable): void;
    remove(cacheKey: string): void;
}

We provide a default browser (localStorage) caching strategy and (TODO) a node in-memory caching strategy.

Running the tests

To run the tests, you need to have a Spotify account.

You will need to create a new app in the Spotify Developer portal, and add a redirect URI of http://localhost:3000.

You will need to add the following environment variables:

  • INTEGRATION_TESTS_SPOTIFY_CLIENT_ID
  • INTEGRATION_TESTS_SPOTIFY_CLIENT_SECRET
  • INTEGRATION_TESTS_USER_EMAIL
  • INTEGRATION_TESTS_USER_PASSWORD

The latter two credentials are used to run integration tests in the scope of a real user account. This is required to test endpoints that require a user's authorization, such as followPlaylist. You need to make sure that your user has access to whichever Spotify app your client credentials and secret are for.

You can run the tests with npm run test, or using a plugin like Wallaby.

We support dotenv, so you can add these to a .env file in the root of the repository.

To run the embedded example app, you will need to add the following environment variables:

  • VITE_SPOTIFY_CLIENT_ID=the same value as set in INTEGRATION_TESTS_SPOTIFY_CLIENT_ID
  • VITE_REDIRECT_TARGET=http://localhost:3000

For the example app to work, this .env file needs to be in the ./example folder.

More Repositories

1

luigi

Luigi is a Python module that helps you build complex pipelines of batch jobs. It handles dependency resolution, workflow management, visualization etc. It also comes with Hadoop support built in.
Python
17,340
star
2

annoy

Approximate Nearest Neighbors in C++/Python optimized for memory usage and loading/saving to disk
C++
12,751
star
3

docker-gc

INACTIVE: Docker garbage collection of containers and images
Shell
5,068
star
4

pedalboard

🎛 🔊 A Python library for audio.
C++
4,964
star
5

chartify

Python library that makes it easy for data scientists to create charts.
Python
3,486
star
6

basic-pitch

A lightweight yet powerful audio-to-MIDI converter with pitch bend detection
Python
2,972
star
7

dockerfile-maven

MATURE: A set of Maven tools for dealing with Dockerfiles
Java
2,748
star
8

docker-maven-plugin

INACTIVE: A maven plugin for Docker
Java
2,652
star
9

scio

A Scala API for Apache Beam and Google Cloud Dataflow.
Scala
2,485
star
10

helios

Docker container orchestration platform
Java
2,097
star
11

web-api-examples

Basic examples to authenticate and fetch data using the Spotify Web API
HTML
1,889
star
12

HubFramework

DEPRECATED – Spotify’s component-driven UI framework for iOS
Objective-C
1,863
star
13

apollo

Java libraries for writing composable microservices
Java
1,648
star
14

dh-virtualenv

Python virtualenvs in Debian packages
Python
1,601
star
15

docker-client

INACTIVE: A simple docker client for the JVM
Java
1,429
star
16

docker-kafka

Kafka (and Zookeeper) in Docker
Shell
1,402
star
17

SPTPersistentCache

Everyone tries to implement a cache at some point in their iOS app’s lifecycle, and this is ours.
Objective-C
1,243
star
18

mobius

A functional reactive framework for managing state evolution and side-effects.
Java
1,213
star
19

voyager

🛰️ An approximate nearest-neighbor search library for Python and Java with a focus on ease of use, simplicity, and deployability.
C++
1,175
star
20

sparkey

Simple constant key/value storage library, for read-heavy systems with infrequent large bulk inserts.
C
1,153
star
21

ruler

Gradle plugin which helps you analyze the size of your Android apps.
Kotlin
1,118
star
22

XCMetrics

XCMetrics is the easiest way to collect Xcode build metrics and improve developer productivity.
Swift
1,095
star
23

web-api

This issue tracker is no longer used. Join us in the Spotify for Developers forum for support with the Spotify Web API ➡️ https://community.spotify.com/t5/Spotify-for-Developers/bd-p/Spotify_Developer
RAML
981
star
24

echoprint-codegen

Codegen for Echoprint
C++
948
star
25

snakebite

A pure python HDFS client
Python
858
star
26

heroic

The Heroic Time Series Database
Java
843
star
27

klio

Smarter data pipelines for audio.
Python
832
star
28

XCRemoteCache

Swift
824
star
29

ios-sdk

Spotify SDK for iOS
Objective-C
627
star
30

apps-tutorial

A Spotify App that contains working examples of the use of Spotify Apps API
627
star
31

SPTDataLoader

The HTTP library used by the Spotify iOS client
Objective-C
626
star
32

postgresql-metrics

Tool that extracts and provides metrics on your PostgreSQL database
Python
588
star
33

JniHelpers

Tools for writing great JNI code
C++
587
star
34

Mobius.swift

A functional reactive framework for managing state evolution and side-effects [Swift implementation]
Swift
556
star
35

reactochart

📈 React chart component library 📉
JavaScript
551
star
36

dockerfile-mode

An emacs mode for handling Dockerfiles
Emacs Lisp
528
star
37

threaddump-analyzer

A JVM threaddump analyzer
JavaScript
485
star
38

featran

A Scala feature transformation library for data science and machine learning
Scala
465
star
39

android-sdk

Spotify SDK for Android
HTML
449
star
40

echoprint-server

Server for the Echoprint audio fingerprint system
Java
396
star
41

completable-futures

Utilities for working with futures in Java 8
Java
382
star
42

web-scripts

DEPRECATED: A collection of base configs and CLI wrappers used to speed up development @ Spotify.
TypeScript
381
star
43

SpotifyLogin

Swift framework for authenticating with the Spotify API
Swift
346
star
44

ratatool

A tool for data sampling, data generation, and data diffing
Scala
337
star
45

fmt-maven-plugin

Opinionated Maven Plugin that formats your Java code.
Java
309
star
46

big-data-rosetta-code

Code snippets for solving common big data problems in various platforms. Inspired by Rosetta Code
Scala
287
star
47

trickle

A small library for composing asynchronous code
Java
284
star
48

coordinator

A visual interface for turning an SVG into XY coördinates.
HTML
283
star
49

pythonflow

🐍 Dataflow programming for python.
Python
281
star
50

styx

"The path to execution", Styx is a service that schedules batch data processing jobs in Docker containers on Kubernetes.
Java
266
star
51

cstar

Apache Cassandra cluster orchestration tool for the command line
Python
255
star
52

netty-zmtp

A Netty implementation of ZMTP, the ZeroMQ Message Transport Protocol.
Java
242
star
53

ios-style

Guidelines for iOS development in use at Spotify
241
star
54

confidence

Python
238
star
55

cassandra-reaper

Software to run automated repairs of cassandra
235
star
56

docker-cassandra

Cassandra in Docker with fast startup
Shell
220
star
57

terraform-gke-kubeflow-cluster

Terraform module for creating GKE clusters to run Kubeflow
HCL
209
star
58

basic-pitch-ts

A lightweight yet powerful audio-to-MIDI converter with pitch bend detection.
TypeScript
206
star
59

dns-java

DNS wrapper library that provides SRV lookup functionality
Java
204
star
60

linux

Spotify's Linux kernel for Debian-based systems
C
204
star
61

git-test

test your commits
Shell
202
star
62

SPStackedNav

[DEPRECATED] Navigation controller which represents its content in stacks of panes, rather than one at a time
Objective-C
195
star
63

spotify-json

Fast and nice to use C++ JSON library.
C++
194
star
64

quickstart

A CommonJS module resolver, loader and compiler for node.js and browsers.
JavaScript
193
star
65

dbeam

DBeam exports SQL tables into Avro files using JDBC and Apache Beam
Java
188
star
66

flink-on-k8s-operator

Kubernetes operator for managing the lifecycle of Apache Flink and Beam applications.
Go
180
star
67

lingon

A user friendly tool for building single-page JavaScript applications
JavaScript
162
star
68

bazel-tools

Tools for dealing with very large Bazel-managed repositories
Java
162
star
69

dataenum

Algebraic data types in Java.
Java
161
star
70

magnolify

A collection of Magnolia add-on modules
Scala
158
star
71

async-google-pubsub-client

[SUNSET] Async Google Pubsub Client
Java
157
star
72

gcp-audit

A tool for auditing security properties of GCP projects.
Python
156
star
73

spark-bigquery

Google BigQuery support for Spark, SQL, and DataFrames
Scala
155
star
74

should-up

Remove most of the "should" noise from your tests
JavaScript
150
star
75

folsom

An asynchronous memcache client for Java
Java
146
star
76

flo

A lightweight workflow definition library
Java
146
star
77

missinglink

Build time tool for detecting link problems in java projects
Java
142
star
78

android-auth

Spotify authentication and authorization for Android. Part of the Spotify Android SDK.
HTML
140
star
79

proto-registry

An implementation of the Protobuf Registry API
TypeScript
140
star
80

zoltar

Common library for serving TensorFlow, XGBoost and scikit-learn models in production.
Java
138
star
81

futures-extra

Java library for working with Guava futures
Java
135
star
82

spotify-web-playback-sdk-example

React based example app that creates a new player in Spotify Connect to play music from in the browse using Spotify Web Playback SDK.
JavaScript
134
star
83

annoy-java

Approximate nearest neighbors in Java
Java
134
star
84

spydra

Ephemeral Hadoop clusters using Google Compute Platform
Java
133
star
85

docker-stress

Simple docker stress test and monitoring tools
Python
125
star
86

spotify-tensorflow

Provides Spotify-specific TensorFlow helpers
Python
124
star
87

crtauth

a public key backed client/server authentication system
Python
118
star
88

redux-location-state

Utilities for reading & writing Redux store state to & from the URL
JavaScript
118
star
89

sparkey-java

Java implementation of the Sparkey key value store
Java
117
star
90

github-java-client

A Java client to Github API
Java
114
star
91

realbook

Easier audio-based machine learning with TensorFlow.
Python
109
star
92

rspec-dns

Easily test your DNS with RSpec
Ruby
107
star
93

web-playback-sdk

This issue tracker is no longer used. Join us in the Spotify for Developers forum for support with the Spotify Web Playback SDK ➡️ https://community.spotify.com/t5/Spotify-for-Developers/bd-p/Spotify_Developer
107
star
94

ffwd-ruby

An event and metrics fast-forwarding agent.
Ruby
106
star
95

gimme

Creating time bound IAM Conditions with ease and flair
Python
103
star
96

super-smash-brogp

Sends and withdraws BGP prefixes for fun.
Python
98
star
97

lighthouse-audit-service

TypeScript
94
star
98

noether

Scala Aggregators used for ML Model metrics monitoring
Scala
91
star
99

python-graphwalker

Python re-implementation of the graphwalker testing tool
Python
91
star
100

spotify.github.io

Showcase site for hand-picked open-source projects by Spotify
HTML
88
star