Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
com.adamratzman:spotify-api-kotlin-metadata
Advanced tools
A Kotlin wrapper for the Spotify Web API.
This is the Kotlin implementation of the Spotify Web API
repositories {
jcenter()
}
implementation("com.adamratzman:spotify-api-kotlin-core:3.4.03")
Note that images and profiles are not supported on the Kotlin/JS target.
If you declare any release types not named debug or release, you may see "Could not resolve com.adamratzman:spotify-api-kotlin-android:VERSION". You need to do the following for each release type not named debug or release:
android {
buildTypes {
yourReleaseType1 {
// ...
matchingFallbacks = ['release', 'debug']
}
yourReleaseType2 {
// ...
matchingFallbacks = ['release', 'debug']
}
...
}
}
To successfully build, you might need to exclude kotlin_module files from the packaging. To do this, inside the android/buildTypes/release closure, you would put:
packagingOptions {
exclude 'META-INF/*.kotlin_module'
}
The spotify-web-api-kotlin
JavaDocs are hosted here.
If you have a question, you can:
To decide which api you need (SpotifyAppApi, SpotifyClientApi, SpotifyImplicitGrantApi), you can refer to the sections below or the Spotify authorization guide. In general:
This provides access only to public Spotify endpoints. Use this when you have a server-side application. Note that implicit grant authorization provides a higher api ratelimit, so consider using implicit grant if your application has significant usage.
By default, the SpotifyApi Token
automatically regenerates when needed.
This can be changed by overriding the automaticRefresh
builder setting.
There are four exposed builders, depending on the level of control you need over api creation. Please see the spotifyAppApi builder docs for a full list of available builders.
You will need:
Example creation (default settings)
val api = spotifyAppApi("clientId", "clientSecret").build() // create and build api
println(api.browse.getNewReleases()) // use it
Example creation, using an existing Token and setting automatic token refresh to false
val token = spotifyAppApi(spotifyClientId, spotifyClientSecret).build().token
val api = spotifyAppApi(
"clientId",
"clientSecret",
token,
SpotifyApiOptionsBuilder(
automaticRefresh = false
)
)
println(api.browse.getNewReleases()) // use it
The SpotifyClientApi
is a superset of SpotifyApi
; thus, nothing changes if you want to
access public data.
This library does not provide a method to retrieve the code from your callback url; instead,
you must implement that with a web server.
Automatic refresh is available only when building with an authorization code or a
Token
object. Otherwise, it will expire Token.expiresIn
seconds after creation.
Make sure your application has requested the proper Scopes in order to
ensure proper function of this library. The api option requiredScopes
allows you to verify
that a client has actually authorized with the scopes you are expecting.
You will need:
Use the PKCE builders and helper methods if you are using the Spotify client authorization PKCE flow.
Building via PKCE returns a SpotifyClientApi
which has modified refresh logic.
Use cases:
To learn more about the PKCE flow, please read the Spotify authorization guide. Some highlights about the flow are:
This library contains helpful methods that can be used to simplify the PKCE authorization process.
This includes getSpotifyPkceCodeChallenge
(not available in the Kotlin/JS target), which SHA256 hashes and base64url encodes the code
challenge, and getPkceAuthorizationUrl
, which allows you to generate an easy authorization url for PKCE flow.
Please see the spotifyClientPkceApi builder docs for a full list of available builders.
Takeaway: Use PKCE authorization flow in applications where you cannot secure the client secret.
To get a PKCE authorization url, to which you can redirect a user, you can use the getPkceAuthorizationUrl
top-level method. An example is shown below, requesting 4 different scopes.
val codeVerifier = "thisisaveryrandomalphanumericcodeverifierandisgreaterthan43characters"
val codeChallenge = getSpotifyPkceCodeChallenge(codeVerifier) // helper method
val url: String = getPkceAuthorizationUrl(
SpotifyScope.PLAYLIST_READ_PRIVATE,
SpotifyScope.PLAYLIST_MODIFY_PRIVATE,
SpotifyScope.USER_FOLLOW_READ,
SpotifyScope.USER_LIBRARY_MODIFY,
clientId = "clientId",
redirectUri = "your-redirect-uri",
codeChallenge = codeChallenge
)
There is also an optional parameter state
, which helps you verify the authorization.
Note: If you want automatic token refresh, you need to pass in your application client id and redirect uri
when using the spotifyClientPkceApi
.
SpotifyClientApi
.val codeVerifier = "thisisaveryrandomalphanumericcodeverifierandisgreaterthan43characters"
val code: String = ...
val api = spotifyClientPkceApi(
"clientId", // optional. include for token refresh
"your-redirect-uri", // optional. include for token refresh
code,
codeVerifier, // the same code verifier you used to generate the code challenge
SpotifyApiOptionsBuilder(
retryWhenRateLimited = false
)
).build()
println(api.library.getSavedTracks().take(10).filterNotNull().map { it.track.name })
To get a non-PKCE authorization url, to which you can redirect a user, you can use the getSpotifyAuthorizationUrl
top-level method. An example is shown below, requesting 4 different scopes.
val url: String = getSpotifyAuthorizationUrl(
SpotifyScope.PLAYLIST_READ_PRIVATE,
SpotifyScope.PLAYLIST_MODIFY_PRIVATE,
SpotifyScope.USER_FOLLOW_READ,
SpotifyScope.USER_LIBRARY_MODIFY,
clientId = "clientId",
redirectUri = "your-redirect-uri",
state = "your-special-state" // optional
)
There are also several optional parameters, allowing you to set whether the authorization url is meant for implicit grant flow, the state, and whether a re-authorization dialog should be shown to users.
There are several exposed builders, depending on the level of control you need over api creation. Please see the spotifyClientApi builder docs for a full list of available builders.
In this example, automatic token refresh is turned on by default.
val authCode = ""
val api = spotifyClientApi(
"clientId",
"clientSecret",
"your-redirect-uri",
authCode
).build() // create and build api
println(api.personalization.getTopTracks(limit = 5).items.map { it.name }) // print user top tracks
In this case, if you provide a client id to the builder, automatic token refresh will also be turned on.
val token: Token = ... // your existing token
val api = spotifyClientApi(
"clientId",
"clientSecret",
"your-redirect-uri",
token,
SpotifyApiOptionsBuilder(
onTokenRefresh = {
println("Token refreshed at ${System.currentTimeMillis()}")
}
)
).build()
println(api.personalization.getTopTracks(limit = 5).items.map { it.name })
Use the SpotifyImplicitGrantApi
if you are using the Spotify implicit grant flow.
SpotifyImplicitGrantApi
is a superset of SpotifyClientApi
.
Unlike the other builders, the spotifyImplicitGrantApi
builder method directly returns
a SpotifyImplicitGrantApi
instead of an api builder.
Use cases:
To learn more about the implicit grant flow, please read the Spotify authorization guide. Some highlights about the flow are:
Please see the spotifyImplicitGrantApi builder docs for a full list of available builders.
The Kotlin/JS target contains the parseSpotifyCallbackHashToToken
method, which will parse the hash
for the current url into a Token object, with which you can then instantiate the api.
Takeaway: There are two ways to use implicit grant flow, browser-side only and browser and server. This library provides easy access for both.
val token: Token = ...
val api = spotifyImplicitGrantApi(
null,
null,
token
) // create api. there is no need to build it
println(api.personalization.getTopArtists(limit = 1)[0].name) // use it
There are three pluggable blocks in each api's corresponding builder
credentials
lets you set the client id, client secret, and redirect uriauthorization
lets you set the type of api authorization you are using.
Acceptable types include: an authorization code, a Token
object, a Token's access code string, and an optional refresh token stringoptions
lets you configure API options to your own specific needsThis library does not attempt to be prescriptivist.
All API options are located in SpotifyApiOptions
and their default values can be overridden; however, use caution in doing so, as
most of the default values either allow for significant performance or feature enhancements to the API instance.
useCache
: Set whether to cache requests. Default: truecacheLimit
: The maximum amount of cached requests allowed at one time. Null means no limit. Default: 200automaticRefresh
: Enable or disable automatic refresh of the Spotify access token when it expires. Default: trueretryWhenRateLimited
: Set whether to block the current thread and wait until the API can retry the request. Default: trueenableLogger
: Set whether to enable to the exception logger. Default: truetestTokenValidity
: After API creation, test whether the token is valid by performing a lightweight request. Default: falsedefaultLimit
: The default amount of objects to retrieve in one request. Default: 50json
: The Json serializer/deserializer instance.allowBulkRequests
: Allow splitting too-large requests into smaller, allowable api requests. Default: truerequestTimeoutMillis
: The maximum time, in milliseconds, before terminating an http request. Default: 100000msrefreshTokenProducer
: Provide if you want to use your own logic when refreshing a Spotify token.requiredScopes
: Scopes that your application requires to function (only applicable to SpotifyClientApi
and SpotifyImplicitGrantApi
).
This verifies that the token your user authorized with actually contains the scopes your
application needs to function.Notes:
useCache
should be truecacheLimit
is per Endpoint, not per API. Don't be surprised if you end up with over 200 items in your cache with the default settings.automaticRefresh
is disabled when client secret is not provided, or if tokenString is provided in SpotifyClientApiallowBulkRequests
for example, lets you query 80 artists in one wrapper call by splitting it into 50 artists + 30 artistsrefreshTokenProducer
is useful when you want to re-authorize with the Spotify Auth SDK or elsewhereAPIs available in all SpotifyApi
instances, including SpotifyClientApi
and SpotifyImplicitGrantApi
:
SearchApi
(searching items)AlbumApi
(get information about albums)BrowseApi
(browse new releases, featured playlists, categories, and recommendations)ArtistApi
(get information about artists)PlaylistApi
(get information about playlists)UserApi
(get public information about users on Spotify)TrackApi
(get information about tracks)FollowingApi
(check whether users follow playlists)APIs available only in SpotifyClientApi
and SpotifyImplicitGrantApi
instances:
ClientSearchApi
(all the methods in SearchApi
, and searching shows and episodes)EpisodeApi
(get information about episodes)ShowApi
(get information about shows)ClientPlaylistApi
(all the methods in PlaylistApi
, and get and manage user playlists)ClientProfileApi
(all the methods in UserApi
, and get the user profile, depending on scopes)ClientFollowingApi
(all the methods in FollowingApi
, and get and manage following of playlists, artists, and users)ClientPersonalizationApi
(get user top tracks and artists)ClientLibraryApi
(get and manage saved tracks and albums)ClientPlayerApi
(view and control Spotify playback)The easiest way to build the API is using .build() after a builder
runBlocking {
val api = spotifyAppApi(clientId, clientSecret).build()
}
Spotify provides these three object models in order to simplify our lives as developers. So let's see what we can do with them!
PagingObjects are a container for the requested objects (items
), but also include
important information useful in future calls. It contains the request's limit
and offset
, along with
(sometimes) a link to the next and last page of items and the total number of items returned.
If a link to the next or previous page is provided, we can use the getNext
and getPrevious
methods to retrieve
the respective PagingObjects
A cursor-based paging object is a PagingObject with a cursor added on that can be used as a key to find the next
page of items. The value in the cursor, after
, describes after what object to begin the query.
Just like with PagingObjects, you can get the next page of items with getNext
. However, there is no
provided implementation of after
in this library. You will need to do it yourself, if necessary.
Some endpoints, like PlaylistAPI.getPlaylistTracks
, return a LinkedResult, which is a simple wrapper around the
list of objects. With this, we have access to its Spotify API url (with href
), and we provide simple methods to parse
that url.
For obvious reasons, in most cases, making asynchronous requests via queue
or queueAfter
is preferred. However,
the synchronous format is also shown.
val api = spotifyAppApi(
System.getenv("SPOTIFY_CLIENT_ID"),
System.getenv("SPOTIFY_CLIENT_SECRET")
).build()
// print out the names of the twenty most similar songs to the search
println(api.search.searchTrack("Début de la Suite").joinToString { it.name })
// simple, right? what about if we want to print out the featured playlists message from the "Overview" tab?
println(api.browse.getFeaturedPlaylists().message)
// easy! let's try something a little harder
// let's find out Bénabar's Spotify ID, find his top tracks, and print them out
val benabarId = api.search.searchArtist("Bénabar")[0].id
// this works; a redundant way would be: api.artists.getArtist("spotify:artist:6xoAWsIOZxJVPpo7Qvqaqv").id
println(api.artists.getArtistTopTracks(benabarId).joinToString { it.name })
Spotify keeps many instances of most tracks on their servers, available in different markets. As such, if we use endpoints that return tracks, we do not know if these tracks are playable in our market. That's where track relinking comes in.
To relink in a specified market, we must supply a market
parameter for endpoints where available.
In both Track and SimpleTrack objects in an endpoint response, there is a nullable field called linked_from
.
If the track is unable to be played in the specified market and there is an alternative that is playable, this
will be populated with the href, uri, and, most importantly, the id of the track.
You can then use this track in SpotifyClientApi
endpoints such as playing or saving the track, knowing that it will be playable
in your market!
See CONTRIBUTING.md
FAQs
Unknown package
We found that com.adamratzman:spotify-api-kotlin-metadata demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
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.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.