Giter VIP home page Giter VIP logo

spotify-web-api-wrapper's Introduction

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

  • 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

spotify-web-api-wrapper's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar jzheng2017 avatar lgtm-migrator avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

spotify-web-api-wrapper's Issues

Add documentation for the public API

Currently there are only few example usages in the README.md that explains how to use the library.

It would be great if there was documentation explaining each function that is provided by the library.

Documentation should contain:

  • Function syntax (return value, parameters, etc)
  • Function description
  • Function example usage (code example)

Add async http calls to Spotify Web API

Currently SpotifyApi makes synchronous HTTP calls to the Spotify Web API. This may not be desirable as it blocks the application until the request is returned.

A great enhancement would be to implement asynchronous HTTP calls of the existing synchronous http calls.

new issue

Hey, I am Vinayak Kanjiker I would like to contribute in this app can you please assign me a task .
This is for my open source contribution class.
please contact me at [email protected]

Add automatic access token refreshment when expired

Is your feature request related to a problem? Please describe.
Currently when the access token expires the API can no longer make any request to the Spotify Web API. There is no system in place that detects whether the access token has expired and refreshes the token when necessary.

The feature request is to implement a system that will refresh the access token automatically when expired using the already existing AuthorizationRefreshToken.

Describe the solution you'd like
The system should be able to detect when the token has expired. When it has detected that the token has expired it will make a request to Spotify Authorization API for a new access token. When the new access token has been obtained it should update all services that use that token to make requests.

Describe alternatives you've considered
None at the moment.

Additional context
This feature should be implemented in SpotifyApi, or somewhere else if it is more fitting but should be well substantiated why it is done that way.

Limit class exposure to end users

Currently the library exposes a lot of internal details, a lot of classes are public. This may not be desirable as end users of the library shouldn't know of the implementation details.

A great enhancement would be to limit the exposure of implementation classes.

Only the following classes should be exposed:

  • SpotifyApi
  • AuthorizationCodeFlow
  • AuthorizationCodeFlowPKCE
  • AuthorizationPKCERequestToken
  • AuthorizationRefreshToken
  • AuthorizationRequestToken
  • ClientCredentialsFlow
  • All of the domain model objects

Make Spotify interfaces return actual paging objects

Is your feature request related to a problem? Please describe.
Currently some api calls of the SpotifyApi interface return an object wrapping a Paging<T> object. This is done because of how the Spotify Web API return their json.

For instance PlaylistSimplifiedPaging is just wrapping around Paging<PlaylistSimplified>. The end user would have to make an additional getter call to get the actual contents of the paging object. This is unnecessary because it is an internal detail of how the json is mapped.

The following functions need to be changed:

If there are anymore I've missed, please comment it on this issue.

Describe the solution you'd like
It would be better if the wrapped object contents got returned instead of the wrapper object itself.

So instead of returning the wrapped object, for instance PlaylistSimplifiedPaging, it would be better to returned the actual Paging object.

Describe alternatives you've considered
None

Additional context
The feature is actually already done once in FollowApiRetrofit class for the function getFollowedArtists. Take this function as reference when implementing the feature.

Add JavaDoc to classes

The library currently lacks a lot of JavaDoc. Almost all classes are without JavaDoc with the authorization classes as an exception.

It would be great if JavaDoc were to be added for the following classes:

  • All classes in the spotify.api.interfaces package
  • All private functions in the spotify.api.impl package (Overridden functions in implementation classes already inherit JavaDoc from their interface)
  • All classes in the spotify.retrofit.services package
  • All classes in the spotify.api.enums package
  • All classes in the spotify.factories package
  • All classes in the spotify.utils package
  • All classes in the spotify.models package (only a brief description of the model at the top of the class)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.