pub struct Spotify<A>where
A: AuthFlow,{ /* private fields */ }Expand description
A blocking client for interacting with the Spotify Web API.
This struct provides synchronous methods for making API requests to Spotify.
It is parameterized by an authentication flow type A which determines how
the client authenticates with the Spotify API.
For most use cases, prefer using the type aliases:
SpotifyPKCEfor user-authorized access (Authorization Code with PKCE)SpotifyClientCredentialsfor app-only access (Client Credentials flow)
See AsyncSpotify for an async version of this client.
Implementations§
Source§impl<A> Spotify<A>where
A: AuthFlow,
impl<A> Spotify<A>where
A: AuthFlow,
Sourcepub fn token(&self) -> Arc<RwLock<Option<Token>>>
pub fn token(&self) -> Arc<RwLock<Option<Token>>>
Returns a shared reference to the stored access token.
This method provides access to the current access token stored within the Spotify instance.
The access token is required for making authenticated requests to the Spotify Web API.
The token is wrapped in an Arc<RwLock<Option<Token>>> to ensure thread-safe access and
shared ownership. This allows multiple threads to retrieve or update the token as needed.
§Returns
An Arc<RwLock<Option<Token>>> containing:
Some(Token)if an access token is currently available.Noneif no access token has been set or retrieved.
Sourcepub fn token_to_string(&self) -> SpotifyResult<Option<String>>
pub fn token_to_string(&self) -> SpotifyResult<Option<String>>
Serializes the currently stored access token to a JSON string.
This method converts the access token into a String in JSON format, allowing
it to be easily stored or transmitted. If no token is stored, it returns Ok(None).
§Errors
Returns a SpotifyError::DataType if serialization of the token fails.
§Returns
Ok(Some(String))- The serialized token string, if available.Ok(None)- If no token is currently stored.
Source§impl Spotify<AuthCodePKCE>
impl Spotify<AuthCodePKCE>
Creates a new instance of Spotify configured for the Authorization Code PKCE flow.
This method initializes the Spotify client with an AuthCodePKCE authentication method.
The Authorization Code PKCE flow is typically used for client-side applications where user
authentication is required, and it uses a secure code challenge to mitigate interception risks.
§Parameters
client_id: The Client ID of your Spotify application.redirect_uri: The URI to which the user will be redirected after authentication.scopes: An optional set of scopes that define the permissions the application is requesting.
§Returns
A SpotifyResult containing the Spotify client configured with Authorization Code PKCE authentication,
or a SpotifyError if initialization fails.
§Example
use spotify_web_api::{Spotify, auth::scopes};
let client_id = "your-client-id";
let redirect_uri = "your-redirect-uri";
let spotify = Spotify::with_authorization_code_pkce(client_id, redirect_uri, scopes::user_details())
.expect("Failed to create Spotify client");Sourcepub fn with_token(self, token: Token) -> Self
pub fn with_token(self, token: Token) -> Self
Sets the access token for the Spotify client and returns the updated instance.
This method allows chaining by consuming the current instance, updating the stored access token, and returning the updated instance.
The scopes in the token will override the scopes in the AuthCodePKCE.
§Parameters
token- The new access token to be stored in the client.
§Returns
The updated Spotify instance with the new token set.
Sourcepub fn token_callback(self, handler: impl Fn(Token) + 'static) -> Self
pub fn token_callback(self, handler: impl Fn(Token) + 'static) -> Self
Sets a handler to be called when the access token acquires a new value.
Constructs the full URL for user authorization.
This method generates the state and code verifier parameters to produce the complete authorization URL. The user should be redirected to this URL to begin the authorization process.
§Returns
String- The fully constructed authorization URL.
Verifies the authorization code and state returned in the callback URL.
This method extracts the code and state parameters from the provided URL. It ensures
that the state matches the one generated earlier, rejecting the response if there is a
mismatch or if the required parameters are missing.
§Arguments
url- A string slice containing the callback URL provided by the OAuth provider.
§Returns
Ok(String)containing the authorization code if verification succeeds.Err(AuthError)if thecodeorstateis missing, or if thestatedoes not match.
§Errors
AuthError::NoState- Returned if theself.stateis None.AuthError::CodeNotFound- Returned if thecodeparameter is missing in the URL.AuthError::InvalidState- Returned if thestateparameter is missing or does not match the expected value.
Sourcepub fn request_token(&self, code: &str) -> Result<(), ApiError<RestError>>
pub fn request_token(&self, code: &str) -> Result<(), ApiError<RestError>>
Requests an access token using the provided authorization code.
This method exchanges the authorization code obtained from the callback URL for an access token. The access token is required to authenticate API requests. The obtained token is stored internally and is valid for the duration specified by Spotify.
§Arguments
code- A string slice containing the authorization code provided by Spotify.
§Returns
Ok(())- If the token was successfully retrieved and stored.Err(ApiError<RestError>)- If the token request fails due to network issues, invalid authorization code, or other API errors.
Sourcepub fn request_token_from_redirect_url(
&self,
url: &str,
) -> Result<(), ApiError<RestError>>
pub fn request_token_from_redirect_url( &self, url: &str, ) -> Result<(), ApiError<RestError>>
Requests an access token using the provided redirect URL.
This method extracts the authorization code from the callback URL and exchanges it for an
access token. It combines the verify_authorization_code and request_token methods
for convenience, handling both verification and token retrieval in a single call.
§Arguments
url- A string slice containing the callback URL redirected to by Spotify after user authorization.
§Returns
Ok(())- If the token was successfully retrieved and stored.Err(ApiError<RestError>)- If the token request fails due to network issues, invalid authorization code, or other API errors.
Sourcepub fn refresh_token(&self) -> Result<(), ApiError<RestError>>
pub fn refresh_token(&self) -> Result<(), ApiError<RestError>>
Refreshes the access token using the stored refresh token.
This method retrieves a new access token by exchanging the stored refresh token. It requires that a valid refresh token is present in the current token.
§Returns
Ok(())- If the token was successfully refreshed and updated.Err(AuthError::EmptyAccessToken)- If no token is available.Err(AuthError::EmptyRefreshToken)- If no refresh token is available.Err(ApiError<RestError>)- If the token refresh request fails due to network issues or other API errors.
Source§impl Spotify<ClientCredentials>
impl Spotify<ClientCredentials>
Sourcepub fn with_client_credentials(
client_id: impl Into<String>,
client_secret: impl Into<String>,
) -> SpotifyResult<Self>
pub fn with_client_credentials( client_id: impl Into<String>, client_secret: impl Into<String>, ) -> SpotifyResult<Self>
Creates a new instance of Spotify configured for the Client Credentials flow.
This method initializes the Spotify client with a ClientCredentials authentication method.
The Client Credentials flow is typically used for server-to-server interactions where user
authentication is not required, such as accessing public Spotify API endpoints.
§Parameters
client_id: The Client ID of your Spotify application.client_secret: The Client Secret of your Spotify application.
§Returns
A SpotifyResult containing the Spotify client configured with Client Credentials authentication,
or a SpotifyError if initialization fails.
§Example
use spotify_web_api::Spotify;
let client_id = "your-client-id";
let client_secret = "your-client-secret";
let spotify = Spotify::with_client_credentials(client_id, client_secret)
.expect("Failed to create Spotify client");Sourcepub fn with_token(self, token: Token) -> Self
pub fn with_token(self, token: Token) -> Self
Sets the access token for the Spotify client and returns the updated instance.
This method allows chaining by consuming the current instance, updating the stored access token, and returning the updated instance.
The refresh_token and scope fields will be set to None in the token.
§Parameters
token- The new access token to be stored in the client.
§Returns
The updated Spotify instance with the new token set.
§Note:
Once the token is expired, subsequent requests will fail.
Sourcepub fn request_token(&self) -> Result<(), ApiError<RestError>>
pub fn request_token(&self) -> Result<(), ApiError<RestError>>
Requests an access token using the configured Client Credentials flow.
This method sends a request to the Spotify authorization server to obtain an access token. The access token is required to authenticate API requests. The obtained token is stored internally and is valid for the duration specified by Spotify.
§Returns
Ok(()): If the token was successfully retrieved and stored.Err(ApiError<RestError>): If the token request fails due to network issues, invalid credentials, or other API errors.
§Example
use spotify_web_api::Spotify;
let client_id = "your-client-id";
let client_secret = "your-client-secret";
let mut spotify = Spotify::with_client_credentials(client_id, client_secret)
.expect("Failed to create Spotify client");
spotify.request_token().expect("Failed to request token");