Struct Spotify

Source
pub struct Spotify<A>
where A: AuthFlow,
{ /* private fields */ }

Implementations§

Source§

impl<A> Spotify<A>
where A: AuthFlow,

Source

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.
  • None if no access token has been set or retrieved.
Source

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>

Source

pub fn with_authorization_code_pkce( client_id: impl Into<String>, redirect_uri: impl Into<String>, scopes: impl Into<Option<HashSet<Scope>>>, ) -> SpotifyResult<Self>

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");
Source

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.

Source

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.

Source

pub fn user_authorization_url(&mut self) -> String

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.
Source

pub fn verify_authorization_code(&self, url: &str) -> AuthResult<String>

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 the code or state is missing, or if the state does not match.
§Errors
  • AuthError::NoState - Returned if the self.state is None.
  • AuthError::CodeNotFound - Returned if the code parameter is missing in the URL.
  • AuthError::InvalidState - Returned if the state parameter is missing or does not match the expected value.
Source

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.
Source

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.
Source

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>

Source

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");
Source

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.

Source

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");

Trait Implementations§

Source§

impl<A> Client for Spotify<A>
where A: AuthFlow,

Source§

fn rest( &self, request: Builder, body: Vec<u8>, ) -> Result<HttpResponse<Bytes>, ApiError<Self::Error>>

Send a REST query.
Source§

impl<A> RestClient for Spotify<A>
where A: AuthFlow,

Source§

type Error = RestError

The errors which may occur for this client.
Source§

fn rest_endpoint(&self, endpoint: &str) -> Result<Url, ApiError<Self::Error>>

Get the URL for a REST v1 endpoint for the client. Read more

Auto Trait Implementations§

§

impl<A> Freeze for Spotify<A>
where A: Freeze,

§

impl<A> !RefUnwindSafe for Spotify<A>

§

impl<A> !Send for Spotify<A>

§

impl<A> !Sync for Spotify<A>

§

impl<A> Unpin for Spotify<A>
where A: Unpin,

§

impl<A> !UnwindSafe for Spotify<A>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,