Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

nl.jiankai:spotify-web-api-wrapper

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nl.jiankai:spotify-web-api-wrapper

A Java Wrapper for Spotify's Web API

  • 1.5.7
  • Source
  • Maven
  • Socket score

Version published
Maintainers
1
Source

Maven Central Build Status Coverage Status Language grade: Java Maintainability GitHub commit activity

Spotify Web API Wrapper

Spotify API wrapper for Java

Table of Contents

Guides

Use the following guides provided by Spotify to use this library:

Support

If you need any help or have any questions there is a Discord channel.

Example usages

Client Credentials Flow

The Client Credentials flow is used in server-to-server authentication. Only endpoints that do not access user information can be accessed.

ClientCredentialsFlow clientCredentialsFlow = new ClientCredentialsFlow();
String accessToken = clientCredentialsFlow.getClientCredentialToken(
        "CLIENT ID",
        "CLIENT SECRET")
        .getAccessToken();

SpotifyApi spotifyApi = new SpotifyApi(accessToken);

AlbumFull albumFull = spotifyApi.getAlbum("ALBUM ID");

Authorization Code Flow

This flow is suitable for long-running applications in which the user grants permission only once. It provides an access token that can be refreshed. Since the token exchange involves sending your secret key, perform this on a secure location, like a backend service, and not from a client such as a browser or from a mobile app.

The first step to get an access and refresh token through the Authorization Code Flow is to build an url.

AuthorizationCodeFlow authorizationCodeFlow = new AuthorizationCodeFlow.Builder()
        .setClientId("CLIENT ID")
        .setRedirectUri("https://www.example.com/callback/")
        .setResponseType("code")
        .setScopes(Arrays.asList(
                 AuthorizationScope.APP_REMOTE_CONTROL,
                 AuthorizationScope.PLAYLIST_MODIFY_PRIVATE))
         .build();

The above code will result in the following url.

https://accounts.spotify.com/authorize?client_id=CLIENT ID&response_type=code&redirect_uri=https://www.example.com/callback/&scope=app-remote-control playlist-modify-private&state=null&show_dialog=false

By visiting the url it will display a prompt to authorize access within the given scopes. Authorizing access will redirect the user to the given redirect uri. An authorization code will also be returned, it can be found as a query parameter in the redirect uri. Use this authorization code for the second step.

For the second step the following values need to be provided:

  • Client ID
  • Client Secret
  • Authorization Code (the code that got returned when redirected from spotify)
  • Redirect Uri (the redirect uri that was given in the first step)
AuthorizationRequestToken authorizationRequestToken = new AuthorizationRequestToken();
AuthorizationCodeFlowTokenResponse token = authorizationRequestToken
                .getAuthorizationCodeToken(
                        "CLIENT ID",
                        "CLIENT SECRET",
                        "AUTHORIZATION CODE",
                        "REDIRECT URI");

Authorization Code Flow with Proof Key for Code Exchange (PKCE)

The authorization code flow with PKCE is the best option for mobile and desktop applications where it is unsafe to store your client secret. It provides your app with an access token that can be refreshed. For further information about this flow, see IETF RFC-7636.

The first step to get an access and refresh token through the Authorization PKCE Code Flow is to build an url.

AuthorizationCodeFlowPKCE pkce = new AuthorizationCodeFlowPKCE.Builder()
     .setClientId("CLIENT ID")
     .setRedirectUri("REDIRECT URI")
     .setResponseType("code")
     .setScopes(Arrays.asList(
              AuthorizationScope.APP_REMOTE_CONTROL,
              AuthorizationScope.PLAYLIST_MODIFY_PRIVATE))
     .setCodeChallengeMethod("S256")
     .setCodeChallenge("CODE CHALLENGE")
     .setState("STATE")
     .build();

The above code will result in the following url.

https://accounts.spotify.com/authorize?client_id=CLIENT ID&response_type=code&redirect_uri=REDIRECT URI&scope=app-remote-control playlist-modify-private&state=STATE&code_challenge_method=S256&code_challenge=CODE CHALLENGE

By visiting the url it will display a prompt to authorize access within the given scopes. Authorizing access will redirect the user to the given redirect uri. An authorization code will also be returned, it can be found as a query parameter in the redirect uri. Use this authorization code for the second step.

For the second step the following values need to be provided:

  • Client ID
  • Authorization Code (the code that got returned when redirected from spotify)
  • Redirect Uri (the redirect uri that was given in the first step)
  • Code verifier (the one that was generated at the first step)
AuthorizationPKCERequestToken auth = new AuthorizationPKCERequestToken();
final String accessToken = auth.getAuthorizationCodeToken(
        "CLIENT ID",
        "CODE",
        "REDIRECT URI",
        "CODE VERIFIER")
        .getAccessToken();

Using access token

The AuthorizationCodeFlowTokenResponse contains the access and refresh token. The access and refresh token can be used to access api endpoints.

SpotifyApi spotifyApi = new SpotifyApi("ACCESS TOKEN", "REFRESH TOKEN");
AlbumFull albumFull = spotifyApi.getAlbum("ALBUM ID");

Refreshing access token

When the access token has expired it can be refreshed using AuthorizationRefreshToken

AuthorizationCodeFlowTokenResponse token = authorizationRefreshToken
                .refreshAccessToken(
                        "CLIENT ID",
                        "CLIENT SECRET",
                        "REFRESH TOKEN");

The above code example will return an AuthorizationCodeFlowTokenResponse which contains the new access and refresh token.

Optional parameters

Many API endpoints have optional parameters. Passing in optional parameters is done with a Map. If you don't want to pass any optional parameters then just pass in an empty Map.

SpotifyApi spotifyApi = new SpotifyApi("ACCESS TOKEN");

Map<String, String> optionalParameters = new HashMap<>();
optionalParameters.put("limit", "10");

CategoryFullPaging categories = spotifyApi.getCategories(optionalParameters);

Error Handling

As of this moment the library can throw three different exceptions.

HttpRequestFailedException

This exception will be thrown when the HTTP request has failed on the server side of Spotify. This can for instance happen when the Spotify server is not reachable at the moment.

SpotifyActionFailedException

This exception will be thrown when the HTTP request has been successfully handled, but the desired results has not been returned. This can for instance happen when one of the provided parameters are invalid.

SpotifyAuthorizationFailedException

This exception will be thrown when authorization has failed. This may be thrown when for instance the provided credentials are not valid.

Why use this library?

Because this library is very simple and straightforward with a clear and simple interface. You only need to provide a few credential info and you're ready to access the endpoints. All other stuff is already taken care for you. When looking at other similar existing libraries, they have really complicated constructs to access an endpoint, where with this library it can be done with 1 line of code.

Installation

Maven

Latest official release:

<dependency>
  <groupId>nl.jiankai</groupId>
    <artifactId>spotify-web-api-wrapper</artifactId>
    <version>1.5.7</version>
</dependency>

Gradle

Latest official release:

implementation 'nl.jiankai:spotify-web-api-wrapper:1.5.7'

Contributing

Do you want to contribute to this library? Well, you're in the right place! We'd love your help. Please refer to our contribution guideline.

License

See the LICENSE file for the license rights and limitations (GNU GPLv3).

Spotify endpoint coverage

This is the most recent coverage in the repository. The marked endpoints may not be available yet in the most recent official release.

  • Albums
    • Get an Album
    • Get Several Albums
    • Get an Album's Tracks
  • Artists
    • Get an Artist's Albums
    • Get an Artist's Related Artists
    • Get an Artist's Top Tracks
    • Get an Artist
    • Get Several Artists
  • Browse
    • Get Available Genre Seeds
    • Get a List of Browse Categories
    • Get a Single Browse Category
    • Get a Category's playlists
    • Get a List of Featured Playlists
    • Get a List of New Releases
    • Get Recommendations Based on Seeds
  • Episodes
    • Get an Episode
    • Get Several Episodes
  • Follow
    • Unfollow Artists or Users
    • Unfollow a Playlist
    • Check if Current User Follows Artists or Users
    • Get Followed Artists
    • Check if Users Follow a Playlist
    • Follow Artists or Users
    • Follow a Playlist
  • Library
    • Remove Albums for Current User
    • Remove User's Saved Shows
    • Remove Tracks for Current User
    • Check Current User's Saved Albums
    • Check User's Saved Shows
    • Check Current User's Saved Tracks
    • Get Current User's Saved Albums
    • Get User's Saved Shows
    • Get Current User's Saved Tracks
    • Save Albums for Current User
    • Save Shows for Current User
    • Save Tracks for Current User
  • Personalization
    • Get User's Top Artists and Tracks
  • Player
    • Get the Current User's Recently Played Tracks
    • Get Information About The User's Current Playback
    • Get a User's Available Devices
    • Get the User's Currently Playing Track
    • Skip User's Playback To Next Track
    • Skip User's Playback To Previous Track
    • Add an item to the end of the user's current playback queue.
    • Pause a User's Playback
    • Start/Resume a User's Playback
    • Set Repeat Mode On User's Playback
    • Seek To Position In Currently Playing Track
    • Toggle Shuffle For User's Playback
    • Transfer a User's Playback
    • Set Volume For User's Playback
  • Playlists
    • Remove Items from a Playlist
    • Get a List of Current User's Playlists
    • Get a Playlist Cover Image
    • Get a Playlist's Items
    • Get a Playlist
    • Get a List of a User's Playlists
    • Add Items to a Playlist
    • Create a Playlist
    • Upload a Custom Playlist Cover Image
    • Reorder a Playlist's Items
    • Replace a Playlist's Items
    • Change a Playlist's Details
  • Search
    • Search for an item
  • Tracks
    • Get a Track
    • Get Several Tracks
    • Get Audio Analysis for a Track
    • Get Audio Features for a Track
    • Get Audio Features for Several Tracks
  • Shows
    • Get Several Shows
    • Get a Show's Episodes
    • Get a Show
  • Users Profile
    • Get Current User's Profile
    • Get a User's Profile

FAQs

Package last updated on 01 Jan 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc