jzheng2017 / spotify-web-api-wrapper

Spotify API wrapper for Java
MIT License
50 stars 33 forks source link
api-library api-wrapper beginner-friendly java java-library library open-source open-source-project spotify spotify-api spotify-api-wrapper spotify-library spotify-web-api spotify-web-api-java spotify-web-api-library spotify-web-api-wrapper spotify-wrapper web-api-wrapper

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:

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:

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 (MIT).

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.