GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - fm-sys/spotify-web-api-java: A Java wrapper for Spotify's Web API.

BranchesTags
Open more actions menu
 
 

Latest commit

 

History

1,562 Commits
1,562 Commits

Folders and files

NameName
Last commit message
Last commit date
.github
.github
 
 
apidocs
apidocs
 
 
ci
ci
 
 
examples
examples
 
 
src
src
 
 
.editorconfig
.editorconfig
 
 
.gitignore
.gitignore
 
 
.renovaterc
.renovaterc
 
 
CODE_OF_CONDUCT.md
CODE_OF_CONDUCT.md
 
 
CONTRIBUTING.md
CONTRIBUTING.md
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
pom.xml
pom.xml
 
 

Repository files navigation

You and me
Spotify has a history of pushing considerable breaking changes to their API and documentation without prior notice. Additionally, Spotify is known for not responding to developers' inquiries.
This can suddenly render development on top of their platform useless, reportedly putting university projects and job applications at risk. Be encouraged to share your feedback with Spotify on a platform of your choice.
[1] [2]
Android Developers
You cannot use this library for Android app development. Have a look at adamint/spotify-web-api-kotlin, kaaes/spotify-web-api-android and Spotify's Android SDK and see why.

Spotify Web API Java

CI codecov

This is a Java wrapper/client for the Spotify Web API.

Table of Contents

  1. Installation
    1. Jitpack
  2. Documentation
  3. General Usage
    1. Authorization
  4. Examples
  5. Contributions
    1. Code Overview

Installation

The artifact is available through Maven Central via Sonatype. Or to use a snapshot of the latest commit you can use jitpack.io as described further down below.

Maven

Latest official release:

<dependency>
  <groupId>se.michaelthelin.spotify</groupId>
  <artifactId>spotify-web-api-java</artifactId>
  <version>9.1.1</version>
</dependency>

Latest snapshot:

<dependency>
  <groupId>com.github.thelinmichael</groupId>
  <artifactId>spotify-web-api-java</artifactId>
  <version>master-SNAPSHOT</version>
</dependency>

Gradle

Latest official release:

implementation 'se.michaelthelin.spotify:spotify-web-api-java:9.1.1'

Latest snapshot:

implementation 'com.github.thelinmichael:spotify-web-api-java:master-SNAPSHOT'

Jitpack

In order to use Jitpack you need to add their repository to your pom.xml:

Maven

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

Gradle

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

Documentation

See this project's Javadoc.

A huge thanks to c-schuhmann for his amazing work on the documentation!

General Usage

// For all requests an access token is needed
SpotifyApi spotifyApi = new SpotifyApi.Builder()
        .setAccessToken("taHZ2SdB-bPA3FsK3D7ZN5npZS47cMy-IEySVEGttOhXmqaVAIo0ESvTCLjLBifhHOHOIuhFUKPW1WMDP7w6dj3MAZdWT8CLI2MkZaXbYLTeoDvXesf2eeiLYPBGdx8tIwQJKgV8XdnzH_DONk")
        .build();

// Create a request object with the optional parameter "market"
final GetSomethingRequest getSomethingRequest = spotifyApi.getSomething("qKRpDADUKrFeKhFHDMdfcu")
        .market(CountryCode.SE)
        .build();

void getSomething_Sync() {
  try {
    // Execute the request synchronous
    final Something something = getSomethingRequest.execute();

    // Print something's name
    System.out.println("Name: " + something.getName());
  } catch (Exception e) {
    System.out.println("Something went wrong!\n" + e.getMessage());
  }
}

void getSomething_Async() {
  try {
    // Execute the request asynchronous
    final Future<Something> somethingFuture = getSomethingRequest.executeAsync();

    // Do other things...

    // Wait for the request to complete
    final Something something = somethingFuture.get();

    // Print something's name
    System.out.println("Name: " + something.getName());
  } catch (Exception e) {
    System.out.println("Something went wrong!\n" + e.getMessage());
  }
}

Authorization

Please see Spotify's Authorization Guide too!

For authorization requests the API object requires at least to have your application's client ID and client secret set as its properties. When using the authorization code flow, the application's redirect URI is required too. Those properties will then be automatically used by functions that depend on them.

SpotifyApi spotifyApi = new SpotifyApi.Builder()
  .setClientId("<your_client_id>")
  .setClientSecret("<your_client_secret>")
  .setRedirectUri("<your_redirect_uri>")
  .build();

There are three ways to retrieving an access token:

Client Credentials Flow

Use the client credentials flow when the requests don't require permission from a specific user. This flow doesn't return a refresh token and is useful for simple requests, like fetching albums or searching for tracks.

Example: ClientCredentialsExample.java

Authorization Code Flow

Using the authorization code flow to retrieve an access token is necessary if the requests are bound to a specific user. Using this flow returns a refresh token, which can be used to renew the access token before it expires. This is how it works:

  1. The authorization code flow requires a code, which is part of the redirectUri's query parameters when the user has opened a custom URL in a browser and authorized the application.

    Example: AuthorizationCodeUriExample.java

  2. When the code has been retrieved, it can be used in another request to get an access token as well as a refresh token.

    Example: AuthorizationCodeExample.java

  3. Now, the refresh token in turn can be used in a loop to retrieve new access and refresh tokens.

    Example: AuthorizationCodeRefreshExample.java


When you've fetched an access and refresh token, you have to add them to your API properties for automatic usage in requests. The implementer has to handle the access token's expiration.

spotifyApi
  .setAccessToken("<your_access_token>")
  .setRefreshToken("<your_refresh_token>")
  .build();

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

The authorization code flow with PKCE is quite like the Authorization Code Flow except that no client secret is necessary (therefore, it is a good option for mobile and desktop applications). Instead, your application should generate a code verifier and a code challenge before each authentication request.

The code verifier is a cryptographically random string between 43 and 128 characters in length. It can contain letters, digits, underscores, periods, hyphens, or tildes. To generate the code challenge, your app should hash the code verifier using the SHA256 algorithm. Then, base64url encode the hash that you generated.

This flow provides your app with an access token which can be refreshed, too. The steps are similar as above:

  1. The authorization code flow with PKCE requires a code, which is part of the redirectUri's query parameters when the user has opened a custom URL in a browser and authorized the application. The code challenge is supplied to this request as a query parameter.

    Example: AuthorizationCodePKCEUriExample.java

  2. When the code has been retrieved, it can be used in another request to get an access token as well as a refresh token. The code verifier is supplied to this request a query parameter.

    Example: AuthorizationCodePKCEExample.java

  3. Now, the refresh token in turn can be used in a loop to retrieve new access and refresh tokens.

    Example: AuthorizationCodePKCERefreshExample.java


When you have fetched an access and refresh token, you have to add them to your API properties for automatic usage in requests. The implementer must handle the access token's expiration. The refresh token can be exchanged for an access token only once, after which it becomes invalid.

Examples

  • Albums

    • Get an Album
    • Get an Album's Tracks
    • Get several Albums
  • Artists

    • Get an Artist
    • Get an Artist's Albums
    • Get an Artist's Top Tracks
    • Get an Artist's Related Artists
    • Get Several Artists
  • Browse

    • Miscellaneous
      • Get Available Genre Seeds
    • Get a Category
    • Get a Category's Playlists
    • Get a List of Categories
    • Get a List of Featured Playlists
    • Get a List of New Releases
    • Get Recommendations
  • Episodes

    • Get an Episode
    • Get several Episodes
  • Follow

    • Check if Current User Follows Artists or Users
    • Check if Users Follow a Playlist
    • Follow Artists or Users
    • Follow a Playlist
    • Get User's Followed Artists
    • Unfollow Artists or Users
    • Unfollow a Playlist
  • Library

    • Check User's Saved Albums
    • Check User's Saved Episodes
    • Check User's Saved Shows
    • Check User's Saved Tracks
    • Get Current User's Saved Albums
    • Get User's Saved Episodes
    • Get User's Saved Shows
    • Get User's Saved Tracks
    • Remove Albums for Current User
    • Remove User's Saved Episodes
    • Remove User's Saved Shows
    • Remove User's Saved Tracks
    • Save Albums for Current User
    • Save Episodes for Current User
    • Save Shows for Current User
    • Save Tracks for User
  • Personalization

    • Simplified
      • Get a User's Top Artists
      • Get a User's Top Tracks
    • Get a User's Top Artists and Tracks
  • Player

    • Add Item to User's Playback Queue
    • Get a User's Available Devices
    • Get Information About The User's Current Playback
    • Get Current User's Recently Played Tracks
    • Get the User's Currently Playing Track
    • Pause a User's Playback
    • Seek To Position In Currently Playing Track
    • Set Repeat Mode On User's Playback
    • Set Volume For User's Playback
    • Skip User's Playback To Next Track
    • Skip User's Playback To Previous Track
    • Start/Resume a User's Playback
    • Toggle Shuffle For User's Playback
    • Transfer a User's Playback
  • Playlists

    • Add Items to a Playlist
    • Change a Playlist's Details
    • Create a Playlist
    • Get a List of Current User's Playlists
    • Get a List of a User's Playlists
    • Get a Playlist
    • Get a Playlist Cover Image
    • Get a Playlist's Items
    • Remove Items from a Playlist
    • Reorder a Playlist's Items
    • Replace a Playlist's Items
    • Upload a Custom Playlist Cover Image
  • Search

    • Simplified
      • Search Albums
      • Search Artists
      • Search Episodes
      • Search Playlists
      • Search Shows
      • Search Tracks
    • Search Item
  • Shows

    • Get a Show
    • Get several Show
    • Get a Show's Episodes
  • Tracks

    • Get Audio Analysis for a Track
    • Get Audio Features for a Track
    • Get Audio Features for Several Tracks
    • Get Several Tracks
    • Get a Track
  • User's Profile

    • Get Current User's Profile
    • Get a User's Profile

Contributions

See CONTRIBUTING.md.

  • Build: mvn clean install
  • Test: mvn clean test

Requirements: Java, Maven.

Code Overview

This project's main Java package is divided into four sections:

  • enumerations
  • exceptions
  • model objects
  • requests.

Those unit-tested parts are connected through various classes that make the API accessible for other Java projects. You can find details about specific parts or single classes in the sections below.

Enumerations

src/main/java/se.michaelthelin.spotify/enums/

Enumerations allow elements to "be of a type" and limit them to a known value set. They are currently not specified in a unique place, but are rather scrambled across the online reference. Thus, the reference only allows for construction of enum classes from this sparse information.

Exceptions

src/main/java/se.michaelthelin.spotify/exceptions/

Exceptions are thrown when errors occur. They are following RFC-specified HTTP status codes and are packed with a more detailed error description.

Model Objects

src/main/java/se.michaelthelin.spotify/model_objects/

The model objects are entities that form the API's responses in arranged formats. They are mostly specified in the Web API Object Model and in the Web API Authorization Guide. Though, unreferenced model objects exist. This project subdivides those into...

  • "miscellaneous" model objects: these are mentioned somewhere in the reference, but not in the model object list
  • "special" model objects: these are not mentioned at all, but appear in API answers nonetheless.

Java classes representing those model objects include private instance variables, a private constructor, but public getter methods as well as an embedded...

  1. builder class, including the setter functions and a public build method
  2. JSON-util class, implementing the createModelObject method.

Requests

src/main/java/se.michaelthelin.spotify/requests/

The request classes mirror the structure of Spotify's Web Api endpoints. They are divided into several categories like authorization, data/albums or data/tracks. They must extend from AbstractDataRequest and contain an implementation of the request's execute method. They have to embed a builder class too, enabling dynamic request creation.

Tests

src/test/java/se.michaelthelin.spotify/

Unit tests ensure that implemented features work. This project's unit tests are implemented with JUnit and mockito for mocking.

Fixtures

src/test/fixtures/

Fixtures are JSON files that represent the data returned from the API server. We use the examples directly provided by the Web API Endpoint Reference with minor tweaks. Tweaks are needed because the reference sometimes contains invalid data examples.

About

A Java wrapper for Spotify's Web API.

Resources

Readme
License

Code of conduct

Code of conduct

Contributing

Contributing
Activity

Stars

0 stars

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.