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 🙏

© 2024 – Pkg Stats / Ryan Hefner

spotify-web-api-client

v1.0.5

Published

Universal client for the Spotify web API.

Downloads

15

Readme

spotify-web-api-client

Universal client for the Spotify web API.

❗️❗️ DISCLAIMER: This was written to solve a particular need I had. It might not end up getting actively maintained!

This client aims to be flexible enough to be either as minimal or full-fledged as you need. Each endpoint can be called with a simple function, and you're not tied into any http library under the hood. Consumers of the library can use the default Fetch-based http client (or 'fetcher') and polyfill as needed. Alternatively, you create your own based on based on your library of choice.

Middleware gives you the possibility to perform some actions before each request is made to the Spotify API, such as logging. This is also the primary way that authentication is added to each request. Create an auth middleware via the supplied helpers and pass this to createClient, and the necessary headers will be added automatically to each request.

Having 'fetchers' passed in from the outside allows for a whole lot of flexibility. Alongside not being tied to any particular library, it makes it easy to add custom timeout logic, request retries. And, if you don't want to go via middleware, you can always do authentication in a custom fetcher and modifier headers yourself.

Contents

Installation

With yarn

yarn add spotify-web-api-client

With npm

npm i spotify-web-api-client

Creating a client

Create a client using the createClient function. This should subsequently be passed to all endpoint functions in order to execute requests to the Spotify API.

The client is nothing special. It's just a function that takes a RequestConfig object as an argument and passes that through the middleware chain and returns the response.

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';

const client = createClient(fetcher);

This above example doesn't do very much yet - it'll make a network request, but that's about it. We can add some middleware in order to start making authenticated requests to Spotify.

Adding middleware

Middleware lets you perform actions just before and just after each request to the Spotify API. This is a useful place to do things like logging, error reporting, applying timeouts, etc. It's also the out-of-the-box way to add authentication to your requests. Read more about auth middleware

If this looks familiar at all, it's because I totally ripped the API from Redux.

function loggerMiddleware(next: MiddlewareFetcher) {
  return (request: RequestConfig) => {
    console.log(`Making request to Spotify: ${JSON.stringify(request)}`);
    return next(request);
  };
}

const client = createClient(fetcher, loggerMiddleware);

A middleware function takes the next middleware as its argument and returns a function that takes a request. This function must then return the result of calling next(request). The function returned from your middleware can also be asynchronous.

Chaining middleware

composeMiddleware takes any number of middleware functions and composes them together using reduceRight under the hood.

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import {
  createAuthMiddleware,
  composeMiddleware
} from 'spotify-web-api-client/middleware';

const authMiddleware = createAuthMiddleware({
  token: () => getTokenFromSomewhere(),
  client_id: '<CLIENT_ID>',
  client_secret: '<CLIENT_SECRET>'
});

function addLogging(next: MiddlewareFetcher) {
  return (request: RequestConfig) => {
    console.log(`Making request to Spotify: ${JSON.stringify(request)}`);
    return next(request);
  };
}

function addCrashReporting(next: MiddlewareFetcher) {
  return (request: RequestConfig) => {
    try {
      return next(request);
    } catch (error) {
      console.log(`Error! ${error.message}`);
      Sentry.captureException(error, {
        extra: {
          url: request.url
        }
      });
      throw error;
    }
  };
}

// Middleware functions are composed right-to-left
const middleware = composeMiddleware(
  authMiddleware,
  loggerMiddleware,
  crashMiddleware
);

const client = createClient(fetcher, middleware);

Auth middleware

Middleware is the default way of adding authentication to your requests, and the library comes with a few helpers to do this: createAuthMiddleware, createBasicAuthMiddleware and createBearerAuthMiddleware.

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import {
  createAuthMiddleware,
  createBasicAuthMiddleware,
  createBearerAuthMiddleware
} from 'spotify-web-api-client/middleware';

const addAuth = createAuthMiddleware({
  token: 'TOKEN',
  client_id: '<CLIENT_ID>',
  client_secret: '<CLIENT_SECRET>'
});
// This client will add the correct headers for any request.
const client = createClient(fetcher, addAuth);

const addBasicAuth = createBasicAuthMiddleware({
  token: 'TOKEN',
  client_id: '<CLIENT_ID>',
  client_secret: '<CLIENT_SECRET>'
});
// This client will be able to handle any endpoint that requires
// `Basic` auth headers, e.g. authentication endpoints.
const basicClient = createClient(fetcher, addBasicAuth);

const addBearerAuth = createBearerAuthMiddleware({
  token: 'TOKEN'
});
// This client will be able to handle any endpoint that requires
// `Bearer` auth headers, e.g. everything that's not authentication.
const addBearerAuth = createClient(fetcher, addBearerAuth);

Authenticating

Read the Spotify docs on authentication flows.

❗️❗️ Important: Never expose your client secret on the frontend! Check which flow is most applicable for your needs.

Authorization code flow

  1. Direct the user to Spotify to authorize your application.
import { createAuthorizationCodeUrl } from 'spotify-web-api-client/auth';
import { app } from './app';

// Imagine app is some Express application you have running.
app.get('/login', (_, res) => {
  const authUrl = createAuthorizationCodeUrl({
    client_id: '<CLIENT_ID>',
    redirect_uri: '<REDIRECT_URI>',
    state: '<STATE>',
    scope: ['user-read-playback-state', 'user-modify-playback-state']
  });

  return res.redirect(authURL);
});
  1. Grab the authorization code from the URL when the user is redirected back to your redirect_uri and request refresh and access tokens.
import { app } from './app';
import { createClient } from 'spotify-web-api-client';
import { createBasicAuthMiddleware } from 'spotify-web-api-client/middleware';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { authorizationCode } from 'spotify-web-api-client/auth';

const addBasicAuth = createBasicAuthMiddleware({
  client_id: '<CLIENT_ID>',
  client_secret: '<CLIENT_SECRET>'
});

const client = createClient(fetcher, addBasicAuth);

// Imagine app is some Express application you have running.
app.get('/callback', (req, res, next) => {
  const { code, error, state } = req.query;

  // You should do something here if there was an error
  // or the states don't match!

  try {
    const { body } = await authorizationCode(client, {
      code,
      redirect_uri: '<REDIRECT_URI>'
    });

    const { access_token, expires_in, refresh_token } = body;

    // Do something with the tokens here...

    return res.send('Authenticated!');
  } catch (error) {
    next(error);
  }
});
  1. Add authentication to your requests to the Spotify API
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { play } from 'spotify-web-api-client/player';

const addBearerAuth = createBearerAuthMiddleware({
  token: '<TOKEN>'
});

const client = createClient(fetcher, addBearerAuth);

async function playSpotify() {
  await play(client);
}

playSpotify();

Authorization code flow with PKCE

Read the Spotify docs for this flow

🗒 Note: The Spotify docs contain more info on generating a code verifier and code challenge. It's worth checking this out!

  1. Direct the user to Spotify to authorize your application.
import { createAuthorizationCodeWithPkceUrl } from 'spotify-web-api-client/auth';
import { app } from './app';

// Imagine app is some Express application you have running.
app.get('/login', (_, res) => {
  const authUrl = createAuthorizationCodeWithPkceUrl({
    client_id: '<CLIENT_ID>',
    redirect_uri: '<REDIRECT_URI>',
    state: '<STATE',
    scope: ['user-read-playback-state', 'user-modify-playback-state'],
    code_challenge: '<CODE_CHALLENGE>'
  });

  return res.redirect(authUrl);
});
  1. Grab the authorization code from the URL when the user is redirected back to your redirect_uri and request refresh and access tokens.
import { app } from './app';
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { authorizationCodeFlow } from 'spotify-web-api-client/auth';

// Note: No auth middleware is technically required for
// the PKCE flow, but a new client would need to be created
// once you've retrieved the tokens.
const client = createClient(fetcher);

// Imagine app is some Express application you have running.
app.get('/callback', async (req, res, next) => {
  const { code, error, state } = req.query;

  // You should do something here if there was an error
  // or the states don't match!

  try {
    const { body } = await authorizationCodeWithPkce(client, {
      code,
      client_id: '<CLIENT_ID>',
      redirect_uri: '<REDIRECT_URI>',
      code_verifier: '<CODE_VERIFIER>'
    });

    const { access_token, expires_in, refresh_token } = body;

    saveTokensSomewhere({ access_token, expires_in, refresh_token });

    return res.send('Authenticated!');
  } catch (error) {
    next(error);
  }
});
  1. Add authentication to your requests to the Spotify API
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { play } from 'spotify-web-api-client/player';

const addAuth = createBearerAuthMiddleware({
  token: '<TOKEN>'
});

const client = createClient(fetcher, addAuth);

async () => {
  await play(client);
};

Implicit grant flow

Read the Spotify docs for this flow.

  1. Direct the user to Spotify to authorize your application.
import { createImplicitGrantUrl } from 'spotify-web-api-client/auth';

function login() {
  const authUrl = createImplicitGrantUrl({
    client_id: '<CLIENT_ID>',
    redirect_uri: 'REDIRECT_URI',
    state: 'STATE',
    scope: ['user-read-playback-state', 'user-modify-playback-state']
  });
  window.location.href = authURL;
}

login();
  1. Grab the access token from the hash fragment of the URL (encoded as query string) when the user is redirected back to your redirect_uri.
function getAccessTokenFromURL() {
  const url = new URL(window.location);
  const error = url.searchParams.get('error');

  if (error) {
    throw new Error(`Authentication error: ${error}`);
  }

  // Strip the '#' from the start of the hash fragment
  const params = new URLSearchParams(window.location.hash.substring(1));

  const access_token = params.get('access_token');
  const token_type = params.get('token_type');
  const expires_in = params.get('expires_in');
  const state = params.get('state');

  // Be sure to compare state here as well!

  return access_token;
}
  1. Add authentication to your requests to the Spotify API
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { play } from 'spotify-web-api-client/player';

const addAuth = createBearerAuthMiddleware({
  token: '<TOKEN>'
});

const client = createClient(fetcher, addAuth);

async () => {
  await play(client);
};

Client credentials flow

Read the Spotify docs for this flow.

  1. Request an access token from the Spotify accounts service
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBasicAuthMiddleware } from 'spotify-web-api-client/middleware';

const addAuth = createBasicAuthMiddleware({
  client_id: '<CLIENT_ID>',
  client_secret: '<CLIENT_SECRET>'
});

const client = createClient(fetcher, addAuth);

async function authenticate() {
  try {
    const { body } = await clientCredentials(client);

    const { access_token, expires_in } = body;

    saveTokenSomewhere({ access_token, expires_in });
  } catch (error) {
    console.log(error.message);
  }
}

authenticate();
  1. Add authentication to your requests to the Spotify API
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { play } from 'spotify-web-api-client/player';

const addAuth = createBearerAuthMiddleware({
  token: () => getTokenSavedEarlier()
});

const client = createClient(fetcher, addAuth);

async () => {
  await play(client);
};

Creating a custom fetcher

A default Fetch-based fetcher can be imported from spotify-web-api-client/fetcher, but it's pretty simple to create your own if you prefer to use another HTTP library.

The role of a fetcher is to take the RequestConfig object, execute the request to Spotify and return a promise that resolves with a Response object.

The RequestConfig and Response objects have the following interfaces:

interface RequestConfig {
  url: string;
  method: HttpMethod;
  headers?: Record<string, any>;
  params?: Record<string, any>;
  body?: any;
  scheme?: AuthenticationScheme;
  signal?: AbortSignal;
}

interface Response<T = any> {
  body: T;
  status: number;
  headers: any;
  request: RequestConfig;
}

You can do anything you like in the fetcher, as long as you return a promise that resolves with a response matching the Response interface. You could handle adding authentication headers and bypass middleware altogether if you wanted.

So, a barebones custom fetcher could look something like:

async function fetcher(request: RequestConfig) {
  const { url, method, body, headers, params, scheme } = request;

  if (scheme === 'Bearer') {
    headers['Authorization'] = 'Bearer <MY_ACCESS_TOKEN>';
  }

  try {
    const response = await myHttpFunction(url, { body, headers, params });
    return {
      body: response.body,
      status: response.status,
      headers: response.headers,
      request
    };
  } catch (error) {
    // Do anything you like with the error object here before rethrowing...
    throw error;
  }
}

Error handling

TODO!

Examples

TODO!

API Reference

createClient

Creates a client that can be used to execute requests to the Spotify API.

createClient(fetcher: Fetcher, middleware?: Middleware): Fetcher

  • fetcher Fetcher - Async function that takes a RequestConfig object, executes the request and returns a Response object.
  • middleware Middleware - Middleware function/s to be executed with each request.

Once created, the client can be passed as the first argument to any endpoint function.

🗒 Note: This library deliberately does not polyfill fetch. If you want to use the default fetcher in a Node env, for example, then you will need to polyfill this yourself.

import { createClient, Fetcher, RequestConfig } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import {
  createAuthMiddleware,
  composeMiddleware
} from 'spotify-web-api-client/middleware';
import { getAlbum } from 'spotify-web-api-client/albums';

const addAuth = createAuthMiddleware({
  token: '<TOKEN>',
  client_id: '<CLIENT_ID>',
  redirect_uri: '<REDIRECT_URI>'
});

function addLogging(next: Fetcher) {
  return (request: RequestConfig) => {
    console.log(`Making request to ${request.url}`);
    return next(request);
  };
}

const client = createClient(fetcher, composeMiddleware(addAuth, addLogging));

getAlbum(client, { id: '0sNOF9WDwhWunNAHPD3Baj' }).then(({ body: album }) =>
  console.log(album.name)
);

composeMiddleware

Composes multiple middleware functions together to be passed as the second argument to createClient.

composeMiddleware(...fns: Middleware[]): Middleware

  • ...fns Middleware[] - Any number of middleware functions.

Middleware functions are composed right-to-left.

import { createClient, Fetcher, RequestConfig } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import {
  createAuthMiddleware,
  composeMiddleware
} from 'spotify-web-api-client/middleware';

const addAuth = createAuthMiddleware({
  token: '<TOKEN>',
  client_id: '<CLIENT_ID>',
  redirect_uri: '<REDIRECT_URI>'
});

function addLogging(next: Fetcher) {
  return (request: RequestConfig) => {
    console.log(`Making request to ${request.url}`);
    return next(request);
  };
}

const middleware = composeMiddleware(addAuth, addLogging)

const client = createClient(fetcher, middleware;

createAuthMiddleware

Composes createBasicAuthMiddleware and createBearerAuthMiddleware together into a single middleware function.

createAuthMiddleware(config: AuthMiddlewareConfig): Middleware

  • config
    • token string | Function - Spotify access token or a function that returns an access token as a string (can be async).
    • client_id string - Spotify client ID.
    • client_secret string - Spotify client secret.
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createAuthMiddleware } from 'spotify-web-api-client/middleware';

const addAuth = createAuthMiddleware({
  /**
   * This could also be an async or sync function that returns
   * a string:
   * token: () => fetchAccessTokenFromSomewhere(),
   */
  token: '<TOKEN>',
  client_id: '<CLIENT_ID>',
  redirect_uri: '<REDIRECT_URI>'
});

const client = createClient(fetcher, addAuth);

createBasicAuthMiddleware

Create a middleware function that will add a Basic authorization header to the correct requests.

createBasicAuthMiddleware(config: BasicAuthMiddlewareConfig): Middleware

  • config
    • client_id string - Spotify client ID.
    • client_secret string - Spotify client secret.
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBasicAuthMiddleware } from 'spotify-web-api-client/middleware';

const addBasicAuth = createBasicAuthMiddleware({
  client_id: '<CLIENT_ID>',
  redirect_uri: '<REDIRECT_URI>'
});

const client = createClient(fetcher, addBasicAuth);

createBearerAuthMiddleware

Create a middleware function that will add a Bearer authorization header to the correct requests.

createBasicAuthMiddleware(config: BearerAuthMiddlewareConfig): Middleware

  • config
    • token string | Function - Spotify access token or a function that returns an access token as a string (can be async).
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';

const addBearerAuth = createBearerAuthMiddleware({
  token: '<TOKEN>'
  /**
   * This could also be an async or sync function that returns
   * a string:
  token: () => fetchAccessTokenFromSomewhere()
  */
});

const client = createClient(fetcher, addBearerAuth);

paginate

Some Spotify API endpoints support pagination. paginate can be used with these endpoints to continuously fetch each new page of results until you've collected all items.

paginate<T>(fn: T, options?: PaginateOptions): (...args: Parameters<T>) => AsyncGenerator

  • fn Function - Spotify endpoint function.
  • options?
    • backoff? number - Duration in ms to wait between each request. Defaults to 0.
    • maxItems? number - The maximum number of items to fetch. Defaults to Infinity.
    • maxRequests? number - The maximum number of requests to be made. This will take precedence over maxItems if both values are supplied. Defaults to Infinity.

🗒 Notes on using paginate:

Unlike normal requests that return a Response object, only the response body for the given endpoint function will be returned on each iteration. If you pass a function for an endpoint that does not support pagination, the request will be executed as normal and the underlying generator function will just return the response body.

Spotify endpoints that support pagination allow you to pass an optional limit parameter to specify the number of items to return in the request. In paginate the value you pass here will be used for each request (Spotify's own default for the given endpoint will be applied if you don't provide a value). If you pass a limit that is greater than maxItems, then limit will be reassigned the lower value in order to avoid overfetching.

If you pass any other optional parameters to the endpoint function - for example, some take a market field - these will also be included in each subsequent page request.

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { paginate } from 'spotify-web-api-client/pagination';
import { getSavedAlbums } from 'spotify-web-api-client/library';

const addBearerAuth = createBearerAuthMiddleware({
  token: '<TOKEN>'
});

const client = createClient(fetcher, addBearerAuth);

async function gatherSavedAlbumNames() {
  const pages = paginate(getSavedAlbums)(client);

  const albumNames: string[] = [];

  for await (const page of pages) {
    albumNames.push(...page.items.map(({ album }) => album.name));
  }

  return albumNames;
}

async function gatherSavedAlbumNamesMax3Requests() {
  const pages = paginate(getSavedAlbums, {
    // Stop pagination after the third request.
    maxRequests: 3
  })(client);

  const albumNames: string[] = [];

  for await (const page of pages) {
    albumNames.push(...page.items.map(({ album }) => album.name));
  }

  return albumNames;
}

gather

Gather all results from paginating requests into an array. This is a shorthand for the examples above using paginate.

gather<T, U>(fn: T, pick: U, options?: PaginateOptions): (...args: Parameters<T>) => Promise<ReturnType<U>>

  • fn Function - Spotify endpoint function.
  • pick Function - Function that takes a response body and should return the page elements to gather up. If you return an array, those array elements will be spread into the resulting array.
  • options?
    • backoff? number - Duration in ms to wait between each request. Defaults to 0.
    • maxItems? number - The maximum number of items to fetch. Defaults to Infinity.
    • maxRequests? number - The maximum number of requests to be made. This will take precedence over maxItems if both values are supplied. Defaults to Infinity.
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { gather } from 'spotify-web-api-client/pagination';
import { getSavedAlbums } from 'spotify-web-api-client/library';

const addBearerAuth = createBearerAuthMiddleware({
  token: '<TOKEN>'
});

const client = createClient(fetcher, addBearerAuth);

async function gatherSavedAlbumNames(): Promise<string[]> {
  const albums = await gather(getSavedAlbums, ({ items }) =>
    items.map(({ album }) => album.name)
  )(client);
  return albums;
}

albums

Endpoints for retrieving information about one or more albums from the Spotify catalog.

Read the Spotify docs for these endpoints

getAlbum

Get Spotify catalog information for a single album.

getAlbum(client: Fetcher, parameters: GetAlbumParameters): GetAlbumResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • id string - The Spotify ID for the album.
    • market? string - An ISO 3166-1 alpha-2 country code or the string 'from_token'.

Read the Spotify API docs for this endpoint. umResponse`

(async () => {
  import { createClient } from 'spotify-web-api-client';
  import { fetcher } from 'spotify-web-api-client/fetcher';
  import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
  import { getAlbum } from 'spotify-web-api-client/albums';

  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body: album } = await getAlbum(client, {
    id: '0sNOF9WDwhWunNAHPD3Baj',
    market: 'US'
  });

  console.log(`Retrieved album ${album.name}`);
})();

getAlbums

Get Spotify catalog information for multiple albums identified by their Spotify IDs.

getAlbums(client: Fetcher, parameters: GetAlbumsParameters): GetAlbumsResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • ids string[] - Array of Spotify IDs for the albums. Maximum: 20 IDs.
    • market? string - An ISO 3166-1 alpha-2 country code or the string 'from_token'.

Read the Spotify API docs for this endpoint. umsResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getAlbums } from 'spotify-web-api-client/albums';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getAlbums(client, {
    ids: [
      '0sNOF9WDwhWunNAHPD3Baj',
      '6JWc4iAiJ9FjyK0B59ABb4',
      '6UXCm6bOO4gFlDQZV5yL37'
    ],
    market: 'US'
  });

  body.albums.forEach((album) => {
    // `album` may be `null` here if the ID at the
    // corresponding position in the `ids` array
    // returned no results.
    if (album) {
      console.log(`Retrieved album ${album.name}`);
    }
  });
})();

getTracksForAlbum

Get Spotify catalog information about an album’s tracks. Optional parameters can be used to limit the number of tracks returned.

getTracksForAlbum(client: Fetcher, parameters: GetTracksForAlbumParameters): GetTracksForAlbumResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • id string - The Spotify ID for the album.
    • limit? number - The maximum number of tracks to return. Default: 20. Minimum: 1. Maximum: 50.
    • offset? number - The index of the first track to return. Default: 0 (the first object). Use with limit to get the next set of tracks.
    • market? string - An ISO 3166-1 alpha-2 country code or the string 'from_token'.

Read the Spotify API docs for this endpoint. cksForAlbumResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getTracksForAlbum } from 'spotify-web-api-client/albums';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getTracksForAlbum(client, {
    id: '0sNOF9WDwhWunNAHPD3Baj',
    market: 'US'
  });

  body.items.forEach((track) => console.log(`Retrieved track ${track.name}`));
})();

artists

Endpoints for retrieving information about one or more artists from the Spotify catalog.

getAlbumsForArtist

Get Spotify catalog information about an artist’s albums. Optional parameters can be specified in the query string to filter and sort the response.

getAlbumsForArtist(client: Fetcher, parameters: GetAlbumsForArtistParameters): GetAlbumsForArtistResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • id string - The Spotify ID for the artist.
    • include_groups? string[] - Array of keywords that will be used to filter the response. If not supplied, all album types will be returned. Valid values are: 'album', 'single', 'appears_on', 'compilation'.
    • country? string - An ISO 3166-1 alpha-2 country code or the string 'from_token'. If not given, results will be returned for all countries and you are likely to get duplicate results per album, one for each country in which the album is available.
    • limit? number - The maximum number of albums objects to return. Default: 20. Minimum: 1. Maximum: 50.
    • offset? number - The index of the first album to return. Default: 0 (the first object). Use with limit to get the next set of albums.

Read the Spotify API docs for this endpoint. umsForArtistResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getAlbumsForArtist } from 'spotify-web-api-client/artists';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getAlbumsForArtist(client, {
    id: '0OdUWJ0sBjDrqHygGUXeCF',
    country: 'US'
  });

  body.items.forEach((album) => console.log(`Retrieved album ${album.name}`));
})();

getArtist

Get Spotify catalog information for a single artist identified by their unique Spotify ID.

getArtist(client: Fetcher, parameters: GetArtistParameters): GetArtistResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • id string - The Spotify ID for the artist.

Read the Spotify API docs for this endpoint. istResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getArtist } from 'spotify-web-api-client/artists';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getArtist(client, {
    id: '0OdUWJ0sBjDrqHygGUXeCF'
  });

  console.log(`Retrieved artist ${artist.name}`);
})();

getArtists

Get Spotify catalog information for several artists based on their Spotify IDs.

getArtists(client: Fetcher, parameters: GetArtistsParameters): GetArtistsResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • ids string[] - Array of Spotify IDs for the artists. Maximum: 50 IDs.

Read the Spotify API docs for this endpoint. istsResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getArtists } from 'spotify-web-api-client/artists';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getArtists(client, {
    ids: ['0oSGxfWSnnOXhD2fKuz2Gy', '3dBVyJ7JuOMt4GE9607Qin']
  });

  body.artists.forEach((artist) => {
    // `artist` may be `null` here if the ID at the
    // corresponding position in the `ids` array
    // returned no results.
    if (artist) {
      console.log(`Retrieved artist ${artist.name}`);
    }
  });
})();

getTopTracksForArtist

Get Spotify catalog information about an artist’s top tracks by country.

getTopTracksForArtist(client: Fetcher, parameters: GetTopTracksForArtistParameters): GetTopTracksForArtistResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • id string - The Spotify ID for the artist.
    • market string - An ISO 3166-1 alpha-2 country code or the string 'from_token'.

Read the Spotify API docs for this endpoint. TracksForArtistResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getTopTracksForArtist } from 'spotify-web-api-client/artists';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getTopTracksForArtist(client, {
    id: '0OdUWJ0sBjDrqHygGUXeCF',
    country: 'from_token'
  });

  console.log('Top tracks for artist:');
  body.tracks.forEach((track) => console.log(track.name));
})();

getRelatedArtistsForArtist

Get Spotify catalog information about artists similar to a given artist. Similarity is based on analysis of the Spotify community’s listening history.

getRelatedArtistsForArtist(client: Fetcher, parameters: GetRelatedArtistsForArtistParameters): GetRelatedArtistsForArtistResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • id string - The Spotify ID for the artist.

Read the Spotify API docs for this endpoint. atedArtistsForArtistResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getRelatedArtistsForArtist } from 'spotify-web-api-client/artists';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getRelatedArtistsForArtist(client, {
    id: '0OdUWJ0sBjDrqHygGUXeCF'
  });

  console.log('Related artists:');
  body.artists.forEach((artist) => console.log(artist.name));
})();

auth

authorizationCode

Exchange a Spotify authorization code for an access token.

authorizationCode(client: Fetcher, parameters: AuthorizationCodeParameters): AuthorizationCodeResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • code string - Spotify authorization code passed as a search param to your redirect URI.
    • redirect_uri string - The redirect URI value provided when requesting the authorization code.
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBasicAuthMiddleware } from 'spotify-web-api-client/middleware';
import { authorizationCode } from 'spotify-web-api-client/auth';

(async () => {
  const addAuth = createBasicAuthMiddleware({
    client_id: '<CLIENT_ID>',
    client_secret: '<CLIENT_SECRET>'
  });

  const client = createClient(fetcher, addAuth);

  const { body } = await authorizationCode(client, {
    code: '<CODE>'
    redirect_uri: 'https://my.app.com/calback'
  });

  console.log(body.access_token);
})();

authorizationCodeWithPkce

Exchange a Spotify authorization code for an access token.

authorizationCodeWithPkce(client: Fetcher, parameters: AuthorizationCodeWithPkceParameters): AuthorizationCodeResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • code string - Spotify authorization code passed as a search param to your redirect URI.
    • redirect_uri string - The redirect URI value provided when requesting the authorization code.
    • client_id string - The client ID for your application.
    • code_verifier string - The code verifier value generated previously in the auth flow.
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBasicAuthMiddleware } from 'spotify-web-api-client/middleware';
import { authorizationCodeWithPkce } from 'spotify-web-api-client/auth';

(async () => {
  const addAuth = createBasicAuthMiddleware({
    client_id: '<CLIENT_ID>',
    client_secret: '<CLIENT_SECRET>'
  });

  const client = createClient(fetcher, addAuth);

  const { body } = await authorizationCodeWithPkce(client, {
    client_id: '<CLIENT_ID>',
    code: '<CODE>',
    code_verifier: '<CODE_VERIFIER>',
    redirect_uri: 'https://my.app.com/calback'
  });

  console.log(body.access_token);
})();

clientCredentials

Obtain an access token using your client ID and client secret.

clientCredentials(client: Fetcher): ClientCredentialsResponse

  • client Fetcher - Client used to execute the request.
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBasicAuthMiddleware } from 'spotify-web-api-client/middleware';
import { clientCredentials } from 'spotify-web-api-client/auth';

(async () => {
  const addAuth = createBasicAuthMiddleware({
    client_id: '<CLIENT_ID>',
    client_secret: '<CLIENT_SECRET>'
  });

  const client = createClient(fetcher, addAuth);

  const { body } = await clientCredentials(client);

  console.log(body.access_token);
})();

createImplicitGrantUrl

Create the authorization URL to redirect users to as part of the implicit grant flow.

createImplicitGrantUrl(parameters: CreateImplicitGrantUrlParameters): string

  • parameters

    • client_id string - The client ID for your application.
    • redirect_uri string - The URI to redirect to after the user grants or denies permission.
    • state? string - Optional value to be used for protection against attacks such as cross-site request forgery.
    • scope? string[] - Array of Spotify scopes.
    • show_dialog? boolean - Whether or not to force the user to approve the app again if they’ve already done so.
import { createImplicitGrantUrl } from 'spotify-web-api-client/auth';

const url = createImplicitGrantUrl({
  scope: ['user-follow-modify', 'user-read-currently-playing'],
  client_id: '<CLIENT_ID>',
  redirect_uri: 'https://my.app.com/calback',
  state: '<STATE>'
});

console.log(url); // https://accounts.spotify.com/authorize?scope=user-follow-modify+user-read-currently-playing&client_id=%3CCLIENT_ID%3E&redirect_uri=https%3A%2F%2Fmy.app.com%2Fcalback&state=%3CSTATE%3E&response_type=token

createAuthorizationCodeUrl

Create the authorization URL to redirect users to as part of the authorization code flow.

createAuthorizationCodeUrl(parameters: CreateAuthorizationCodeUrlParameters): string

  • parameters
    • client_id string - The client ID for your application.
    • redirect_uri string - The URI to redirect to after the user grants or denies permission.
    • state? string - Optional value to be used for protection against attacks such as cross-site request forgery.
    • scope? string[] - Array of Spotify scopes.
    • show_dialog? boolean - Whether or not to force the user to approve the app again if they’ve already done so.
import { createAuthorizationCodeUrl } from 'spotify-web-api-client/auth';

const url = createAuthorizationCodeUrl({
  scope: ['user-follow-modify', 'user-read-currently-playing'],
  client_id: '<CLIENT_ID>',
  redirect_uri: 'https://my.app.com/calback',
  state: '<STATE>'
});

console.log(url); // https://accounts.spotify.com/authorize?scope=user-follow-modify+user-read-currently-playing&client_id=%3CCLIENT_ID%3E&redirect_uri=https%3A%2F%2Fmy.app.com%2Fcalback&state=%3CSTATE%3E&response_type=code

createAuthorizationCodeWithPkceUrl

Create the authorization URL to redirect users to as part of the authorization code with proof key for code exchange flow.

createAuthorizationCodeWithPkceUrl(parameters: CreateAuthorizationCodeWithPkceUrlParameters): string

  • parameters
    • client_id string - The client ID for your application.
    • redirect_uri string - The URI to redirect to after the user grants or denies permission.
    • code_challenge string - Your code_verifier value hashed with the SHA256 algorithm and then base64url encoded.
    • state? string - Optional value to be used for protection against attacks such as cross-site request forgery.
    • scope? string[] - Array of Spotify scopes.
import { createAuthorizationCodeWithPkceUrl } from 'spotify-web-api-client/auth';

const url = createAuthorizationCodeWithPkceUrl({
  scope: ['user-follow-modify', 'user-read-currently-playing'],
  client_id: '<CLIENT_ID>',
  redirect_uri: 'https://my.app.com/calback',
  code_challenge: 'YUxVdmtrQmNoRksyOU1Hb0VicHZDcFNYX1ZTM0pMNHJnaGlnOEtwTmtSbw=='
});

console.log(url); // https://accounts.spotify.com/authorize?scope=user-follow-modify+user-read-currently-playing&client_id=%3CCLIENT_ID%3E&redirect_uri=https%3A%2F%2Fmy.app.com%2Fcalback&code_challenge=YUxVdmtrQmNoRksyOU1Hb0VicHZDcFNYX1ZTM0pMNHJnaGlnOEtwTmtSbw%3D%3D&response_type=code&code_challenge_method=S256

refreshAccessToken

Obtain a new access token using your refresh token.

refreshAccessToken(client: Fetcher, parameters: RefreshAccessTokenParameters): RefreshAccessTokenResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • refresh_token string - Your Spotify refresh token.
import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBasicAuthMiddleware } from 'spotify-web-api-client/middleware';
import { refreshAccessToken } from 'spotify-web-api-client/auth';

(async () => {
  const addAuth = createBasicAuthMiddleware({
    client_id: '<CLIENT_ID>',
    client_secret: '<CLIENT_SECRET>'
  });

  const client = createClient(fetcher, addAuth);

  const { body } = await refreshAccessToken(client, {
    refresh_token: '<REFRESH_TOKEN>'
  });

  console.log(body.access_token);
})();

browse

getCategory

Get a single category used to tag items in Spotify.

getCategory(client: Fetcher, parameters: GetCategoryParameters): GetCategoryResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • category_id string - The Spotify category ID for the category.
    • country? string - ISO 3166-1 alpha-2 country code. Provide this parameter to ensure that the category exists for a particular country.
    • locale? string - The desired language, consisting of an ISO 639-1 language code and an ISO 3166-1 alpha-2 country code, joined by an underscore. For example: es_MX, meaning "Spanish (Mexico)". Provide this parameter if you want the category strings returned in a particular language. Note that, if locale is not supplied, or if the specified language is not available, the category strings returned will be in the Spotify default language (American English).

Read the Spotify API docs for this endpoint. egoryResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getCategory } from 'spotify-web-api-client/browse';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getCategory(client, {
    category_id: 'party',
    country: 'US'
  });

  console.log(`Found category ${body.name}`);
})();

getCategories

Get a list of categories used to tag items in Spotify.

getCategories(client: Fetcher, parameters: GetCategoriesParameters): GetCategoriesResponse

  • client Fetcher - Client used to execute the request.
  • parameters?
    • country? string - ISO 3166-1 alpha-2 country code. Provide this parameter to ensure that the category exists for a particular country.
    • locale? string - The desired language, consisting of an ISO 639-1 language code and an ISO 3166-1 alpha-2 country code, joined by an underscore. For example: es_MX, meaning "Spanish (Mexico)". Provide this parameter if you want the category strings returned in a particular language. Note that, if locale is not supplied, or if the specified language is not available, the category strings returned will be in the Spotify default language (American English).
    • limit? number - The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
    • offset? number - The index of the first item to return. Default: 0 (the first object). Use with limit to get the next set of items.

Read the Spotify API docs for this endpoint. egoriesResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getCategories } from 'spotify-web-api-client/browse';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getCategories(client, {
    country: 'DE',
    locale: 'de_DE',
    limit: 30
  });

  console.log(`Found ${body.categories.total} categories.`);
})();

getFeaturedPlaylists

Get a list of Spotify featured playlists.

getFeaturedPlaylists(client: Fetcher, parameters?: GetFeaturedPlaylistsParameters): GetFeaturedPlaylistsResponse

  • client Fetcher - Client used to execute the request.
  • parameters?
    • locale? string - The desired language, consisting of an ISO 639-1 language code and an ISO 3166-1 alpha-2 country code, joined by an underscore. For example: es_MX, meaning "Spanish (Mexico)". Provide this parameter if you want the category strings returned in a particular language. Note that, if locale is not supplied, or if the specified language is not available, the category strings returned will be in the Spotify default language (American English).
    • country? string - ISO 3166-1 alpha-2 country code. Provide this parameter to ensure that the category exists for a particular country.
    • timestamp? string - A timestamp in ISO 8601 format: yyyy-MM-ddTHH:mm:ss. Use this parameter to specify the user’s local time to get results tailored for that specific date and time in the day. If not provided, the response defaults to the current UTC time.
    • limit? number - The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
    • offset? number - The index of the first item to return. Default: 0 (the first object). Use with limit to get the next set of items.

Read the Spotify API docs for this endpoint. turedPlaylistsResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getFeaturedPlaylists } from 'spotify-web-api-client/browse';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getFeaturedPlaylists(client, {
    country: 'DE',
    locale: 'de_DE',
    timestamp: '2020-06-01T09:00:00',
    limit: 30
  });

  console.log(body.message);
})();

getNewReleases

Get a list of new album releases featured in Spotify.

getNewReleases(client: Fetcher, parameters?: GetNewReleasesParameters): GetNewReleasesResponse

  • client Fetcher - Client used to execute the request.
  • parameters?
    • country? string - ISO 3166-1 alpha-2 country code. Provide this parameter to ensure that the category exists for a particular country.
    • limit? number - The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
    • offset? number - The index of the first item to return. Default: 0 (the first object). Use with limit to get the next set of items.

Read the Spotify API docs for this endpoint. ReleasesResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getNewReleases } from 'spotify-web-api-client/browse';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getNewReleases(client, {
    country: 'US',
    limit: 30
  });

  console.log(body.message);
})();

getPlaylistsForCategory

Get a list of Spotify playlists tagged with a particular category.

getPlaylistsForCategory(client: Fetcher, parameters: GetPlaylistsForCategoryParameters): GetPlaylistsForCategoryResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • category_id string - The Spotify category ID for the category.
    • country? string - ISO 3166-1 alpha-2 country code. Provide this parameter to ensure that the category exists for a particular country.
    • limit? number - The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
    • offset? number - The index of the first item to return. Default: 0 (the first object). Use with limit to get the next set of items.

Read the Spotify API docs for this endpoint. ylistsForCategoryResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getPlaylistsForCategory } from 'spotify-web-api-client/browse';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getPlaylistsForCategory(client, {
    category_id: 'party',
    country: 'US'
  });

  console.log(`Found ${body.playlists.total} playlists.`);
})();

getRecommendations

Recommendations are generated based on the available information for a given seed entity and matched against similar artists and tracks. If there is sufficient information about the provided seeds, a list of tracks will be returned together with pool size details.

getRecommendations(client: Fetcher, parameters?: GetRecommendationsParameters): GetRecommendationsResponse

  • client Fetcher - Client used to execute the request.
  • parameters?
    • limit? number - The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
    • market? string - An ISO 3166-1 alpha-2 country code or the string 'from_token'.
    • max_*? number - A hard ceiling value for any of the available tunable track attributes. Check the Spotify documentation for available attributes.
    • min_*? number - A hard floor value for any of the available tunable track attributes. Check the Spotify documentation for available attributes.
    • seed_artists? string[] - Array of Spotify IDs for seed artists.
    • seed_genres? string[] - Array of seed genres.
    • seed_tracks? string[] - Array Spotify IDs for seed tracks.
    • target_*? number - A target value for any of the available tunable track attributes. Check the Spotify documentation for available attributes.

Read the Spotify API docs for this endpoint. ommendationsResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getRecommendations } from 'spotify-web-api-client/browse';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getRecommendations(client, {
    limit: 10,
    market: 'US',
    max_acousticness: 0.6,
    max_energy: 0.9,
    target_key: 0,
    min_liveness: 0.2,
    seed_artists: ['4NHQUGzhtTLFvgF5SZesLK'],
    seed_tracks: ['0c6xIDDpzE81m2q797ordA']
  });

  console.log(`Found ${body.tracks.length} recommendations`);
})();

getRecommendationGenres

Retrieve a list of available genres seed parameter values for recommendations.

getRecommendations(client: Fetcher): GetRecommendationGenresResponse

  • client Fetcher - Client used to execute the request.

Read the Spotify API docs for this endpoint. ommendationGenresResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getRecommendationGenres } from 'spotify-web-api-client/browse';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getRecommendationGenres(client);

  body.genres.forEach((genre) => console.log(genre));
})();

episodes

getEpisode

Endpoints for retrieving information about one or more episodes from the Spotify catalog.

getEpisode(client: Fetcher, parameters: GetEpisodeParameters): GetEpisodeResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • id string - The Spotify ID for the episode.
    • market? string - An ISO 3166-1 alpha-2 country code or the string.

Read the Spotify API docs for this endpoint. sodeResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getEpisode } from 'spotify-web-api-client/episodes';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getEpisode(client, {
    id: '512ojhOuo1ktJprKbVcKyQ',
    market: 'US'
  });

  console.log(`Found episode ${body.name}`);
})();

getEpisodes

Get Spotify catalog information for multiple episodes based on their Spotify IDs.

getEpisodes(client: Fetcher, parameters: GetEpisodesParameters): GetEpisodesResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • ids string[] - Array of the Spotify IDs for the episodes. Maximum: 50 IDs.
    • market? string - An ISO 3166-1 alpha-2 country code or the string.

Read the Spotify API docs for this endpoint. sodesResponse`

import { createClient } from 'spotify-web-api-client';
import { fetcher } from 'spotify-web-api-client/fetcher';
import { createBearerAuthMiddleware } from 'spotify-web-api-client/middleware';
import { getEpisodes } from 'spotify-web-api-client/episodes';

(async () => {
  const client = createClient(
    fetcher,
    createBearerAuthMiddleware({ token: 'NPrq7CF6QxVFo0eKO4aDdzV3G52R2EIMHt8' })
  );

  const { body } = await getEpisodes(client, {
    ids: ['77o6BIVlYM3msb4MMIL1jH', '0Q86acNRm6V9GYx55SXKwf'],
    market: 'US'
  });

  body.episodes.forEach((episode) => {
    // `episode` may be `null` here if the ID at the
    // corresponding position in the `ids` array
    // returned no results.
    if (episode) {
      console.log(`Found episode ${episode.name}`);
    }
  });
})();

follow

areFollowingPlaylist

Check to see if one or more Spotify users are following a specified playlist.

areFollowingPlaylist(client: Fetcher, parameters: AreFollowingPlaylistParameters): AreFollowingPlaylistResponse

  • client Fetcher - Client used to execute the request.
  • parameters
    • playlist_id string - The Spotify ID of the playlist.
    • ids string[] - Array of Spotify user IDs to check. Maximum 5 IDs.

Read the Spotify API docs for this endpoint. lowingPlaylistResponse sodesResponse

<