RSpotify
This is a ruby wrapper for the Spotify Web API.
Features
Installation
Add this line to your application's Gemfile:
gem 'rspotify'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rspotify
Usage
RSpotify was designed with usability as its primary goal, so that you can forget the API and intuitively interact with your playlists, favorite artists, users and so on.
You can write things like my_playlist.tracks.sort_by(&:popularity).last.album
without having to think which API calls must be done. RSpotify fills the gaps for you.
Below are some basic usage examples. Check the documentation for the complete reference.
require 'rspotify'
artists = RSpotify::Artist.search('Arctic Monkeys')
arctic_monkeys = artists.first
arctic_monkeys.popularity
arctic_monkeys.genres
arctic_monkeys.top_tracks(:US)
albums = arctic_monkeys.albums
albums.first.name
am = albums.first
am.release_date
am.images
am.available_markets
tracks = am.tracks
tracks.first.name
do_i_wanna_know = tracks.first
do_i_wanna_know.duration_ms
do_i_wanna_know.track_number
do_i_wanna_know.preview_url
playlists = RSpotify::Playlist.search('Indie')
playlists.first.name
albums = RSpotify::Album.search('The Wall')
tracks = RSpotify::Track.search('Thriller')
Find by id:
arctic_monkeys = RSpotify::Artist.find('7Ln80lUS6He07XvHI8qqHH')
arctic_monkeys.related_artists
am = RSpotify::Album.find('41vPD50kQ7JeamkxQW7Vuy')
am.album_type
do_i_wanna_know = RSpotify::Track.find('2UzMpPKPhbcC8RbsmuURAZ')
do_i_wanna_know.album
me = RSpotify::User.find('guilhermesad')
me.uri
ids = %w(2UzMpPKPhbcC8RbsmuURAZ 7Jzsc04YpkRwB1zeyM39wE)
my_tracks = RSpotify::Track.find(ids)
my_tracks.size
Some data require authentication to be accessed, such as playlists' details. You can easily get your credentials here.
Then just copy and paste them like so:
RSpotify.authenticate("<your_client_id>", "<your_client_secret>")
me = RSpotify::User.find('guilhermesad')
me.playlists
playlist = RSpotify::Playlist.find('guilhermesad', '1Xi8mgiuHHPLQYOw2Q16xv')
playlist.name
playlist.description
playlist.followers['total']
playlist.tracks
party = RSpotify::Category.find('party')
party.playlists
categories = RSpotify::Category.list
featured_playlists = RSpotify::Playlist.browse_featured(country: 'US')
new_releases = RSpotify::Album.new_releases(country: 'ES')
sorry = RSpotify::Track.search("Sorry").first
sorry.audio_features.danceability
sorry.audio_features.energy
sorry.audio_features.tempo
recommendations = RSpotify::Recommendations.generate(seed_genres: ['blues', 'country'])
recommendations = RSpotify::Recommendations.generate(seed_tracks: my_fav_tracks.map(&:id))
recommendations = RSpotify::Recommendations.generate(seed_artists: my_fav_artists.map(&:id))
recommendations.tracks
Rails + OAuth
You might want your application to access a user's Spotify account.
For instance, suppose you want your app to create playlists for the user based on their taste, or to add a feature that syncs user's playlists with some external app.
If so, add the following to your application (Remember to get your credentials)
RSpotify::authenticate("<your_client_id>", "<your_client_secret>")
require 'rspotify/oauth'
Rails.application.config.middleware.use OmniAuth::Builder do
provider :spotify, "<your_client_id>", "<your_client_secret>", scope: 'user-read-email playlist-modify-public user-library-read user-library-modify'
end
OmniAuth.config.allowed_request_methods = [:post, :get]
You should replace the scope values for the ones your own app will require from the user. You can see the list of available scopes in here.
Next, make a link so the user can log in with his Spotify account:
<%= link_to 'Sign in with Spotify', '/auth/spotify', method: :post %>
And create a route to receive the callback:
get '/auth/spotify/callback', to: 'users#spotify'
Remember you need to tell Spotify this address is white-listed. You can do this by adding it to the Redirect URIs list in your application page. An example of Redirect URI would be http://localhost:3000/auth/spotify/callback.
Finally, create a new RSpotify User with the response received:
class UsersController < ApplicationController
def spotify
spotify_user = RSpotify::User.new(request.env['omniauth.auth'])
spotify_user.country
spotify_user.email
playlist = spotify_user.create_playlist!('my-awesome-playlist')
tracks = RSpotify::Track.search('Know')
playlist.add_tracks!(tracks)
playlist.tracks.first.name
spotify_user.save_tracks!(tracks)
spotify_user.saved_tracks.size
spotify_user.remove_tracks!(tracks)
albums = RSpotify::Album.search('launeddas')
spotify_user.save_albums!(albums)
spotify_user.saved_albums.size
spotify_user.remove_albums!(albums)
spotify_user.follow(playlist)
spotify_user.follows?(artists)
spotify_user.unfollow(users)
spotify_user.top_artists
spotify_user.top_tracks(time_range: 'short_term')
end
end
Refreshing the access token
The user's access token is automatically refreshed by RSpotify when needed. This is especially useful if you persist
the user data on a database. This way, the user only need log in to Spotify once during the use of the application.
Additionally, you can store a proc that is invoked when a new access token is generated. This give you the
opportunity to persist the new access token for future use. The proc will be invoked with two arguments: the
new access token and the lifetime of the token in seconds. For example, if lifetime value returned from
Spotify is 3600, you know that the token will be good for one hour.
In the sample code below, the credentials have been retrieved from some persistent store such as
AWS SecretsManager.
callback_proc = Proc.new { |new_access_token, token_lifetime |
now = Time.now.utc.to_i
deadline = now+token_lifetime
self.save_new_access_token(new_access_token)
}
spotify_user = RSpotify::User.new(
{
'credentials' => {
"token" => self.credentials["access_token"],
"refresh_token" => self.credentials["refresh_token"],
"access_refresh_callback" => callback_proc
} ,
'id' => self.credentials["user_id"]
})
RSpotify provides a way to facilitate persistence:
hash = spotify_user.to_hash
spotify_user = RSpotify::User.new(hash)
spotify_user.create_playlist!('my_awesome_playlist')
Getting raw response
To get the raw response from Spotify API requests, just toggle the raw_response
variable:
RSpotify.raw_response = true
RSpotify::Artist.search('Cher')
Notes
If you'd like to use OAuth outside rails, have a look here for the requests that need to be made. You should be able to pass the response to RSpotify::User.new just as well, and from there easily create playlists and more for your user.
Contributing
- Fork it ( https://github.com/guilhermesad/rspotify/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Test your changes (
bundle exec rspec
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request