1. Home
  2. OSS Drivers & Modules
  3. ossEasyAPI: Spotify ‘now playing’ information

ossEasyAPI: Spotify ‘now playing’ information

Introduction

This is a guide to accessing the Spotify music service REST API.
The guide includes a description of the API access authorisation process and a few example API requests.

Overview

To be able to access Spotify data and control the operation of Spotify clients the user must first register an application to access the API.
The user must then generate an authorisation code using a manual process.
This authorisation code is then used in a token request which returns an access token and a refresh token.
The access token can then be used in API requests to access the Spotify API.
This access token will expire, usually after one hour.
The refresh token is then used to obtain a new access token.


The above process is described in the following Spotify documentation:

https://developer.spotify.com/documentation/general/guides/authorization-guide/

The descriptions in this document are valid as of March 2020. Updates to the Spotify API or web portal may mean that this guide does not reflect the latest procedures. Please refer to the latest Spotify API documentation for up to date information.


Registering An Application

To be able to register an application you will need to access the Spotify dashboard using your Spotify login credentials:

https://developer.spotify.com/dashboard

Create The Application

To register and configure an application click on the “Create A Client ID” button on the Spotify dashboard.
This will prompt you to enter an application name and description.
Click on the “I don’t know” option to create a non-commercial application.
You can try using the other options, but we do not have experience of these.
If non-commercial, you will be prompted to confirm that the application will not be used for commercial purposes under the Spotify terms and conditions.

Configure The Application Settings

Once the application has been created you must update the settings to be able to complete the
authorisation stage.
On the application page click on the “Edit Settings” button.
You must enter a value in the “Redirect URIs” field.
This redirect URI should be a safe website as a request will be sent here with a private authorisation code.
It works if you use a dummy local address (even if you have no local web server running):

http://localhost:8888/callback

Once the address is entered click on the “Save” button at the bottom of the window.

Save Credentials

On the Spotify API application page click on the “Show Client Secret” button and make a record of both the client ID and the client secret, for use later.


Authorisation Code

Select The Authorisation Scope

First you must decide on what operations and information the application will be authorised to access, this is called the ‘scope’.
These are described in the Spotify documentation:

https://developer.spotify.com/documentation/general/guides/authorization/scopes/

You can include multiple scopes, separated by a plus (“+”) sign.
Scopes you are likely to need to read and control Spotify clients are: “user-read-playback-state” and “user-modify-playback-state”.
If you change the scope you will have to regenerate the authorisation code and then the access token.

Create API Authorisation code URL

To generate an API authorisation code you must first construct a special URL.
This URL begins with the following text:

https://accounts.spotify.com/authorize

This is followed by the parameters described in Table 1.

Parameter IDValue
client_idThe client ID generated when registering the application.
response_typeThe text value ‘code’.
redirect_uriThis must be the redirect URI specified when creating the application. This URL
text must be ‘escaped’ to remove certain invalid characters. See the example
below for guidance.
scopeThis contains the list of permissions that you have previously selected. Multiple
values are separated by plus (‘+’) signs.
show_dialogThe text value ‘true’.
Table 1: Authorisation Code URL Parameters

API Authorisation code URL Example

The following is an example of an authorisation code URL:

https://accounts.spotify.com/authorize

?client_id=<CLIENT-ID>&response_type=code

&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Fcallback

&scope=user-read-playback-state+user-modify-playback-state&show_dialog=true

This should be one continuous line, but has be divided for clarity. The ‘<CLIENT-ID>’ section should be replaced with your own application client ID.

The redirect_uri text is an example of the ‘http://localhost:8888/callback’ URL that has been escaped.
Change the scope values if you have selected different permissions.

Use the URL to generate the Authorisation Code

Copy the URL you have created as one continuous line and paste it into a web browser address bar, (it is recommended to use the Google Chrome web browser).
This will take you to a Spotify login page, (if you are not already logged in). You will need to log into the Spotify account that you used to set up the application.
Once logged in you will be taken to an authorisation confirmation page that will summarise the permissions that you are granting to the application accessing the API using this authorisation code.
Click on the agree button to continue.
This will redirect the web browser to the redirect URL you specified, but followed by parameter which contains the required API authorisation code.
(Note that if you are using the localhost based redirect URI, without a local web server, then the redirect will lead to a invalid web page (e.g. “unable to connect”). This is OK, as it is not the web page that is important, just the text in the address bar).
To extract the authorisation code from the address bar text find the ‘?code=’ text in the URL. The code starts after the equals (‘=’) sign and continues to the end of the line.
This resulting URL usually takes the following form:

http://localhost:8888/callback?code=<THE-AUTH-CODE-TO-EXTRACT>

You should end up with a code that is a long (200+ characters) line of text that includes letters, numbers, underscores (‘_’) and minus signs (‘-‘), but should not contain ampersand (‘&’) or equals (‘=’) characters.

Authorisation Code Expiry

Spotify authorisation codes are only valid for around 10 minutes, so the next step, the initial token request must be completed in this time or another code will need to be generated, by repeating the process described in this section.
Additionally, authorisation codes can only be used once to generate tokens, then those tokens must be refreshed using the refresh token to continue accessing the API. If the tokens are lost then the authorisation code must be regenerated and new tokens obtained.


Initial Token Request

Token Request

Once you have an API authorisation code you can use it to get access tokens.
The token request requires a HTTP POST request to the following URL:

https://accounts.spotify.com/api/token

The only HTTP header that is required is the ‘basic access authentication’ header as defined in RFC 7617. The username is the application client ID and the password is the application client secret.
The HTTP POST body data must include the parameters described in Table 2.

Parameter IDValue
grant_typeThe text value ‘authorisation_code’.
codeThe application authorisation code value obtained in ‘Authorisation Code‘.
redirect_uriThis should contain the same redirection URI used in ‘Authorisation Code‘ (escaped).
Table 2: Token Request Parameters

This should result in a request body of the following form:

grant_type=authorisation_code

&code=<AUTHORISATION-CODE>

&redirect_uri=https%3A%2D%2Flocalhost%3A8888%2Fcallback

Note that this text should be used as a single, continuous line, (but has been divided for clarity). The ‘<AUTHORISATION-CODE>’ section should be replaced with the application authorisation code value obtained in ‘Authorisation Code‘. The ‘redirect_uri’ should be replaced if the you are not using the example localhost URL.

Token Response

The token request will return a JSON data response.

This JSON data should contain the fields described in Table 3.

Field KeyValue
access_tokenThe API Bearer access token to use in subsequent API accesses.
refresh_tokenThe refresh token to use when the access token expires.
expires_inThe number seconds the access token is valid for before it needs refreshing.
Table 3: Token Response Fields

Other fields can be ignored.

Limitations

As the authorisation code will expire after around 10 minutes this initial token request should be made within this time or another authorisation code must be generated.

You should ensure that you save the tokens returned in the token response as the authorisation code can be used only once. If these tokens are lost then a new authorisation code must be generated.
Access tokens have a limited lifetime, specified by the ‘expires_in’ return field. This is usually around 1 hour. Once the access token has expired then a new access token must be generated using the refresh token, as described in ‘Token Refresh‘.


Token Refresh

Token Refresh Request

API access tokens periodically expire and need to be refreshed to obtain new tokens.
This token refresh request requires a HTTP POST request to the following URL:

https://accounts.spotify.com/api/token

The only HTTP header that is required is the ‘basic access authentication’ header as defined in RFC 7617. The username is the application client ID and the password is the application client secret.
The HTTP POST body data must include the parameters described in Table 4.

Parameter IDValue
grant_typeThe text value ‘refresh_token’.
refresh_tokenThe refresh token returned by the initial token request.
Table 4: Token Refresh Request Parameters

This should result in a request body of the following form:

grant_type=refresh_token

&refresh_token=<REFRESH-TOKEN>

Note that this text should be used as a single, continuous line, (but has been divided for clarity). The ‘<REFRESH-TOKEN>’ section should be replaced with the refresh token returned by the initial token request.

Token Refresh Response

The token refresh request will return a JSON data response.

This JSON data should contain the fields described in Table 5.

Field KeyValue
access_tokenThe new API Bearer access token to use in subsequent data requests.
expires_inThe number of seconds the access token is valid for before it needs refreshing.
Table 5: Token Refresh Response Fields

Other fields can be ignored.

Note that with the Spotify API a new refresh token is not included in the token refresh. The original refresh token remains valid and can be reused whenever the access token expires.


Read Currently Playing Track

Data Request

Once you have an API access token you can use it to make API requests.

This section describes how to read data indicating the current play state of the Spotify account. This API request is described in more detail in the Spotify API documentation.

This request requires a HTTP GET request to the following URL:

https://api.spotify.com/v1/me/player/currently-playing

The following HTTP headers must be included in the request:

Authorization: Bearer: <ACCESS-TOKEN>

Where the ‘<ACCESS-TOKEN>’ section must be replaced with the access token received from the last token request (or the refresh token request).

Data Response

The request will return a JSON data response.

This JSON data will contain a range of fields with various information on the playback state. Some key fields are detailed in Table 6.

Field KeyValue
timestampAn Epoch Millisecond timestamp indicating when the data was fetched.
is_playingSet to true if something is currently playing.
progress_msProgress into the currently playing track. Can be null.
item.nameThe name of the track playing.
item.artistsAn array of artist objects. Each artist object has a name field indicating the name of the artist.
Table 6: Token Refresh Response Fields.

For full details of the JSON contents refer to the Spotify API documentation.


Pause The Current Playback

Data Request

This section describes how to pause the currently active Spotify account playback.
This API request is described in more detail in the Spotify API documentation.
This request requires a HTTP GET request to the following URL:

https://api.spotify.com/v1/me/player/pause

The following HTTP headers must be included in the request:

Authorization: Bearer <ACCESS-TOKEN>

Where the ‘<ACCESS-TOKEN>’ section must be replaced with the access token received from the last token request (or the refresh token request).

Request Response

If successful the request will return a HTTP 204 (No Content) response code.
No data will be returned.
If nothing is currently playing, or playback is already paused a HTTP 403 (Forbidden) response code will be returned.
If no Spotify client is running for the associated account (or cannot be accessed) then a HTTP 404 (Not Found) response code will be returned.
For full details of the pause request refer to the Spotify API documentation.


Start Or Resume Playback

Data Request

This section describes how to start or resume playback on the Spotify account.
This API request is described in more detail in the Spotify API documentation.
This request requires a HTTP GET request to the following URL:

https://api.spotify.com/v1/me/player/play

The following HTTP headers must be included in the request:

Authorization: Bearer <ACCESS-TOKEN>

Where the ‘<ACCESS-TOKEN>’ section must be replaced with the access token received from the last token request (or the refresh token request).

Request Response

If successful the request will return a HTTP 204 (No Content) response code.
No data will be returned.
If something is currently playing a HTTP 403 (Forbidden) response code will be returned.
If no Spotify client is running for the associated account (or cannot be accessed) then a HTTP 404 (Not Found) response code will be returned.
For full details of the pause request refer to the Spotify API documentation.


References

The following is a list of useful references:

• Overview of the Spotify Web API:
https://developer.spotify.com/documentation/web-api/

• Spotify Web API Authorization Guide:
https://developer.spotify.com/documentation/general/guides/authorization-guide/

• Spotify Web API Endpoint Reference:
https://developer.spotify.com/documentation/web-api/reference/

Updated on August 15, 2022

Was this article helpful?

Related Articles

Existing Customer?
Need some technical support from the One Sight team?
CONTACT SUPPORT