Crate spotifyrs

Source
Expand description

spotifyrs aims to be a relatively easy to use wrapper for the Spotify API. It is still currently under development (see issues and roadmap); however, it can be used for most purposes in its current state. This wrapper allows you to interact with the Spotify API using simple method calls and consistent objects that give you a consistent way to access the data returned by the API.

§Authorization codeflow

Note: Currently, the only supported authorization method is the PKCE extension for OAuth2.0, ideal for client-side applications.

Support exists for both a fully-automated authentication from a localhost port as well as more manual authentication that allows you to use any redirect uri. Likely the more manual authentication will become default, but it is currently gated behind the "manual_auth" feature.

§Localhost/Fully Automated Authentication

This authentication is ideal for local applications.

First, create a .env file in the root of your project with the CLIENT_ID variable:

CLIENT_ID=your_client_id

Then, you can simply create a new Spotify object with the authenticate method, which will be used to make all requests to the API. You need to pass in the localhost port you want to use for the redirect URI and the scope you need:

use spotifyrs::Spotify;

let spotify = Spotify::new(); // create blank object
spotify.authenticate(String::from("8080"), String::from("user-read-private user-read-email")).unwrap(); // authenticate it

This will open a browser window and prompt the user to authorize your application. Once they do, they will be redirected to an html page confirming the authorization. You can then use the Spotify object to make requests to the API. This can return an error if the user cancels the request. Be warned, this method will also not automatically timeout and will indefinitely hang waiting for the user to authorize if the user closes the browser.

The Spotify object will handle refreshing your access token when it expires upon making a request. This ensures that you never have to check if your token is expired.

§Arbitrary Redirect URI Authentication

This authentication method is best for all situations where the program cannot read requests sent to localhost ports on the machine. For example, a website that is employing the Spotify API.

As this authentication method does not assume assess to a local machine, it requires you to supply the client ID from within the program. Additionally, you will have to manually call a function to generate a code challenge and a code verifier, which are used by the PKCE for authentication purposes. The full code flow to get the authorization code request url looks like this:

let scope = String::from("user-modify-playback-state");
let redirect_uri = "www.YOUR_URL.com/callback";
let client_id = dotenv::var("CLIENT_ID").unwrap();

let (code_verifier, code_challenge) = generate_verifier();
let (auth_url, state) = requesturl_authorization_code(
    &client_id[..],
    redirect_uri,
    &scope[..],
    &code_challenge[..],     
);

You then should redirect the user to the provided auth_url, at which point, once the user has granted you access, they will be redirected to the provided redirect uri with a query containing both the access code (under code) and the state value. It is recommended you check this state matches that returned in the above function. With these, you should run

let spotify = Spotify::new_from_auth_code(
    auth_code,
    &client_id[..],
    scope,
    code_verifier,
    redirect_uri,
);

This Spotify object will handle refreshing the access token and is how you will interact with the API.

§Examples

We can get information on a specific artist:

let artist: Artist = spotify.get_artist("59sBwR0jPSTrbMtuTkRPN5").unwrap();

assert_eq!(artist.name, "Wild Rivers");

Alternatively, we can get the tracks in the current user’s queue:

let (currently_playing, queue) = spotify.get_users_queue().unwrap();

See the Spotify struct for a full list of supported endpoints.

Structs§

Album
Struct to represent Album
AnalysisTrack
Struct to represent a Track’s audio analysis
Artist
Struct to represent Artist
Bar
Struct representing bars in a track for audio analysis Bar: A bar (or measure) is a segment of time defined as a given number of beats.
Beat
Struct representing beats in a track for audio analysis Beat: A beat is the basic time unit of a piece of music; for example, each tick of a metronome. Beats are typically multiples of tatums.
Category
Struct to represent Spotify category
DatedAlbum
Struct to represent Album with “date_added” field
DatedTrack
Struct to represent dated track
Device
Struct to represent a playback device
ExternalTrackIds
struct to hold known external ids for tracks
FeatureTrack
Struct to represent a Track’s features
Playback
Struct representing playback state
PlaybackActions
Struct representing allowed actions for a given playback state
PlayedTrack
Struct to represent track played by user (ie in recently played)
Playlist
Struct to represent a Spotify Playlist
PlaylistTrack
Struct to represent track in playlist
Section
Struct representing sections in a track for audio analysis Section: Sections are defined by large variations in rhythm or timbre, e.g. chorus, verse, bridge, guitar solo, etc. Each section contains its own descriptions of tempo, key, mode, time_signature, and loudness.
Segment
Struct representing segments in a track for audio analysis Segment: Each segment contains a roughly consistent sound throughout its duration.
Spotify
An authenticated instance of the Spotify API client. Can be used to make requests in the given scope.
SpotifyCollection
Struct to hold general collection of Spotify objects
SpotifyImage
Struct to represent Spotify images (album art, etc.)
Tatum
Struct representing tatums in a track for audio analysis Tatum: A tatum represents the lowest regular pulse train that a listener intuitively infers from the timing of percieved musical events (segments).
Track
Struct to represent Track
User
Struct to represent User

Enums§

AlbumType
Enum to represent three states of album type
ReleaseDatePrecision
RepeatState
Enum representing repeat state of user playback
RestrictionReason
Enum to represent reason for album restriction
SpotifyContext
Enum to represent different spotify contexts
SpotifyError
Error object for Spotify struct
TimeRange
Enum to represent possibilities for time range of user top tracks and artists

Traits§

SpotifyObject
Trait to represent single Spotify objects (i.e. Track, Artist, Album, etc.)