SpotifyAPI
public class SpotifyAPI<AuthorizationManager> : Codable where AuthorizationManager : SpotifyAuthorizationManager
extension SpotifyAPI: CustomStringConvertible
The central class in this library. Provides methods for all of the Spotify web API endpoints and contains an authorization manager for managing the authorization process of your application.
The methods that require authorization scopes and/or an access token that was
issued on behalf of a user are declared in conditional conformances where
AuthorizationManager
conforms to SpotifyScopeAuthorizationManager
. This
protocol requires conforming types to support authorization scopes. This
strategy provides a compile-time guarantee that you cannot call methods that
require authorization scopes if you are using an authorization manager that
doesn’t support them.
AuthorizationCodeFlowBackendManager
and
AuthorizationCodeFlowPKCEBackendManager
conform to
SpotifyScopeAuthorizationManager
. ClientCredentialsFlowBackendManager
is
not a conforming type because it does not support authorization scopes.
All of the endpoints are documented at the the web API reference.
-
Manages the authorization process for your application and contains all the authorization information.
It is this property that you should encode to data using a
JSONEncoder
in order to save it to persistent storage. This prevents the user from having to login again every time the app is quit and relaunched. See this article for more information.Assigning a new authorization manager to this property causes
authorizationManagerDidChange
to emit a signal.Declaration
Swift
public var authorizationManager: AuthorizationManager { get set }
-
A function that gets called every time this class—and only this class—needs to make a network request.
Use this function if you need to use a custom networking client. The
url
andhttpMethod
properties of theURLRequest
parameter are guaranteed to be non-nil
. No guarantees are made about which thread this function will be called on. By default,URLSession
will be used for the network requests.Warning
Do not mutate this property while a network request is being made.Declaration
Swift
public var networkAdaptor: (URLRequest) -> AnyPublisher<(data: Data, response: HTTPURLResponse), Error>
-
A publisher that emits whenever the authorization information changes.
Subscribe to this subject in order to update the persistent storage of the authorization information. See this article for more information.
Emits after any of the following events occur:
- After the access and/or refresh tokens are retrieved.
- After the access token (and possibly the refresh token) is refreshed.
- After you assign a new authorization manager to the
authorizationManager
property of this class.
This publisher subscribes to the
didChange
publisher ofauthorizationManager
and emits whenever it emits.See also
authorizationManagerDidDeauthorize
, a publisher that emits afterauthorizationManager.deauthorize()
is called.Thread Safety
No guarantees are made about which thread this publisher will emit on.
Declaration
Swift
public let authorizationManagerDidChange: PassthroughSubject<Void, Never>
-
A publisher that emits after
authorizationManager.deauthorize()
is called.authorizationManager.deauthorize()
sets the authorization information tonil
.Subscribe to this publisher in order to remove the authorization information from persistent storage when it emits.
This publisher subscribes to the
didDeauthorize
publisher ofauthorizationManager
and emits whenever it emits.See also
authorizationManagerDidChange
.Thread Safety
No guarantees are made about which thread this publisher will emit on.
Declaration
Swift
public let authorizationManagerDidDeauthorize: PassthroughSubject<Void, Never>
-
Logs general messages for this class.
Declaration
Swift
public var logger: Logger
-
Logs messages when the authorization information changes.
Logs a message when the any of the following publishers emit a signal:
authorizationManagerDidChange
authorizationManagerDidDeauthorize
authorizationManager.didChange
authorizationManager.didDeauthorize
Also logs a message in the didSet observer of
authorizationManager
.Declaration
Swift
public var authDidChangeLogger: Logger
-
Logs the URLs of the network requests made to Spotify and, if present, the body of the requests by converting the raw data to a string.
Declaration
Swift
public var apiRequestLogger: Logger
-
Creates an instance of
SpotifyAPI
, which contains all the methods for making requests to the Spotify web API.To get a client id and client secret, go to the Spotify Developer Dashboard and create an app. see the README in the root directory of this package for more information.
Declaration
Swift
public init( authorizationManager: AuthorizationManager, networkAdaptor: ( (URLRequest) -> AnyPublisher<(data: Data, response: HTTPURLResponse), Error> )? = nil )
Parameters
authorizationManager
An instance of a type that conforms to
SpotifyAuthorizationManager
. It Manages the authorization process for your application and contains all the authorization information. It is this property that you should encode to data using aJSONEncoder
in order to save it to persistent storage. See this article for more information.networkAdaptor
A function that gets called every time this class—and only this class—needs to make a network request. The
authorizationManager
will NOT use this function. Use this function if you need to use a custom networking client. Theurl
andhttpMethod
properties of theURLRequest
parameter are guaranteed to be non-nil
. No guarantees are made about which thread this function will be called on. The default isnil
, in which caseURLSession
will be used for the network requests.
-
Creates a new instance by decoding from the given decoder.
authorizationManager
is the only property that is decoded.This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.
Declaration
Swift
public required init(from decoder: Decoder) throws
Parameters
decoder
The decoder to read data from.
-
Encodes this value into the given encoder.
authorizationManager
is the only property that is encoded.If the value fails to encode anything,
encoder
will encode an empty keyed container in its place.This function throws an error if any values are invalid for the given encoder’s format.
Declaration
Swift
public func encode(to encoder: Encoder) throws
Parameters
encoder
The encoder to write data to.
-
Get an album.
See also
artistAlbums(_:groups:country:limit:offset:)
andalbums(_:market:)
(gets multiple albums).No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func album( _ album: SpotifyURIConvertible, market: String? = nil ) -> AnyPublisher<Album, Error>
Parameters
album
The URI for an album.
market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. Provide this parameter if you want to apply Track Relinking.
Return Value
The full version of an Album.
-
Get multiple albums.
See also
artistAlbums(_:groups:country:limit:offset:)
andalbum(_:market:)
(gets a single album).No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func albums( _ albums: [SpotifyURIConvertible], market: String? = nil ) -> AnyPublisher<[Album?], Error>
Parameters
albums
An array of up to 20 URIs for albums. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. Provide this parameter if you want to apply Track Relinking.
Return Value
An array of the full versions of up to 20 album objects. Albums are returned in the order requested. If an album is not found,
nil
is returned in the corresponding position. Duplicate albums in the request will result in duplicate albums in the response. -
Get the tracks for an album.
No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func albumTracks( _ album: SpotifyURIConvertible, market: String? = nil, limit: Int? = nil, offset: Int? = nil ) -> AnyPublisher<PagingObject<Track>, Error>
Parameters
album
The URI for an album.
market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. Provide this parameter if you want to apply Track Relinking.
limit
Optional. The maximum number of tracks to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first track to return. Default: 0. Use with
limit
to get the next set of tracks.Return Value
An array of simplified track objects, wrapped in a paging object.
-
Get a single artist.
No scopes are required for this endpoint.
See also
artists(_:)
(gets multiple artists).Read more at the Spotify web API reference.
Declaration
Swift
func artist( _ uri: SpotifyURIConvertible ) -> AnyPublisher<Artist, Error>
Parameters
uri
The URI for the artist.
Return Value
The full version of an artist.
-
Get multiple artists.
No scopes are required for this endpoint.
See also
artist(_:)
(gets a single artist).Read more at the Spotify web API reference.
Declaration
Swift
func artists( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<[Artist?], Error>
Parameters
uris
An array of up to 20 URIs for artists. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
Return Value
An array of the full versions of artists. Artists are returned in the order requested. If an artist is not found,
nil
is returned in the corresponding position. Duplicate artists in the request will result in duplicate artists in the response. -
Get an artist’s albums.
See also
album(_:market:)
(gets a single album) andalbums(_:market:)
(gets multiple albums).No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func artistAlbums( _ artist: SpotifyURIConvertible, groups: [AlbumType]? = nil, country: String? = nil, limit: Int? = nil, offset: Int? = nil ) -> AnyPublisher<PagingObject<Album>, Error>
Parameters
artist
The URI of an artist.
groups
Optional. The types of albums to return. Possible values are
album
,single
,appearsOn
, andcompilation
. Ifnil
, then all types will be returned.country
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. Supply this parameter to limit the response to one particular geographical market. For example, for albums available in Sweden: “SE”. If not given, results will be returned for all countries and you are likely to get duplicate results per album, one for each country in which the album is available!
limit
Optional. The number of album objects to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first album to return. Default: 0. Use with
limit
to get the next set of albums.Return Value
An array of simplified album objects wrapped in a paging object.
-
Get the top tracks for an artist.
No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func artistTopTracks( _ artist: SpotifyURIConvertible, country: String ) -> AnyPublisher<[Track], Error>
Parameters
artist
The URI of an artist.
country
Required. An ISO 3166-1 alpha-2 country code or the string “from_token”.
Return Value
The full versions of up to ten tracks.
-
Get the related artists for an artist.
No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func relatedArtists( _ artist: SpotifyURIConvertible ) -> AnyPublisher<[Artist], Error>
Parameters
artist
The URI of an artist.
Return Value
The full versions of up to 20 artists.
-
Get a Spotify Category.
Use
categories(country:locale:limit:offset:)
to get an array of categories.No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func category( _ id: String, country: String? = nil, locale: String? = nil ) -> AnyPublisher<SpotifyCategory, Error>
Parameters
id
A category id.
country
Optional. A country: an ISO 3166-1 alpha-2 country code. Provide this parameter to ensure that the category exists for a particular country.
locale
Optional. The desired language, consisting of an ISO 639-1 language code and an ISO 3166-1 alpha-2 country code, joined by an underscore. For example: es_MX, meaning “Spanish (Mexico)”. Provide this parameter if you want the category strings returned in a particular language. Note that, if this parameter is not supplied, or if the specified language is not available, the category strings returned will be in the Spotify default language (American English).
Return Value
A category object.
-
Get a list of categories used to tag items in Spotify (on, for example, the Spotify player’s “Browse” tab).
See also
category(_:country:locale:)
(gets a single category based on an id).No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func categories( country: String? = nil, locale: String? = nil, limit: Int? = nil, offset: Int? = nil ) -> AnyPublisher<PagingObject<SpotifyCategory>, Error>
Parameters
country
Optional. A country: an ISO 3166-1 alpha-2 country code. Provide this parameter if you want to narrow the list of returned categories to those relevant to a particular country. If omitted, the returned items will be globally relevant.
locale
Optional. The desired language, consisting of an ISO 639-1 language code and an ISO 3166-1 alpha-2 country code, joined by an underscore. For example: es_MX, meaning “Spanish (Mexico)”. Provide this parameter if you want the category metadata returned in a particular language. Note that, if locale is not supplied, or if the specified language is not available, all strings will be returned in the Spotify default language (American English). The locale parameter, combined with the country parameter, may give odd results if not carefully matched. For example, “SE” for
country
and “de_DE” forlocale
will return a list of categories relevant to Sweden but as German language strings.limit
Optional. The maximum number of categories to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first category to return. Default: 0. Use with limit to get the next set of categories.
Return Value
An array of category objects wrapped in a paging object.
-
Get a list of Spotify playlists tagged with a particular category.
No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func categoryPlaylists( _ id: String, country: String? = nil, limit: Int? = nil, offset: Int? = nil ) -> AnyPublisher<PagingObject<Playlist<PlaylistItemsReference>>, Error>
Parameters
id
A category id.
country
Optional. A country: an ISO 3166-1 alpha-2 country code.
limit
Optional. The maximum number of items to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first playlist to return. Default:
- Use with limit to get the next set of playlists.
Return Value
An array of simplified playlist objects wrapped in a paging object.
-
Get a list of featured playlists (shown, for example, on a Spotify player’s “Browse” tab).
No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func featuredPlaylists( locale: String? = nil, country: String? = nil, timestamp: Date? = nil, limit: Int? = nil, offset: Int? = nil ) -> AnyPublisher<FeaturedPlaylists, Error>
Parameters
locale
Optional. The desired language, consisting of an ISO 639-1 language code and an ISO 3166-1 alpha-2 country code, joined by an underscore. For example: es_MX, meaning “Spanish (Mexico)”. Provide this parameter if you want the results returned in a particular language. Note that, if locale is not supplied, or if the specified language is not available, all strings will be returned in the Spotify default language (American English). The locale parameter, combined with the country parameter, may give odd results if not carefully matched. For example, “SE” for
country
and “de_DE” forlocale
will return a list of playlists relevant to Sweden but as German language strings.country
Optional. A country: an ISO 3166-1 alpha-2 country code. Provide this parameter if you want to narrow the list of returned categories to those relevant to a particular country. If omitted, the returned items will be globally relevant.
timestamp
Optional. A date, which will be converted to a second-precision timestamp (“yyyy-MM-ddTHH:mm:ss”). Use this parameter to specify the user’s local time to get results tailored for that specific date and time in the day. If not provided, the response defaults to the current UTC time. If there were no featured playlists (or there is no data) at the specified time, the response will revert to the current UTC time.
limit
Optional. The maximum number of playlists to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first playlist to return. Default:
- Use with limit to get the next set of playlists.
Return Value
An array of simplified playlist objects wrapped in a paging object and a message that can be displayed to the user, such as “Good Morning”, or “Editors’s picks”, localized based on the locale, country, and timestamp parameters.
-
Get a list of new album releases featured in Spotify (shown, for example, on a Spotify player’s “Browse” tab).
No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func newAlbumReleases( country: String? = nil, limit: Int? = nil, offset: Int? = nil ) -> AnyPublisher<NewAlbumReleases, Error>
Parameters
country
Optional. A country: an ISO 3166-1 alpha-2 country code. Provide this parameter if you want the list of returned albums to be relevant to a particular country. If omitted, the albums will be relevant to all countries.
limit
Optional. The maximum number of albums to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first album to return. Default: 0. Use with limit to get the next set of albums.
Return Value
An array of simplified album objects wrapped in a paging object and a message that can be displayed to the user, such as “Good Morning”, or “Editors’s picks”, localized based on the locale, country, and timestamp parameters.
-
Get Recommendations Based on Seeds.
Create a playlist-style listening experience based on seed artists, tracks and genres.
Recommendations are generated based on the available information for a given seed entity and matched against similar artists and tracks. If there is sufficient information about the provided seeds, a list of tracks will be returned together with pool size details.
For artists and tracks that are very new or obscure there might not be enough data to generate a list of tracks.
Use
SpotifyAPI.recommendationGenres()
to get the available seed genres.Read more at the Spotify web API reference.
Declaration
Swift
func recommendations( _ trackAttributes: TrackAttributes, limit: Int? = nil, market: String? = nil ) -> AnyPublisher<RecommendationsResponse, Error>
Parameters
trackAttributes
limit
Optional. The target size of the list of recommended tracks. For seeds with unusually small pools or when highly restrictive filtering is applied, it may be impossible to generate the requested number of recommended tracks. Debugging information for such cases is available in the response. Default: 20; Minimum: 1; Maximum: 100.
market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. Provide this parameter if you want to apply Track Relinking. Because minimum, maximum, and target values are applied to pools before relinking, the generated results may not precisely match the filters applied. Original, non-relinked tracks are available via the
linkedFrom
attribute of the relinked track response.Return Value
Recommendation seeds and an array of tracks.
-
Retrieve a list of available genres seeds for recommendations.
No scopes are required for this endpoint.
These values can be used in the
seedGenres
property ofTrackAttributes
when using therecommendations(_:limit:market:)
endpoint.Read more at the Spotify web API reference.
Declaration
Swift
func recommendationGenres() -> AnyPublisher<[String], Error>
Return Value
An array of genres ids.
-
Get an episode.
See also
episodes(_:market:)
(gets multiple episodes).Reading the user’s resume points on episode objects requires the
userReadPlaybackPosition
scope. Otherwise, no scopes are required.Read more at the Spotify web API reference.
Declaration
Swift
func episode( _ uri: SpotifyURIConvertible, market: String? = nil ) -> AnyPublisher<Episode, Error>
Parameters
uri
The URI of an episode.
market
Optional. An ISO 3166-1 alpha-2 country code. If a country code is specified, the episode will only be returned if it is available in that market. If the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), the country associated with the user account will take priority over this parameter. Users can view the country that is associated with their account in the account settings. Note: If neither market or user country are provided, the episode is considered unavailable for the client and Spotify will return a 404 error with the message “non existing id”. Therefore, if you authorized your application using the client credentials flow, you must provide a value for this parameter.
Return Value
The full version of an
Episode
object. -
Get multiple episodes.
See also
episode(_:market:)
(gets a single episode).Reading the user’s resume points on episode objects requires the
userReadPlaybackPosition
scope. Otherwise, no scopes are required.Read more at the Spotify web API reference.
Declaration
Swift
func episodes( _ uris: [SpotifyURIConvertible], market: String? = nil ) -> AnyPublisher<[Episode?], Error>
Parameters
uris
An array of episode URIs. Maximum: 50. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
market
Optional. An ISO 3166-1 alpha-2 country code. If a country code is specified, only episodes that are available in that market will be returned. If the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), the country associated with the user account will take priority over this parameter. Users can view the country that is associated with their account in the account settings. Note: If neither market or user country are provided, the episodes are considered unavailable for the client and Spotify will return
nil
for all of the episodes. Therefore, if you authorized your application using the client credentials flow, you must provide a value for this parameter.Return Value
The full versions of up to 50 episode objects. Episodes are returned in the order requested. If an episode is not found or is unavailable in the specified market/country,
nil
is returned in the appropriate positions. Duplicate episode URIs in the request will result in duplicate episodes in the response. Unlike many of the other endpoints for retrieving multiple objects, if one of the URIs is invalid, then the entire request will fail with a 400 “invalid id” error.
-
Check to see if one or more Spotify users are following a specified playlist.
See also
currentUserFollowsArtists(_:)
andcurrentUserFollowsUsers(_:)
.Following a playlist can be done publicly or privately. Checking if a user publicly follows a playlist doesn’t require any scopes; if the user is publicly following the playlist, this endpoint returns
true
. Checking if the user is privately following a playlist is only possible for the current user when that user has granted access to theplaylistReadPrivate
scope.If the user has created the playlist themself (or you created it for them) and it shows up in their Spotify client, then that also means that they are following it. See also Following and Unfollowing a Playlist.
Read more at the Spotify web API reference.
Declaration
Swift
func usersFollowPlaylist( _ uri: SpotifyURIConvertible, userURIs: [SpotifyURIConvertible] ) -> AnyPublisher<[Bool], Error>
Parameters
uri
The URI for a playlist
userURIs
An array of up to 5 user URIs. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
Return Value
An array of
true
orfalse
values, in the order requested, indicating whether each user is following the playlist.
-
Get the list of markets where Spotify is available.
No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func availableMarkets() -> AnyPublisher<[String], Error>
Return Value
A list of the countries in which Spotify is available, identified by their ISO 3166-1 alpha-2 country code with additional country codes for special territories. For example:
["AD", "AE", "AR", ...]
.
-
Makes a request to the “/playlists/{playlistId}” endpoint and allows you to specify fields to filter the query.
See also:
filteredPlaylistItems(_:filters:additionalTypes:limit:offset:market:)
playlist(_:market:)
playlistItems(_:limit:offset:market:)
playlistTracks(_:limit:offset:market:)
playlistImage(_:)
No scopes are required for this endpoint. Both Public and Private playlists belonging to any user can be retrieved.
Use the Spotify console to test your queries, then copy and paste the response into this online JSON viewer.
You are also encouraged to assign a folder to
SpotifyDecodingError.dataDumpFolder
—or assign a value to the environment variable “SPOTIFY_DATA_DUMP_FOLDER”, which is whatdataDumpFolder
is initialized to—so that the data will be written to a folder when the decoding fails. You can then upload this file to the JSON viewer. Set thelogLevel
ofspotifyDecodeLogger
totrace
to print the raw data of all requests to the standard output.When decoding the data, use the combine operators
decodeSpotifyObject(_:)
ordecodeOptionalSpotifyObject(_:)
instead ofdecode(type:decoder:)
, otherwise the above doesn’t apply.Read more at the Spotify web API reference.
Declaration
Swift
func filteredPlaylist( _ playlist: SpotifyURIConvertible, filters: String, additionalTypes: [IDCategory], market: String? = nil ) -> AnyPublisher<(data: Data, response: HTTPURLResponse), Error>
Parameters
playlist
The URI of a playlist.
filters
Required. Filters for the query: a comma-separated list (no spaces) of the fields to return. If omitted, all fields are returned. For example, to get just the playlist’s description and URI: “description,uri”. A dot separator can be used to specify non-reoccurring fields, while parentheses can be used to specify reoccurring fields within objects. For example, to get just the added date and user ID of the adder: “tracks.items(added_at,added_by.id)”. Use multiple parentheses to drill down into nested objects, for example: “tracks.items(track(name,href,album(name,href)))”. Fields can be excluded by prefixing them with an exclamation mark, for example: “tracks.items(track(name,href,album(!name,href)))”.
additionalTypes
Required. An array of id categories. Valid types are
track
andepisode
. If you provide[]
or[.track]
, then both tracks and episodes will be returned in theTrack
format. In this case, trying to decode episodes intoPlaylistItem
orEpisode
will always fail. Instead, both tracks and episodes must be decoded intoTrack
. If you expect the the playlist to have both tracks and episodes, then use[.episode]
or[.track, .episode]
and decode the tracks and episodes intoPlaylistItem
.market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. For tracks, Provide this parameter if you want to apply Track Relinking. For episodes, if the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), the country associated with the user account will take priority over this parameter. Users can view the country that is associated with their account in the account settings. Note: If neither market or user country are provided, the episodes are considered unavailable for the client and
nil
will will be returned at the corresponding positions for each episode. Therefore, if you authorized your application using the client credentials flow and you want to retrieve the episodes in a playlist, you must provide a value for this parameter.Return Value
The raw data and URL response from the server. Because the response is entirely dependent on the filters you specify, you are responsible for decoding the data. Use the combine operators
decodeSpotifyObject(_:)
ordecodeOptionalSpotifyObject(_:)
instead ofdecode(type:decoder:)
. -
Gets a playlist, including its tracks/episodes and additional information about it.
See also:
playlistItems(_:limit:offset:market:)
playlistTracks(_:limit:offset:market:)
filteredPlaylist(_:fields:additionalTypes:market:)
filteredPlaylistItems(_:filters:additionalTypes:limit:offset:market:)
playlistImage(_:)
In contrast to the above methods, additional data about the playlist itself will be retrieved, including its name and any images associated with it.
No scopes are required for this endpoint. Both Public and Private playlists belonging to any user can be retrieved.
Returns:
Playlist<PagingObject<PlaylistItemContainer<PlaylistItem>>>
The full version of the playlist will be returned.
To access just the tracks/episodes, use:
let playlistItems: [PlaylistItem] = playlist.items.items.compactMap(\.item)
Read more at the Spotify web API reference.
Declaration
Swift
func playlist( _ playlist: SpotifyURIConvertible, market: String? = nil ) -> AnyPublisher<Playlist<PlaylistItems>, Error>
Parameters
playlist
The URI of a playlist.
market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. For tracks, Provide this parameter if you want to apply Track Relinking. For episodes, if the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), the country associated with the user account will take priority over this parameter. Users can view the country that is associated with their account in the account settings. Note: If neither market or user country are provided, the episodes are considered unavailable for the client and
nil
will will be returned at the corresponding positions for each episode. Therefore, if you authorized your application using the client credentials flow and you want to retrieve the episodes in a playlist, you must provide a value for this parameter. -
Makes a request to the “/playlists/{playlistId}/tracks” endpoint and allows you to specify fields to filter the query.
Unlike,
filteredPlaylist(_:filters:additionalTypes:market:)
, this endpoint allows you to request different pages of results.See also:
filteredPlaylist(_:filters:additionalTypes:market:)
playlist(_:market:)
playlistItems(_:limit:offset:market:)
playlistTracks(_:limit:offset:market:)
playlistImage(_:)
No scopes are required for this endpoint. Both Public and Private playlists belonging to any user can be retrieved.
You are also encouraged to assign a folder to
SpotifyDecodingError.dataDumpFolder
—or assign a value to the environment variable “SPOTIFY_DATA_DUMP_FOLDER”, which is whatdataDumpFolder
is initialized to—so that the data will be written to a folder when the decoding fails. You can then upload this file to the JSON viewer. Set thelogLevel
ofspotifyDecodeLogger
totrace
to print the raw data of all requests to the standard output.When decoding the data, use the combine operators
decodeSpotifyObject(_:)
ordecodeOptionalSpotifyObject(_:)
instead ofdecode(type:decoder:)
, otherwise the above doesn’t apply.Read more at the Spotify web API reference.
Declaration
Swift
func filteredPlaylistItems( _ playlist: SpotifyURIConvertible, filters: String, additionalTypes: [IDCategory], limit: Int? = nil, offset: Int? = nil, market: String? = nil ) -> AnyPublisher<(data: Data, response: HTTPURLResponse), Error>
Parameters
playlist
The URI of a playlist.
filters
Required. Filters for the query: a comma-separated list (no spaces) of the fields to return. If omitted, all fields are returned. For example, to get just the playlist’s description and URI: “description,uri”. A dot separator can be used to specify non-reoccurring fields, while parentheses can be used to specify reoccurring fields within objects. For example, to get just the added date and user ID of the adder: “tracks.items(added_at,added_by.id)”. Use multiple parentheses to drill down into nested objects, for example: “tracks.items(track(name,href,album(name,href)))”. Fields can be excluded by prefixing them with an exclamation mark, for example: “tracks.items(track(name,href,album(!name,href)))”.
additionalTypes
Required. An array of id categories. Valid types are
track
andepisode
. If you provide[]
or[.track]
, then both tracks and episodes will be returned in theTrack
format. In this case, trying to decode episodes intoPlaylistItem
orEpisode
will always fail. Instead, both tracks and episodes must be decoded intoTrack
. If you expect the the playlist to have both tracks and episodes, then use[.episode]
or[.track, .episode]
and decode the tracks and episodes intoPlaylistItem
.limit
Optional. The maximum number of items to return. Default: 100; minimum: 1; maximum: 100.
offset
Optional. The index of the first item to return. Default: 0. Use with
limit
to get the next set of tracks.market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. For tracks, Provide this parameter if you want to apply Track Relinking. For episodes, if the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), the country associated with the user account will take priority over this parameter. Users can view the country that is associated with their account in the account settings. Note: If neither market or user country are provided, the episodes are considered unavailable for the client and
nil
will will be returned at the corresponding positions for each episode. Therefore, if you authorized your application using the client credentials flow and you want to retrieve the episodes in a playlist, you must provide a value for this parameter.Return Value
The raw data and URL response from the server. Because the response is entirely dependent on the filters you specify, you are responsible for decoding the data. Use the combine operators
decodeSpotifyObject(_:)
ordecodeOptionalSpotifyObject(_:)
instead ofdecode(type:decoder:)
. -
Get all of the episodes and tracks in a playlist in
Track
format.Warning
This endpoint does NOT return only the tracks in a playlist. Instead, it returns both the tracks and episodes in
Track
format. You are discouraged from using this endpoint unless you are certain that the playlist only contains tracks. If unsure, useplaylistItems(_:limit:offset:market:)
instead. Use thetype
property ofTrack
to check if it is actually a track.See also:
playlist(_:market:)
filteredPlaylist(_:fields:additionalTypes:market:)
filteredPlaylistItems(_:filters:additionalTypes:limit:offset:market:)
playlistImage(_:)
No scopes are required for this endpoint. Tracks from both Public and Private playlists belonging to any user can be retrieved.
Returns:
PagingObject<PlaylistItemContainer<Track>>
The full versions of the tracks will be returned.
To get an array of just the tracks, use:
let tracks: [Track] = playlistTracks.items.compactMap(\.item)
Read more at the Spotify web API reference.
Declaration
Swift
func playlistTracks( _ playlist: SpotifyURIConvertible, limit: Int? = nil, offset: Int? = nil, market: String? = nil ) -> AnyPublisher<PlaylistTracks, Error>
Parameters
playlist
The URI of a playlist.
limit
Optional. The maximum number of items to return. Default: 100; minimum: 1; maximum: 100.
offset
Optional. The index of the first item to return. Default: 0. Use with
limit
to get the next set of tracks.market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. For tracks, Provide this parameter if you want to apply Track Relinking. For episodes, if the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), the country associated with the user account will take priority over this parameter. Users can view the country that is associated with their account in the account settings. Note: If neither market or user country are provided, the episodes are considered unavailable for the client and
nil
will will be returned at the corresponding positions for each episode. Therefore, if you authorized your application using the client credentials flow and you want to retrieve the episodes in a playlist, you must provide a value for this parameter. -
Get all of the episodes and tracks in a playlist.
See also:
playlistTracks(_:limit:offset:market:)
playlist(_:market:)
filteredPlaylist(_:fields:additionalTypes:market:)
filteredPlaylistItems(_:filters:additionalTypes:limit:offset:market:)
playlistImage(_:)
No scopes are required for this endpoint. Tracks from both Public and Private playlists belonging to any user can be retrieved.
Returns:
PagingObject<PlaylistItemContainer<PlaylistItem>>
To get an array of just the tracks/episodes, use:
let items: [PlaylistItem] = playlistItems.items.compactMap(\.item)
Read more at the Spotify web API reference.
Declaration
Swift
func playlistItems( _ playlist: SpotifyURIConvertible, limit: Int? = nil, offset: Int? = nil, market: String? = nil ) -> AnyPublisher<PlaylistItems, Error>
Parameters
playlist
The URI of a playlist.
limit
Optional. The maximum number of items to return. Default: 100; minimum: 1; maximum: 100.
offset
Optional. The index of the first item to return. Default: 0. Use with
limit
to get the next set of tracks.market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. For tracks, Provide this parameter if you want to apply [Track Relinking][5]. For episodes, if the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), the country associated with the user account will take priority over this parameter. Users can view the country that is associated with their account in the [account settings][6]. Note: If neither market or user country are provided, the episodes are considered unavailable for the client and
nil
will will be returned at the corresponding positions for each episode. Therefore, if you authorized your application using the client credentials flow and you want to retrieve the episodes in a playlist, you must provide a value for this parameter. -
Get a list of the playlists for a user, including those that they are following.
See also
currentUserPlaylists(limit:offset:)
.No scopes are required for retrieving the public playlists of any user. Private playlists are only retrievable for the current user and requires the
playlistReadPrivate
scope to have been authorized by the user. Note that this scope alone will not return collaborative playlists, even though they are always private. Collaborative playlists are only retrievable for the current user and requires theplaylistReadCollaborative
scope to have been authorized by the user. See also Working with Playlists.Returns:
PagingObject<Playlist<PlaylistItemsReference>
The simplified versions of the playlists will be returned.
A
PlaylistItemsReference
simply contains a link to all of the tracks/episodes and the total number in the playlist. To get all of the tracks and episodes in each playlist, you can useplaylistItems(_:limit:offset:market:)
, passing in the URI of each of the playlists. To get all of the URIs, use:let uris: [String] = playlists.items.map(\.uri)
Read more at the Spotify web API reference.
Declaration
Swift
func userPlaylists( for userURI: SpotifyURIConvertible, limit: Int? = nil, offset: Int? = nil ) -> AnyPublisher<PagingObject<Playlist<PlaylistItemsReference>>, Error>
Parameters
userURI
the URI of a Spotify user.
limit
Optional. The maximum number of playlists to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first playlist to return. Default: 0; Maximum: 100,000. Use with
limit
to get the next set of playlists.
-
Get Spotify Catalog information about albums, artists, playlists, tracks, shows or episodes that match a keyword string.
No scopes are required for this endpoint—unless the
market
parameter is set to “from_token”, in which case theuserReadPrivate
scope is required.Keyword matching
Matching of search keywords is not case-sensitive. Operators, however, should be specified in uppercase. Unless surrounded by double quotation marks, keywords are matched in any order. For example:
roadhouse blues
matches both “Blues Roadhouse” and “Roadhouse of the Blues”."roadhouse blues"
(with quotes) matches “My Roadhouse Blues” but not “Roadhouse of the Blues”.Searching for playlists returns results where the query keyword(s) match any part of the playlist’s name or description. Only popular public playlists are returned.
Operator
The operator NOT can be used to exclude results.
For example:
roadhouse NOT blues
returns items that match “roadhouse” but excludes those that also contain the keyword “blues”. Similarly, the OR operator can be used to broaden the search:roadhouse OR blues
returns all the results that include either of the terms. Only one OR operator can be used in a query.Note: Operators must be specified in uppercase. Otherwise, they are handled as normal keywords to be matched.
Field filters
By default, results are returned when a match is found in any field of the target object type. Searches can be made more specific by specifying an album, artist or track field filter. To limit the results to a particular year, use the field filter year with album, artist, and track searches. For example:
query: "bob year:2014"
Or with a date range. For example:query: "bob year:1980-2020"
. To retrieve only albums released in the last two weeks, use the field filter “tag:new” in album searches.To retrieve only albums with the lowest 10% popularity, use the field filter “tag:hipster” in album searches. Note: This field filter only works with album searches. Depending on object types being searched for, other field filters, include genre (applicable to tracks and artists), upc, and isrc. Use double quotation marks around the genre keyword string if it contains spaces.
Read more at the Spotify web API reference.
Declaration
Swift
func search( query: String, categories: [IDCategory], market: String? = nil, limit: Int? = nil, offset: Int? = nil, includeExternal: String? = nil ) -> AnyPublisher<SearchResult, Error>
Parameters
query
A query, which can also include filters, as specified above. Do NOT percent encode it yourself. It will be percent-encoded automatically.
categories
Required. An array of id categories. Only results that match the specified categories will be returned. Valid types:
album
,artist
,playlist
,track
,show
,episode
.market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. If a country code is specified, only content that is playable in that market is returned. Note: Playlist results are not affected by the market parameter. If market is set to “from_token”, and the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), only content playable in the country associated with the user account, is returned. Users can view the country that is associated with their account in the account settings. Note: If neither market or user country are provided, the shows and episodes are considered unavailable for the client and Spotify will return
nil
for all of the shows and episodes. Therefore, if you authorized your application using the client credentials flow, you must provide a value for this parameter in order to retrieve shows and episodes.limit
Optional. Maximum number of results to return. Default: 20; Minimum: 1; Maximum: 50. Note: The limit is applied within each type, not on the total response. For example, if the limit value is 3 and the types are
artist
andalbum
, the response contains up to 3 artists and 3 albums.offset
Optional. The index of the first result to return. Default: 0 (the first result). Maximum offset (including limit): 2,000. Use with
limit
to get the next page of search results.includeExternal
Optional. Possible values: “audio”. if this is specified, the response will include any relevant audio content that is hosted externally. By default external content is filtered out from responses.
Return Value
A
SearchResult
. Thealbums
,artist
,playlists
,tracks
,shows
, andepisodes
properties of this struct will be non-nil
for each of the categories that were requested from thesearch
endpoint. If no results were found for a category, then theitems
property of the property’s paging object will be empty; the property itself will only benil
if the category was not requested in the search. The simplified versions of all these objects will be returned.
-
Get a show.
See also:
shows(_:market:)
- gets multiple showsshowEpisodes(_:market:offset:limit:)
- gets all of the episodes for a show
Reading the user’s resume points on episode objects requires the
userReadPlaybackPosition
scope. Otherwise, no scopes are required.Read more at the Spotify web API reference.
Declaration
Swift
func show( _ uri: SpotifyURIConvertible, market: String? = nil ) -> AnyPublisher<Show, Error>
Parameters
uri
The URI of an episode.
market
Optional. An ISO 3166-1 alpha-2 country code. If a country code is specified, the show will only be returned if it is available in that market. If the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), the country associated with the user account will take priority over this parameter. Users can view the country that is associated with their account in the account settings. Note: If neither market or user country are provided, the show is considered unavailable for the client and Spotify will return a 404 error with the message “non existing id”. Therefore, if you authorized your application using the client credentials flow, you must provide a value for this parameter.
Return Value
The full version of a show object.
-
Get multiple shows.
See also:
show(_:market:)
- gets a single showshowEpisodes(_:market:offset:limit:)
- gets all of the episodes for a show
Reading the user’s resume points on episode objects requires the
userReadPlaybackPosition
scope. Otherwise, no scopes are required.Read more at the Spotify web API reference.
Declaration
Swift
func shows( _ uris: [SpotifyURIConvertible], market: String? = nil ) -> AnyPublisher<[Show?], Error>
Parameters
uris
An array of show URIs. Maximum: 50. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
market
Optional. An ISO 3166-1 alpha-2 country code. If a country code is specified, only shows that are available in that market will be returned. If the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), the country associated with the user account will take priority over this parameter. Users can view the country that is associated with their account in the account settings. Note: If neither market or user country are provided, the shows are considered unavailable for the client and Spotify will return
nil
for all of the shows. Therefore, if you authorized your application using the client credentials flow, you must provide a value for this parameter.Return Value
The simple versions of up to 50 show objects. Shows are returned in the order requested. If a show is not found,
nil
is returned in the appropriate position. Duplicate shows URIs in the request will result in duplicate shows in the response. Unlike many of the other endpoints for retrieving multiple objects, if one of the URIs is invalid, then the entire request will fail with a 400 “invalid id” error. -
Get a show’s episodes.
See also:
shows(_:market:)
- gets multiple showsshow(_:market:)
- gets a single show
Reading the user’s resume points on episode objects requires the
userReadPlaybackPosition
scope. Otherwise, no scopes are required.Read more at the Spotify web API reference.
Declaration
Swift
func showEpisodes( _ uri: SpotifyURIConvertible, market: String? = nil, offset: Int? = nil, limit: Int? = nil ) -> AnyPublisher<PagingObject<Episode>, Error>
Parameters
uri
The URI of a show.
market
Optional. An ISO 3166-1 alpha-2 country code. If a country code is specified, only episodes that are available in that market will be returned. If the access token was granted on behalf of a user (i.e., if you authorized your application using the authorization code flow or the authorization code flow with proof key for code exchange), the country associated with the user account will take priority over this parameter. Users can view the country that is associated with their account in the account settings. Note: If neither market or user country are provided, the show and all of its episodes are considered unavailable for the client and Spotify will return a 404 error with the message “non existing id”. Therefore, if you authorized your application using the client credentials flow, you must provide a value for this parameter.
limit
Optional. The maximum number of episodes to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first episode to return. Default:
- Use with
limit
to get the next set of episodes.
Return Value
The simplified versions of episode objects wrapped in a paging object.
-
Get a Track.
See also
tracks(_:market:)
- gets multiple tracksNo scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func track( _ uri: SpotifyURIConvertible, market: String? = nil ) -> AnyPublisher<Track, Error>
Parameters
uri
The URI for a track.
market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. Provide this parameter if you want to apply Track Relinking.
Return Value
The full version of a track.
-
Get multiple Tracks.
See also
track(_:market:)
- gets a single trackNo scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func tracks( _ uris: [SpotifyURIConvertible], market: String? = nil ) -> AnyPublisher<[Track?], Error>
Parameters
uris
An array of track URIs. Maximum: 50. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. Provide this parameter if you want to apply Track Relinking.
Return Value
The full versions of up to 50
Track
objects. Tracks are returned in the order requested. If a track is not found,nil
is returned in the appropriate position. Duplicate tracks URIs in the request will result in duplicate tracks in the response. -
Get audio analysis for a track.
The Audio Analysis endpoint provides low-level audio analysis for all of the tracks in the Spotify catalog. The Audio Analysis describes the track’s structure and musical content, including rhythm, pitch, and timbre. All information is precise to the audio sample.
Many elements of analysis include confidence values, a floating-point number ranging from 0.0 to 1.0. Confidence indicates the reliability of its corresponding attribute. Elements carrying a small confidence value should be considered speculative. There may not be sufficient data in the audio to compute the attribute with high certainty.
See also:
trackAudioFeatures(_:)
- gets the audio features for a single tracktracksAudioFeatures(_:)
- gets the audio features for multiple tracks
No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func trackAudioAnalysis( _ uri: SpotifyURIConvertible ) -> AnyPublisher<AudioAnalysis, Error>
Parameters
uri
The URI for a track.
-
Get audio features for a track.
See also:
tracksAudioFeatures(_:)
- gets the audio features for multiple trackstrackAudioAnalysis(_:)
- gets audio analysis for a track
No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func trackAudioFeatures( _ uri: SpotifyURIConvertible ) -> AnyPublisher<AudioFeatures, Error>
Parameters
uri
The URI for a track.
-
Get audio features for multiple tracks.
See also:
trackAudioFeatures(_:)
- gets the audio features for a single tracktrackAudioAnalysis(_:)
- gets audio analysis for a track.
No scopes are required for this endpoint.
Read more at the Spotify web API reference.
Declaration
Swift
func tracksAudioFeatures( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<[AudioFeatures?], Error>
Parameters
uris
An array of up to 100 URIs for tracks. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
Return Value
Results are returned in the order requested. If the audio features for a track is not found,
nil
is returned in the appropriate position. Duplicate ids in the request will result in duplicate results in the response.
-
Get the public profile information for a user.
See also
currentUserProfile()
.No scopes are required for this endpoint.
The
country
,email
,product
,allowsExplicitContent
, andexplicitContentSettingIsLocked
properties ofSpotifyUser
will always benil
even if the URI of the current user is provided and the application is authorized for theuserReadPrivate
anduserReadEmail
scopes. You must usecurrentUserProfile()
to retrieve these properties.Read more at the Spotify web API reference.
Declaration
Swift
func userProfile( _ uri: SpotifyURIConvertible ) -> AnyPublisher<SpotifyUser, Error>
Parameters
uri
The URI of a Spotify user.
-
Retrieves the data linked to by an href and decodes it into
responseType
.An href is a URL provided in many of the responses from the Spotify web API which links to additional data instead of including it in the current response in order to limit the size.
Always prefer using a different method whenever possible because this method adds the additional complexity of determining the appropriate
ResponseType
.Declaration
Swift
func getFromHref<ResponseType: Decodable>( _ href: URL, responseType: ResponseType.Type ) -> AnyPublisher<ResponseType, Error>
Parameters
href
The full URL to a Spotify web API endpoint.
responseType
The expected response from the server.
Return Value
The data decoded into
responseType
. -
Retrieves additional pages of results from a
Paginated
type.This method is also available as a combine operator of the same name for all publishers where
Output
:Paginated
.Compare with
SpotifyAPI.extendPagesConcurrently(_:maxExtraPages:)
.Each time an additional page is received, its
next
property is used to retrieve the next page of results, and so on, untilnext
isnil
ormaxExtraPages
is reached. This means that the next page will not be requested until the previous one is received and that the pages will always be returned in order.Declaration
Swift
func extendPages<Page: Paginated>( _ page: Page, maxExtraPages: Int? = nil ) -> AnyPublisher<Page, Error>
Parameters
page
A
Paginated
type; that is, a type that contains a link for retrieving the next page of results.maxExtraPages
The maximum number of additional pages to retrieve. For example, to just get the next page, use
1
. Leave asnil
(default) to retrieve all pages of results.Return Value
A publisher that immediately republishes the page that was passed in, as well as additional pages that are returned by the Spotify web API.
-
Retrieves additional pages of results from a paging object concurrently.
This method is also available as a combine operator of the same name for all publishers where the output is a paging object.
Compare with
SpotifyAPI.extendPages(_:maxExtraPages:)
.This method immediately republishes the page of results that were passed in and then requests additional pages concurrently. This method has better performance than
SpotifyAPI.extendPages(_:maxExtraPages:)
, which must wait for the previous page to be received before requesting the next page. However, the order in which the pages are received is unpredictable. If you need to wait for all pages to be received before processing them, then always use this method.See Working with Paginated Results.
See also
Publisher.collectAndSortByOffset()
.Declaration
Swift
func extendPagesConcurrently<Page: PagingObjectProtocol>( _ page: Page, maxExtraPages: Int? = nil ) -> AnyPublisher<Page, Error>
Parameters
page
A paging object.
maxExtraPages
The maximum number of additional pages to retrieve. For example, to just get the next page, use
1
. Leave asnil
(default) to retrieve all pages of results.Return Value
A publisher that immediately republishes the
page
that was passed in, as well as additional pages that are returned by the Spotify web API. -
Declaration
Swift
public var description: String { get }
-
This method has no stable API and may change arbitrarily. Only use it for testing purposes.
Declaration
Swift
public func setupDebugging()
-
Get the current user’s followed artists.
See also
SpotifyAPI.currentUserFollowsArtists(_:)
.This endpoint requires the
userFollowRead
scope.Read more at the Spotify web API reference.
Declaration
Swift
func currentUserFollowedArtists( after artist: SpotifyURIConvertible? = nil, limit: Int? = nil ) -> AnyPublisher<CursorPagingObject<Artist>, Error>
Parameters
artist
Optional. the URI of the last artist from the previous request. Use this parameter to retrieve the next set of artists after this artist.
limit
Optional. The maximum number of items to return. Default: 20; Minimum: 1; Maximum: 50.
Return Value
An array of artist objects wrapped in a
CursorPagingObject
. -
Check if the current user follows the specified artists.
See also
SpotifyAPI.currentUserFollowedArtists(after:limit:)
.This endpoint requires the
userFollowRead
scope.Read more at the Spotify web API reference.
Declaration
Swift
func currentUserFollowsArtists( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<[Bool], Error>
Parameters
uris
An array of artist URIs. Maximum: 50. Passing in duplicates will result in a 502 “Failed to check following status” error. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
Return Value
An array of
true
orfalse
values, in the order requested, indicating whether the user is following each artist. -
Add the current user as a follower of one or more artists.
See also
followUsersForCurrentUser(_:)
andfollowPlaylistForCurrentUser(_:publicly:)
.This endpoint requires the
userFollowModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func followArtistsForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of artist URIs. Maximum: 50. Passing in an empty array will prevent a network request from being made.
-
Unfollow one or more artists for the current user.
See also
unfollowUsersForCurrentUser(_:)
andunfollowPlaylistForCurrentUser(_:)
.This endpoint requires the
userFollowModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func unfollowArtistsForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of artist URIs. maximum: 50. Passing in an empty array will prevent a network request from being made.
-
Check if the current user follows the specified users.
See also
currentUserFollowsArtists(_:)
andusersFollowPlaylist(_:userURIs:)
.This endpoint requires the
userFollowRead
scope.Read more at the Spotify web API reference.
Declaration
Swift
func currentUserFollowsUsers( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<[Bool], Error>
Parameters
uris
An array of user URIs. Maximum: 50. Passing in duplicates will result in a 502 “Failed to check following status” error. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
Return Value
An array of
true
orfalse
values, in the order requested, indicating whether the user is following each user. -
Add the current user as a follower of one or more users.
See also
followArtistsForCurrentUser(_:)
andfollowPlaylistForCurrentUser(_:publicly:)
.This endpoint requires the
userFollowModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func followUsersForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of user URIs. Maximum: 50. Passing in an empty array will prevent a network request from being made.
-
Unfollow one or more users for the current user.
See also
unfollowArtistsForCurrentUser(_:)
andunfollowPlaylistForCurrentUser(_:)
.This endpoint requires the
userFollowModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func unfollowUsersForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of user URIs. maximum: 50. Passing in an empty array will prevent a network request from being made.
-
Follow a playlist for the current user.
See also
followArtistsForCurrentUser(_:)
andfollowUsersForCurrentUser(_:)
.Following a playlist publicly requires authorization of the
playlistModifyPublic
scope; following it privately requires theplaylistModifyPrivate
scope.Note that the scopes you provide relate only to whether the current user is following the playlist publicly or privately (i.e. showing others what they are following), not whether the playlist itself is public or private.
See also the guide for working with playlists.
Read more at the Spotify web API reference.
Declaration
Swift
func followPlaylistForCurrentUser( _ uri: SpotifyURIConvertible, publicly: Bool = true ) -> AnyPublisher<Void, Error>
Parameters
uri
The URI for a playlist.
publicly
Optional. Defaults to
true
. Iftrue
, the playlist will be included in the user’s public playlists, iffalse
, it will remain private. To be able to follow playlists privately, the user must have granted theplaylistModifyPrivate
scope. -
Unfollow a playlist for the current user.
See also
unfollowArtistsForCurrentUser(_:)
andunfollowUsersForCurrentUser(_:)
.Spotify has no concept of deleting playlists. When a user deletes a playlist in their Spotify client, they are actually just unfollowing it. The playlist can always be retrieved again given a valid URI.
Unfollowing a publicly followed playlist for a user requires authorization of the
playlistModifyPublic
scope; unfollowing a privately followed playlist requires theplaylistModifyPrivate
scope.Note that the scopes you provide relate only to whether the current user is following the playlist publicly or privately (i.e. showing others what they are following), not whether the playlist itself is public or private.
See also the guide for working with playlists.
Read more at the Spotify web API reference.
Declaration
Swift
func unfollowPlaylistForCurrentUser( _ uri: SpotifyURIConvertible ) -> AnyPublisher<Void, Error>
Parameters
uri
The URI for a playlist.
-
Get the saved albums for the current user.
See also
currentUserSavedAlbumsContains(_:)
.This endpoint requires the
userLibraryRead
scope.To get just the albums, use:
results.items.map(\.item)
Read more at the Spotify web API reference.
Declaration
Swift
func currentUserSavedAlbums( limit: Int? = nil, offset: Int? = nil, market: String? = nil ) -> AnyPublisher<PagingObject<SavedAlbum>, Error>
Parameters
limit
Optional. The maximum number of albums to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first album to return. Default: 0. Use with
limit
to get the next set of albums.market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. Provide this parameter if you want to apply Track Relinking.
Return Value
An array of the full versions of
Album
objects wrapped in aSavedItem
object, wrapped in aPagingObject
. -
Get the saved tracks for the current user.
See also
currentUserSavedTracksContains(_:)
.This endpoint requires the
userLibraryRead
scope.To get just the tracks, use:
results.items.map(\.item)
Read more at the Spotify web API reference.
Declaration
Swift
func currentUserSavedTracks( limit: Int? = nil, offset: Int? = nil, market: String? = nil ) -> AnyPublisher<PagingObject<SavedTrack>, Error>
Parameters
limit
Optional. The maximum number of tracks to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first track to return. Default: 0. Use with
limit
to get the next set of tracks.market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. Provide this parameter if you want to apply Track Relinking.
Return Value
An array of the full versions of
Track
objects wrapped in aSavedItem
object, wrapped in aPagingObject
. -
Get the saved episodes for the current user.
This API endpoint is in beta and could change without warning.
See also
currentUserSavedEpisodesContains(_:)
.This endpoint requires the
userLibraryRead
scope.To get just the episodes, use:
results.items.map(\.item)
Read more at the Spotify web API reference.
Declaration
Swift
func currentUserSavedEpisodes( limit: Int? = nil, offset: Int? = nil, market: String? = nil ) -> AnyPublisher<PagingObject<SavedEpisode>, Error>
Parameters
limit
Optional. The maximum number of episodes to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first episode to return. Default: 0. Use with
limit
to get the next set of episodes.market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”.
Return Value
An array of the full versions of
Show
objects wrapped in aSavedItem
object, wrapped in aPagingObject
. -
Get the saved shows for the current user.
See also
currentUserSavedShowsContains(_:)
.This endpoint requires the
userLibraryRead
scope.To get just the shows, use:
results.items.map(\.item)
Read more at the Spotify web API reference.
Declaration
Swift
func currentUserSavedShows( limit: Int? = nil, offset: Int? = nil, market: String? = nil ) -> AnyPublisher<PagingObject<SavedShow>, Error>
Parameters
limit
Optional. The maximum number of shows to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first show to return. Default: 0. Use with
limit
to get the next set of shows.market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”.
Return Value
An array of the full versions of
Show
objects wrapped in aSavedItem
object, wrapped in aPagingObject
. -
Check if one or more albums is saved in the current user’s “Your Music” library.
This endpoint requires the
userLibraryRead
scope.Read more at the Spotify web API reference.
Declaration
Swift
func currentUserSavedAlbumsContains( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<[Bool], Error>
Parameters
uris
An array of album URIs. Maximum: 50. Duplicate albums in the request will result in duplicate values in the response. A single invalid URI causes the entire request to fail. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
Return Value
An array of
true
orfalse
values, in the order requested, indicating whether the user’s library contains each album. -
Check if one or more tracks is saved in the current user’s “Your Music” library.
This endpoint requires the
userLibraryRead
scope.Read more at the Spotify web API reference.
Declaration
Swift
func currentUserSavedTracksContains( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<[Bool], Error>
Parameters
uris
An array of track URIs. Maximum: 50. Duplicate tracks in the request will result in duplicate values in the response. A single invalid URI causes the entire request to fail. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
Return Value
An array of
true
orfalse
values, in the order requested, indicating whether the user’s library contains each track. -
Check if one or more episodes is saved in the current user’s “Your Music” library.
This API endpoint is in beta and could change without warning.
This endpoint requires the
userLibraryRead
scope.Read more at the Spotify web API reference.
Declaration
Swift
func currentUserSavedEpisodesContains( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<[Bool], Error>
Parameters
uris
An array of episode URIs. Maximum: 50. Duplicate episodes in the request will result in duplicate values in the response. A single invalid URI causes the entire request to fail. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
Return Value
An array of
true
orfalse
values, in the order requested, indicating whether the user’s library contains each episode. -
Check if one or more shows is saved in the current user’s “Your Music” library.
This endpoint requires the
userLibraryRead
scope.Read more at the Spotify web API reference.
Declaration
Swift
func currentUserSavedShowsContains( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<[Bool], Error>
Parameters
uris
An array of show URIs. Maximum: 50. Duplicate shows in the request will result in duplicate values in the response. A single invalid URI causes the entire request to fail. Passing in an empty array will immediately cause an empty array of results to be returned without a network request being made.
Return Value
An array of
true
orfalse
values, in the order requested, indicating whether the user’s library contains each show. -
Save albums for the current user.
This endpoint requires the
userLibraryModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func saveAlbumsForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of album URIs. Maximum: 50. Duplicates will be ignored. A single invalid URI causes the entire request to fail. Passing in an empty array will prevent a network request from being made.
-
Save tracks for the current user.
This endpoint requires the
userLibraryModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func saveTracksForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of track URIs. Maximum: 50. Duplicates will be ignored. A single invalid URI causes the entire request to fail. Passing in an empty array will prevent a network request from being made.
-
Save episodes for the current user.
This API endpoint is in beta and could change without warning.
This endpoint requires the
userLibraryModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func saveEpisodesForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of episdoe URIs. Maximum: 50. Duplicates will be ignored. A single invalid URI causes the entire request to fail. Passing in an empty array will prevent a network request from being made.
-
Save shows for the current user.
This endpoint requires the
userLibraryModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func saveShowsForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of show URIs. Maximum: 50. Duplicates will be ignored. A single invalid URI causes the entire request to fail. Passing in an empty array will prevent a network request from being made.
-
Remove saved albums for the current user.
This endpoint requires the
userLibraryModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func removeSavedAlbumsForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of album URIs. Maximum: 50. Duplicates will be ignored. A single invalid URI causes the entire request to fail. Passing in an empty array will prevent a network request from being made.
-
Remove saved tracks for the current user.
This endpoint requires the
userLibraryModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func removeSavedTracksForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of track URIs. Maximum: 50. Duplicates will be ignored. A single invalid URI causes the entire request to fail. Passing in an empty array will prevent a network request from being made.
-
Remove saved episodes for the current user.
This endpoint requires the
userLibraryModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func removeSavedEpisodesForCurrentUser( _ uris: [SpotifyURIConvertible] ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of episode URIs. Maximum: 50. Duplicates will be ignored. A single invalid URI causes the entire request to fail. Passing in an empty array will prevent a network request from being made.
-
Remove saved shows for the current user.
This endpoint requires the
userLibraryModify
scope.Read more at the Spotify web API reference.
Declaration
Swift
func removeSavedShowsForCurrentUser( _ uris: [SpotifyURIConvertible], market: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
uris
An array of show URIs. Maximum: 50. Duplicates will be ignored. A single invalid URI causes the entire request to fail. Passing in an empty array will prevent a network request from being made.
market
Optional. An ISO 3166-1 alpha-2 country code. If a country code is specified, only shows that are available in that market will be removed. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter. Note: If neither market or user country are provided, the content is considered unavailable for the client. Users can view the country that is associated with their account in the account settings.
-
Get the current user’s top artists, calculated based on affinity.
See also
currentUserTopTracks(_:offset:limit:)
.This endpoint requires the
userTopRead
scope.Affinity is a measure of the expected preference a user has for a particular artist. It is based on user behavior, including play history, but does not include actions made while in incognito mode. Light or infrequent users of Spotify may not have sufficient play history to generate a full affinity data set. As a user’s behavior is likely to shift over time, this preference data is available over three time spans. See
timeRange
in the query parameter table for more information. For each time range, the top 50 artists are available for each user. In the future, it is likely that this restriction will be relaxed. This data is typically updated once each day for each user.Read more at the Spotify web API reference.
Declaration
Swift
func currentUserTopArtists( _ timeRange: TimeRange? = nil, offset: Int? = nil, limit: Int? = nil ) -> AnyPublisher<PagingObject<Artist>, Error>
Parameters
timeRange
Optional. Over what time frame the affinities are computed. Valid values:
longTerm
(calculated from several years of data and including all new data as it becomes available),mediumTerm
(approximately last 6 months), andshortTerm
(approximately last 4 weeks). Default:mediumTerm
.offset
Optional. The index of the first artist to return. Default:
- Use with limit to get the next set of artists.
limit
Optional. The number of artists to return. Default: 20; Minimum: 1; Maximum: 50.
Return Value
An array of the full versions of artist objects wrapped in a paging object.
-
Get the current user’s top tracks, calculated based on affinity.
See also
currentUserTopArtists(_:offset:limit:)
.This endpoint requires the
userTopRead
scope.Affinity is a measure of the expected preference a user has for a particular track. It is based on user behavior, including play history, but does not include actions made while in incognito mode. Light or infrequent users of Spotify may not have sufficient play history to generate a full affinity data set. As a user’s behavior is likely to shift over time, this preference data is available over three time spans. See time_range in the query parameter table for more information. For each time range, the top 50 tracks are available for each user. In the future, it is likely that this restriction will be relaxed. This data is typically updated once each day for each user.
Read more at the Spotify web API reference.
Declaration
Swift
func currentUserTopTracks( _ timeRange: TimeRange? = nil, offset: Int? = nil, limit: Int? = nil ) -> AnyPublisher<PagingObject<Track>, Error>
Parameters
timeRange
Optional. Over what time frame the affinities are computed. Valid values:
longTerm
(calculated from several years of data and including all new data as it becomes available),mediumTerm
(approximately last 6 months), andshortTerm
(approximately last 4 weeks). Default:mediumTerm
.offset
Optional. The index of the first track to return. Default: 0. Use with limit to get the next set of tracks.
limit
Optional. The number of tracks to return. Default: 20; Minimum: 1; Maximum: 50.
Return Value
An array of the full versions of track objects wrapped in a paging object.
-
Get the user’s available devices.
Note that an available device is not the same as an active device.
This endpoint requires the
userReadPlaybackState
scope.You can use this endpoint to determine which devices are currently active by checking each device’s
isActive
property.See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func availableDevices() -> AnyPublisher<[Device], Error>
Return Value
An array of device objects.
-
Get information about the user’s current playback, including the currently playing track or episode, progress, and active device.
See also
availableDevices()
andrecentlyPlayed(_:limit:)
.This endpoint requires the
userReadPlaybackState
scope.The notable details that are returned are:
- The track or episode that is currently playing
- The context, such as a playlist, that it is playing in
- The progress into the currently playing track/episode
- The current shuffle and repeat state
The information returned is for the last known state, which means an inactive device could be returned if it was the last one to execute playback. When no available devices are found,
nil
is returned. Always useavailableDevices()
instead if you just need to get the available and active devices. Note that an available device is not the same as an active device.Read more at the Spotify web API reference.
Declaration
Swift
func currentPlayback( market: String? = nil ) -> AnyPublisher<CurrentlyPlayingContext?, Error>
Parameters
market
Optional. An ISO 3166-1 alpha-2 country code or the string “from_token”. Provide this parameter if you want to apply Track Relinking.
-
Get the current user’s recently played tracks.
See also
availableDevices()
andcurrentPlayback()
.This endpoint requires the
userReadRecentlyPlayed
scope.Currently doesn’t support podcast episodes.
Returns the most recent 50 tracks played by a user. Note that a track currently playing will not be visible in play history until it has completed. A track must be played for more than 30 seconds to be included in the play history.
Any tracks listened to while the user had “Private Session” enabled in their client will not be returned in the list of recently played tracks.
This endpoint uses a bidirectional cursor for paging. Follow the next field with the before parameter to move back in time, or use the after parameter to move forward in time. If you supply no before or after parameter, the endpoint will return the most recently played tracks, and the next link will page back in time.
Read more at the Spotify web API reference.
Declaration
Swift
func recentlyPlayed( _ timeReference: TimeReference? = nil, limit: Int? = nil ) -> AnyPublisher<CursorPagingObject<PlayHistory>, Error>
Parameters
timeReference
Optional. A reference to a period of time before or after a specified date. For example,
.before(Date())
refers to the period of time before the current date. This is used to filter the response. SeeSpotifyCursor.before
andSpotifyCursor.after
(which is part of the returnedCursorPagingObject
). Dates will be converted to millisecond-precision timestamps. Only results that are within the specified time period will be returned. Ifnil
, the most recently played tracks will be returned.limit
Optional. The maximum number of items to return. Default: 20; Minimum: 1; Maximum: 50.
Return Value
An array of simplified tracks wrapped in a
CursorPagingObject
. -
Add a track or episode to the user’s playback queue.
This endpoint requires the
userModifyPlaybackState
scope.When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func addToQueue( _ uri: SpotifyURIConvertible, deviceId: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
uri
The URI for either a track or an episode.
deviceId
The id of the device to target. See
availableDevices()
. It is highly recommended that you leave this asnil
(default) to target the active device. If you provide the id of a device that is not active, you may get a 403 “Player command failed: Restriction violated” error. If you want to add to the queue for a non-active device, calltransferPlayback(to:play:)
first. -
Skip the user’s playback to the next track/episode.
This endpoint requires the
userModifyPlaybackState
scope.When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func skipToNext( deviceId: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
deviceId
The id of the device to target. See
availableDevices()
.It is highly recommended that you leave this asnil
(default) to target the active device. If you provide the id of a device that is not active, you may get a 403 “Player command failed: Restriction violated” error. If you want to skip to the next item on a non-active device, calltransferPlayback(to:play:)
first. -
Skip the user’s playback to the previous track/episode.
This endpoint requires the
userModifyPlaybackState
scope.When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func skipToPrevious( deviceId: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
deviceId
The id of the device to target. See
availableDevices()
. It is highly recommended that you leave this asnil
(default) to target the active device. If you provide the id of a device that is not active, you may get a 403 “Player command failed: Restriction violated” error. If you want to skip to the previous item on a non-active device, calltransferPlayback(to:play:)
first. -
Pause the user’s current playback.
This endpoint requires the
userModifyPlaybackState
scope.If playback is already paused, then you will get a 403 “Player command failed: Restriction violated” error.
When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func pausePlayback( deviceId: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
deviceId
The id of the device to target. See
availableDevices()
. It is highly recommended that you leave this asnil
(default) to target the active device. If you provide the id of a device that is not active, you may get a 403 “Player command failed: Restriction violated” error. If you want to pause playback on a non-active device, calltransferPlayback(to:play:)
first. -
Resume the current user’s current playback.
See also:
play(_:deviceId:)
- play specific contenttransferPlayback(to:play:)
- transfer playback to a different device
This endpoint requires the
userModifyPlaybackState
scope.If content is already playing, then you will get a 403 “Player command failed: Restriction violated” error.
When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func resumePlayback( deviceId: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
deviceId
The id of the device to target. See
availableDevices()
. It is highly recommended that you leave this asnil
(default) to target the active device. If you provide the id of a device that is not active, you may get a 403 “Player command failed: Restriction violated” error. If you want to resume playback on a non-active device, calltransferPlayback(to:play:)
first. -
Play content for the current user.
See also:
resumePlayback(deviceId:)
- resume the user’s current playbacktransferPlayback(to:play:)
- transfer the user’s playback to a different device
This endpoint requires the
userModifyPlaybackState
scope.The
playbackRequest
has the following parameters:context: The context in which to play the content. One of the following:
contextURI(SpotifyURIConvertible)
: A URI for the context in which to play the content. Must be in one of the following categories:- Album
- Artist
- Show
- Playlist
uris([SpotifyURIConvertible])
: An array of track/episode URIs.
offset: Indicates where in the context playback should start. One of the following:
position(Int)
: The index of the item in the context at which to start playback. Cannot be used if the context is an artist.uri(SpotifyURIConvertible)
: The URI of the item to start playback at.
positionMS: Indicates from what position to start playback in milliseconds. If
nil
, then the track/episode will start from the beginning. Passing in a position that is greater than the length of the track/episode will cause the player to start playing the next item.
When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func play( _ playbackRequest: PlaybackRequest, deviceId: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
deviceId
The id of the device to target. See
availableDevices()
. Unlike other player endpoints, you can provide the id of a non-active device, which will cause the given content to be played on that device. Leave asnil
to target the active device. If there are no active devices, then you must provide a device id, otherwise you will get a “Player command failed: No active device found” error.playbackRequest
A request to play content for the user. See above.
-
Seek to position in the currently playing track/episode.
This endpoint requires the
userModifyPlaybackState
scope.When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func seekToPosition( _ positionMS: Int, deviceId: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
positionMS
The position in milliseconds to seek to. Must be a positive number. Passing in a position that is greater than the length of the track will cause the player to start playing the next song.
deviceId
The id of the device to target. See
availableDevices()
. It is highly recommended that you leave this asnil
(default) to target the active device. If you provide the id of a device that is not active, you may get a 403 “Player command failed: Restriction violated” error. If you want to seek to a position on a non-active device, calltransferPlayback(to:play:)
first. -
Set the repeat mode for the user’s playback.
This endpoint requires the
userModifyPlaybackState
scope.When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func setRepeatMode( to repeatMode: RepeatMode, deviceId: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
repeatMode
Either
track
,context
oroff
. track will repeat the current track. context will repeat the current context.off
will turn repeat off.deviceId
The id of the device to target. See
availableDevices()
. It is highly recommended that you leave this asnil
(default) to target the active device. If you provide the id of a device that is not active, you may get a 403 “Player command failed: Restriction violated” error. If you want to set the repeat mode on a non-active device, calltransferPlayback(to:play:)
first. -
Set the volume for the user’s playback.
This endpoint requires the
userModifyPlaybackState
scope.You can not set the volume for the Spotify iOS app.
When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func setVolume( to percent: Int, deviceId: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
percent
The volume to set. Must be in the range 0…100.
deviceId
The id of the device to target. See
availableDevices()
. It is highly recommended that you leave this asnil
(default) to target the active device. If you provide the id of a device that is not active, you may get a 403 “Player command failed: Restriction violated” error. If you want to set the volume on a non-active device, calltransferPlayback(to:play:)
first. -
Set the shuffle mode for the user’s playback.
This endpoint requires the
userModifyPlaybackState
scope.When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func setShuffle( to mode: Bool, deviceId: String? = nil ) -> AnyPublisher<Void, Error>
Parameters
mode
true
to turn shuffle on;false
to turn if off.deviceId
The id of the device to target. See
availableDevices()
. It is highly recommended that you leave this asnil
(default) to target the active device. If you provide the id of a device that is not active, you may get a 403 “Player command failed: Restriction violated” error. If you want to set the shuffle mode on a non-active device, calltransferPlayback(to:play:)
first. -
Transfer the user’s playback to a different device.
After you transfer playback to a different device, that device will be considered active.
See also
resumePlayback(_:deviceId:)
andplay(_:deviceId:)
.This endpoint requires the
userModifyPlaybackState
scope.When performing an action that is restricted, a
SpotifyPlayerError
will be returned. It contains the following properties:message
: A short description of the cause of the error.reason
: A player error reason, modeled bySpotifyPlayerError.ErrorReason
.statusCode
: The HTTP status code that is also returned in the response header.
See also Using the Player Endpoints.
Read more at the Spotify web API reference.
Declaration
Swift
func transferPlayback( to deviceId: String, play: Bool ) -> AnyPublisher<Void, Error>
Parameters
deviceId
The id of a device to transfer the playback to. Must be one of the devices returned by
availableDevices()
.play
If
true
, ensure playback happens on the new device. Iffalse
, keep the current playback state. Note that a value offalse
will NOT pause playback. To ensure that playback is paused on the new device you should callpausePlayback(deviceId:)
(and wait for completion) before transferring playback to the new device.
-
Get a list of the current user’s playlists, including those that they are following.
See also
userPlaylists(for:limit:offset:)
.No scopes are required for retrieving the user’s public playlists. However, the access token must have been issued on behalf of a user. Requires the
playlistReadPrivate
scope for retrieving private playlists. TheplaylistReadCollaborative
scope is required to retrieve collaborative playlists, even though these are also always private. See also Working with Playlists.Returns:
PagingObject<Playlist<PlaylistItemsReference>>
The simplified versions of the playlists will be returned.
A
PlaylistItemsReference
simply contains a link to all of the tracks/episodes and the total number in the playlist. To get all of the tracks and episodes in each playlist, you can useplaylistItems(_:limit:offset:market:)
, passing in the URI of each of the playlists. To get all of the URIs, use:let uris: [String] = playlists.items.map(\.uri)
Read more at the Spotify web API reference.
Declaration
Swift
func currentUserPlaylists( limit: Int? = nil, offset: Int? = nil ) -> AnyPublisher<PagingObject<Playlist<PlaylistItemsReference>>, Error>
Parameters
limit
Optional. The maximum number of playlists to return. Default: 20; Minimum: 1; Maximum: 50.
offset
Optional. The index of the first playlist to return. Default: 0; Maximum: 100,000. Use with
limit
to get the next set of playlists. -
Get the current images associated with a specific playlist.
See also
playlist(_:market:)
.No scopes are required for this endpoint; the access token must have been issued on behalf of a user, but not necessarily the owner of this playlist.
Read more at the Spotify web API reference.
Declaration
Swift
func playlistImage( _ playlist: SpotifyURIConvertible ) -> AnyPublisher<[SpotifyImage], Error>
Parameters
playlist
A Spotify playlist.
Return Value
An array of image objects, which contain the URL for the image and its dimensions.
-
Add tracks/episodes to one of the current user’s playlists.
Adding items to the current user’s public playlists requires authorization of the
playlistModifyPublic
scope; adding items to the current user’s private playlists (including collaborative playlists) requires theplaylistModifyPrivate
scope.Read more at the Spotify web API reference.
Declaration
Swift
func addToPlaylist( _ playlist: SpotifyURIConvertible, uris: [SpotifyURIConvertible], position: Int? = nil ) -> AnyPublisher<String, Error>
Parameters
playlist
The URI of a playlist.
uris
An Array of URIs for tracks/episodes. A maximum of 100 items can be added in one request.
position
Optional. The position to insert the items. A zero-based index. If
nil
, the items will be appended to the playlist.Return Value
The snapshot id of the playlist, which is an identifier for the current version of the playlist. Every time the playlist changes, a new snapshot id is generated. You can use this value to efficiently determine whether a playlist has changed since the last time you retrieved it. Can be supplied in other requests to target a specific playlist version.
-
Create a playlist for the current user.
Creating a public playlist for a user requires authorization of the
playlistModifyPublic
scope; creating a private playlist requires theplaylistModifyPrivate
scope.Read more at the Spotify web API reference.
Declaration
Swift
func createPlaylist( for userURI: SpotifyURIConvertible, _ playlistDetails: PlaylistDetails ) -> AnyPublisher<Playlist<PlaylistItems>, Error>
Parameters
userURI
The URI of a user. The access token must have been issued on behalf of this user.
playlistDetails
The details of the playlist.
Return Value
The just-created playlist. It will be empty until you add tracks/episodes.
-
Reorders the tracks/episodes in a playlist.
See also:
removeSpecificOccurrencesFromPlaylist(_:urisWithPositions:)
removeAllOccurrencesFromPlaylist(_:uris:)
replaceAllPlaylistItems(_:with:)
Reordering items in the current user’s public playlists requires authorization of the
playlistModifyPublic
scope; reordering items in the current user’s private playlists (including collaborative playlists) requires theplaylistModifyPrivate
scope.The body of the request contains the following properties:
- rangeStart: The position of the first item to be reordered.
- rangeLength: The amount of items to be reordered. Defaults to 1.
The range of items to be reordered begins from the
rangeStart
position (inclusive), and includes therangeLength
subsequent items. For example, ifrangeLength
is 1, then the item at indexrangeStart
will be inserted before the item at indexinsertBefore
. - insertBefore: The position where the items should be inserted.
- snapshotId: Optional. The version identifier for the current playlist.
Examples:
To reorder the first item to the last position in a playlist with 10 items, set
rangeStart
to 0, setrangeLength
to 1 (default) andinsertBefore
to 10.To reorder the last item in a playlist with 10 items to the start of the playlist, set
rangeStart
to 9, setrangeLength
to 1 (default) and setinsertBefore
to 0.To move the items at index 9-10 to the start of the playlist, set
rangeStart
to 9, setrangeLength
to 2, and setinsertBefore
to 0.Read more at the Spotify web API reference.
Declaration
Swift
func reorderPlaylistItems( _ playlist: SpotifyURIConvertible, body: ReorderPlaylistItems ) -> AnyPublisher<String, Error>
Parameters
playlist
The URI of a playlist.
body
An instance of
ReorderPlaylistItems.
See above.Return Value
The snapshot id of the playlist, which is an identifier for the current version of the playlist. Every time the playlist changes, a new snapshot id is generated. You can use this value to efficiently determine whether a playlist has changed since the last time you retrieved it. Can be supplied in other requests to target a specific playlist version.
-
Replace all the tracks/episodes in a playlist with new items.
Replace all the items in a playlist, overwriting its existing items. This powerful request can be useful for replacing items, re-ordering existing items, or clearing the playlist.
See also:
removeSpecificOccurrencesFromPlaylist(_:urisWithPositions:)
removeAllOccurrencesFromPlaylist(_:uris:)
reorderPlaylistItems(_:body:)
Setting items in the current user’s public playlists requires authorization of the
playlistModifyPublic
scope; setting items in the current user’s private playlists (including collaborative playlists) requires theplaylistModifyPrivate
scope.If a single URI is invalid, then the entire request will fail and the playlist will not be modified.
Read more at the Spotify web API reference.
Declaration
Swift
func replaceAllPlaylistItems( _ playlist: SpotifyURIConvertible, with newItems: [SpotifyURIConvertible] ) -> AnyPublisher<String, Error>
Parameters
playlist
The URI of a playlist.
newItems
The new items to replace all of the current items with. A maximum of 100 items can be sent at once. Pass in an empty array to remove all of the items from the playlist.
Return Value
The snapshot id of the playlist, which is an identifier for the current version of the playlist. Every time the playlist changes, a new snapshot id is generated. You can use this value to efficiently determine whether a playlist has changed since the last time you retrieved it. Can be supplied in other requests to target a specific playlist version.
-
Change the details of a playlist.
Changing a public playlist for a user requires authorization of the
playlistModifyPublic
scope; changing a private playlist requires theplaylistModifyPrivate
scope.The details of the playlist that can be changed are:
- name: The new name for the playlist.
- isPublic: If
true
the playlist will be public; iffalse
it will be private. - collaborative: If
true
, the playlist will become collaborative and other users will be able to modify the playlist in their Spotify client. Note: You can only set collaborative totrue
on non-public playlists. - description: A new playlist description as displayed in Spotify Clients and in the Web API.
All of the properties are optional. The value of each non-
nil
property will be used update the details of the playlist.Read more at the Spotify web API reference.
Declaration
Swift
func changePlaylistDetails( _ playlist: SpotifyURIConvertible, to newDetails: PlaylistDetails ) -> AnyPublisher<Void, Error>
Parameters
playlist
The URI of a playlist.
newDetails
The new details to update the playlist with.
-
Upload an image for a playlist.
This endpoint requires the
ugcImageUpload
scope. In addition, theplaylistModifyPublic
scope is required for public playlists, and theplaylistModifyPrivate
scope is required for private playlists.To convert a
UIImage
to base64-encoded jpeg data, use:let jpegData = uiImage.jpegData( compressionQuality: 0.5 )! let base64EncodedData = jpegData.base64EncodedData()
Adjust the compression quality as needed to ensure the size is below 256 KB.
The process of uploading the image may take some time, so performing a request for this playlist may not immediately return the image.
Read more at the Spotify web API reference.
Declaration
Swift
func uploadPlaylistImage( _ playlist: SpotifyURIConvertible, imageData: Data ) -> AnyPublisher<Void, Error>
Parameters
playlist
The URI of a playlist.
imageData
Base64-encoded JPEG image data. Maximum size is 256 KB.
-
Removes all Occurrences of the specified tracks/episodes from a playlist.
See also:
removeSpecificOccurrencesFromPlaylist(_:urisWithPositions:)
replaceAllPlaylistItems(_:with:)
reorderPlaylistItems(_:body:)
Removing items from a user’s public playlist requires authorization of the
playlistModifyPublic
scope; removing items from a private playlist requires theplaylistModifyPrivate
scope.If a single URI is invalid, then the entire request will fail and the playlist will not be modified. Trying to remove an item that is not contained in the playlist has no effect.
Read more at the Spotify web API reference.
Declaration
Swift
func removeAllOccurrencesFromPlaylist( _ playlist: SpotifyURIConvertible, of uris: [SpotifyURIConvertible], snapshotId: String? = nil ) -> AnyPublisher<String, Error>
Parameters
playlist
The URI for a playlist.
uris
An Array of URIs for tracks/episodes. A maximum of 100 items can be removed at once.
snapshotId
The snapshot id of the playlist to target. If
nil
, the most recent version of the playlist is targeted.Return Value
The snapshot id of the playlist, which is an identifier for the current version of the playlist. Every time the playlist changes, a new snapshot id is generated. You can use this value to efficiently determine whether a playlist has changed since the last time you retrieved it. Can be supplied in other requests to target a specific playlist version.
-
Removes the specified tracks/episodes at the specified positions from a playlist. This is useful if the playlist contains duplicate items.
See also:
removeAllOccurrencesFromPlaylist(_:uris:)
replaceAllPlaylistItems(_:with:)
reorderPlaylistItems(_:body:)
Removing items from a user’s public playlist requires authorization of the
playlistModifyPublic
scope; removing items from a private playlist requires theplaylistModifyPrivate
scope.If a single URI is invalid or if a given item is not found at a given position, the entire request will fail and no edits will take place.
Read more at the Spotify web API reference.
Declaration
Swift
func removeSpecificOccurrencesFromPlaylist( _ playlist: SpotifyURIConvertible, of urisWithPositions: URIsWithPositionsContainer ) -> AnyPublisher<String, Error>
Parameters
playlist
The URI for a playlist.
urisWithPositions
A collection of URIs along with their positions in a playlist and, optionally, the snapshot id of the playlist you want to target. A maximum of 100 items can be sent at once.
Return Value
The snapshot id of the playlist, which is an identifier for the current version of the playlist. Every time the playlist changes, a new snapshot id is generated. You can use this value to efficiently determine whether a playlist has changed since the last time you retrieved it. Can be supplied in other requests to target a specific playlist version.
-
Get the profile of the current user.
See also
userProfile(_:)
.The access token must have been issued on behalf of a user.
The
allowsExplicitContent
,explicitContentSettingIsLocked
,country
, andproduct
properties ofSpotifyUser
require theuserReadPrivate
scope.SpotifyUser.email
requires theuserReadEmail
scope.If the application is not authorized for these scopes, then these properties will be
nil
.Read more at the Spotify web API reference.
Declaration
Swift
func currentUserProfile() -> AnyPublisher<SpotifyUser, Error>