pub struct QobuzApiService {
pub app_id: String,
pub app_secret: String,
pub user_auth_token: Option<String>,
/* private fields */
}Expand description
The service disclosing the various endpoints of the Qobuz REST API.
The service can be initialized using your own ‘app_id’ and ‘app_secret’, or by letting the service attempt to fetch these 2 values from the Qobuz Web Player.
§Examples
Basic initialization with automatic credential fetching:
use qobuz_api_rust::QobuzApiService;
#[tokio::main]
async fn main() -> Result<(), qobuz_api_rust::QobuzApiError> {
let service = QobuzApiService::new().await?;
Ok(())
}Initialization with custom credentials:
use qobuz_api_rust::QobuzApiService;
#[tokio::main]
async fn main() -> Result<(), qobuz_api_rust::QobuzApiError> {
let service = QobuzApiService::with_credentials(
Some("your_app_id".to_string()),
Some("your_app_secret".to_string())
).await?;
Ok(())
}Fields§
§app_id: StringThe application ID for the Qobuz API
This is a unique identifier for your application registered with Qobuz. It’s used in API requests to identify the source of the request.
app_secret: StringThe application secret for the Qobuz API
This is a secret key associated with your application ID. It’s used to sign requests and authenticate with the API.
user_auth_token: Option<String>The user authentication token, if authenticated
This token is obtained after successful user authentication and is used for API requests that require user context.
Implementations§
Source§impl QobuzApiService
impl QobuzApiService
Sourcepub async fn login(
&mut self,
identifier: &str,
password: &str,
) -> Result<Login, QobuzApiError>
pub async fn login( &mut self, identifier: &str, password: &str, ) -> Result<Login, QobuzApiError>
Authenticates a user with the Qobuz API using their identifier and password.
This method performs a login request to the Qobuz API using either an email address or username as the identifier. The password must be provided as an MD5 hash. On successful login, the user authentication token is automatically stored in the service instance for use in subsequent authenticated API requests.
§Arguments
identifier- The user’s identifier, which can be either an email address or usernamepassword- The MD5 hash of the user’s password
§Returns
Ok(Login)- A login response containing user information and authentication tokenErr(QobuzApiError)- If the API request fails or authentication is unsuccessful
§Example
let mut api = QobuzApiService::new().await?;
// Note: Password should be MD5 hashed
let login_result = api.login("user@example.com", "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8").await?;Sourcepub async fn login_with_token(
&mut self,
user_id: &str,
user_auth_token: &str,
) -> Result<Login, QobuzApiError>
pub async fn login_with_token( &mut self, user_id: &str, user_auth_token: &str, ) -> Result<Login, QobuzApiError>
Authenticates a user with the Qobuz API using their user ID and authentication token.
This method allows authentication using an existing user ID and authentication token, which can be useful for maintaining sessions across application restarts. On successful login, the authentication token is stored in the service instance for use in subsequent API requests that require authentication.
§Arguments
user_id- The user’s unique identifier in the Qobuz systemuser_auth_token- The user’s authentication token
§Returns
Ok(Login)- A login response containing user information and authentication tokenErr(QobuzApiError)- If the API request fails or authentication is unsuccessful
§Example
let mut api = QobuzApiService::new().await?;
let login_result = api.login_with_token("123456789", "auth_token_here").await?;Sourcepub async fn reset_password(
&self,
identifier: &str,
) -> Result<QobuzApiStatusResponse, QobuzApiError>
pub async fn reset_password( &self, identifier: &str, ) -> Result<QobuzApiStatusResponse, QobuzApiError>
Requests a password reset link for the specified user identifier.
This method sends a password reset request to the Qobuz API for the given identifier, which can be either an email address or username. If the identifier exists in the system, the user will receive instructions to reset their password.
§Arguments
identifier- The user’s identifier (email address or username) for which to request a password reset
§Returns
Ok(QobuzApiStatusResponse)- A response indicating whether the password reset request was successfulErr(QobuzApiError)- If the API request fails
§Example
let api = QobuzApiService::new().await?;
let result = api.reset_password("user@example.com").await?;
if result.status == Some("success".to_string()) {
println!("Password reset email sent successfully");
}Source§impl QobuzApiService
impl QobuzApiService
Sourcepub async fn get_album(
&self,
album_id: &str,
with_auth: Option<bool>,
extra: Option<&str>,
limit: Option<i32>,
offset: Option<i32>,
) -> Result<Album, QobuzApiError>
pub async fn get_album( &self, album_id: &str, with_auth: Option<bool>, extra: Option<&str>, limit: Option<i32>, offset: Option<i32>, ) -> Result<Album, QobuzApiError>
Retrieves an album with the specified ID.
This method fetches detailed information about a specific album from the Qobuz API, including metadata, track listing, and other album-related information.
§Arguments
album_id- The unique identifier of the album to retrievewith_auth- Optional boolean to execute request with or without user authentication token. WhenNone, defaults tofalse(no authentication).extra- Optional string specifying additional album information to include in the response, such as “items”, “tracks”, “release_tags”, etc.limit- Optional integer specifying the maximum number of tracks to include in the response. WhenNone, defaults to 1200.offset- Optional integer specifying the offset of the first track to include in the response. WhenNone, defaults to 0.
§Returns
Ok(Album)- Contains the complete album information if the request is successfulErr(QobuzApiError)- If the API request fails due to network issues, invalid parameters, or other API-related errors
§Example
let service = QobuzApiService::new().await?;
let album = service.get_album("12345", None, Some("tracks"), Some(10), None).await?;
println!("Album title: {}", album.title.unwrap_or_default());Sourcepub async fn search_albums(
&self,
query: &str,
limit: Option<i32>,
offset: Option<i32>,
with_auth: Option<bool>,
) -> Result<SearchResult, QobuzApiError>
pub async fn search_albums( &self, query: &str, limit: Option<i32>, offset: Option<i32>, with_auth: Option<bool>, ) -> Result<SearchResult, QobuzApiError>
Searches for albums using the specified query.
This method allows searching for albums based on a text query, with optional pagination parameters to control the number of results returned.
§Arguments
query- The search query string (e.g., album title, artist name)limit- Optional integer specifying the maximum number of results to return. WhenNone, defaults to 50.offset- Optional integer specifying the offset of the first result to return. WhenNone, defaults to 0.with_auth- Optional boolean to execute search with or without user authentication token. WhenNone, defaults tofalse(no authentication).
§Returns
Ok(SearchResult)- Contains the search results with albums matching the queryErr(QobuzApiError)- If the API request fails due to network issues, invalid parameters, or other API-related errors
§Example
let service = QobuzApiService::new().await?;
let results = service.search_albums("radiohead", Some(10), None, None).await?;
if let Some(albums) = results.albums {
println!("Found {} albums", albums.total.unwrap_or(0));
}Sourcepub async fn download_album(
&self,
album_id: &str,
format_id: &str,
path: &str,
config: &MetadataConfig,
) -> Result<(), QobuzApiError>
pub async fn download_album( &self, album_id: &str, format_id: &str, path: &str, config: &MetadataConfig, ) -> Result<(), QobuzApiError>
Downloads an entire album to the specified path.
This method downloads all tracks of an album to a specified directory, with options for different audio quality formats. The method handles track-by-track downloads and includes automatic credential refresh if signature errors occur during the download process.
§Arguments
album_id- The unique identifier of the album to downloadformat_id- The format ID specifying audio quality:- “5”: MP3 320 kbps
- “6”: FLAC Lossless (16-bit/44.1kHz)
- “7”: FLAC Hi-Res (24-bit/96kHz)
- “27”: FLAC Hi-Res (24-bit/192kHz)
path- The directory path where the album should be saved. The directory will be created if it doesn’t exist. The path should already include artist/album folder structure.
§Returns
Ok(())- If all tracks in the album are downloaded successfullyErr(QobuzApiError)- If the API request fails, download fails for any track, or other errors occur during the process
§Note
This method includes automatic retry with credential refresh if signature errors occur. Each track is downloaded with progress reporting and metadata embedding.
§Example
let service = QobuzApiService::new().await?;
service.download_album("12345", "6", "./downloads/Artist/Album Title").await?;
println!("Album downloaded successfully!");Source§impl QobuzApiService
impl QobuzApiService
Sourcepub async fn get_artist(
&self,
artist_id: &str,
with_auth: Option<bool>,
extra: Option<&str>,
sort: Option<&str>,
limit: Option<i32>,
offset: Option<i32>,
) -> Result<Artist, QobuzApiError>
pub async fn get_artist( &self, artist_id: &str, with_auth: Option<bool>, extra: Option<&str>, sort: Option<&str>, limit: Option<i32>, offset: Option<i32>, ) -> Result<Artist, QobuzApiError>
Retrieves detailed information about an artist using their unique ID.
This method fetches comprehensive information about a specific artist from the Qobuz API.
The response includes basic artist details as well as potentially extended information
based on the extra parameter.
§Arguments
artist_id- The unique identifier of the artist to retrievewith_auth- Whether to execute the request with user authentication (optional, defaults to false)extra- Additional information to include in the response, such as albums, playlists, etc. (optional)sort- How to sort the requested extra information (optional)limit- Maximum number of extra results to return (optional, defaults to 50)offset- Offset of the first extra result to return (optional, defaults to 0)
§Returns
Returns Ok(Artist) containing the artist information if successful, or Err(QobuzApiError)
if the API request fails.
§Example
let service = QobuzApiService::new().await?;
let artist = service.get_artist("12345", None, Some("albums"), None, None, None).await?;
println!("Artist name: {:?}", artist.name);Sourcepub async fn get_release_list(
&self,
artist_id: &str,
params: ArtistReleaseListParams,
) -> Result<ReleasesList, QobuzApiError>
pub async fn get_release_list( &self, artist_id: &str, params: ArtistReleaseListParams, ) -> Result<ReleasesList, QobuzApiError>
Retrieves a list of releases for the specified artist.
This method fetches all releases (albums, singles, etc.) associated with a specific artist. The results can be filtered and sorted based on the provided parameters.
§Arguments
artist_id- The unique identifier of the artist whose releases to fetchparams- Configuration parameters for the request, including filtering, sorting, and pagination options
§Returns
Returns Ok(ReleasesList) containing the list of releases if successful, or Err(QobuzApiError)
if the API request fails.
§Example
let service = QobuzApiService::new().await?;
let params = ArtistReleaseListParams {
release_type: Some("album".to_string()),
sort: Some("release_date".to_string()),
order: Some("desc".to_string()),
..Default::default()
};
let releases = service.get_release_list("12345", params).await?;
println!("Found {} releases", releases.items.as_ref().map(|items| items.len()).unwrap_or(0));Sourcepub async fn search_artists(
&self,
query: &str,
limit: Option<i32>,
offset: Option<i32>,
with_auth: Option<bool>,
) -> Result<SearchResult, QobuzApiError>
pub async fn search_artists( &self, query: &str, limit: Option<i32>, offset: Option<i32>, with_auth: Option<bool>, ) -> Result<SearchResult, QobuzApiError>
Searches for artists matching the specified query.
This method performs a text-based search across artist names and other metadata to find artists that match the provided query string.
§Arguments
query- The search term to look for in artist names and metadatalimit- Maximum number of results to return (optional, defaults to 50)offset- Offset for pagination (optional, defaults to 0)with_auth- Whether to execute the search with user authentication (optional, defaults to false)
§Returns
Returns Ok(SearchResult) containing the search results if successful, or Err(QobuzApiError)
if the API request fails.
§Example
let service = QobuzApiService::new().await?;
let results = service.search_artists("Beatles", Some(10), None, None).await?;
if let Some(artists) = results.artists {
println!("Found {} artists", artists.items.as_ref().map(|items| items.len()).unwrap_or(0));
}Source§impl QobuzApiService
Provides functionality for interacting with the Qobuz catalog API.
impl QobuzApiService
Provides functionality for interacting with the Qobuz catalog API.
This module contains methods for searching the Qobuz music catalog, allowing users to find albums, artists, tracks, and other content based on various criteria.
Sourcepub async fn search_catalog(
&self,
query: &str,
limit: Option<i32>,
offset: Option<i32>,
type_param: Option<&str>,
with_auth: Option<bool>,
) -> Result<SearchResult, QobuzApiError>
pub async fn search_catalog( &self, query: &str, limit: Option<i32>, offset: Option<i32>, type_param: Option<&str>, with_auth: Option<bool>, ) -> Result<SearchResult, QobuzApiError>
Searches the Qobuz catalog for content matching the specified query.
This method allows you to search across the entire Qobuz catalog or filter
results by a specific content type. The search is performed using the Qobuz API
and returns a SearchResult containing the matching items.
§Arguments
query- The search query string. This can be an artist name, album title, track title, or any other text to search for in the catalog.limit- The maximum number of results to return. Defaults to 50 if not specified. The API may return fewer results than requested depending on the search criteria.offset- The offset of the first result to return, used for pagination. Defaults to 0 if not specified, which returns results starting from the first match.type_param- Optional parameter to limit results to a specific content type. Valid values include “albums”, “artists”, “tracks”, “playlists”, “labels”, etc. If not specified, results from all content types will be returned.with_auth- Whether to execute the search with the user’s authentication token. This parameter is currently unused in the implementation but is reserved for future use to enable authenticated searches that may return personalized results.
§Examples
let api = QobuzApiService::new().await?;
// Search for "Billie Eilish" across all content types
let results = api.search_catalog("Billie Eilish", None, None, None, None).await?;
// Search for only albums by "Billie Eilish", limited to 10 results
let album_results = api.search_catalog("Billie Eilish", Some(10), None, Some("albums"), None).await?;§Returns
Ok(SearchResult)- Contains the search results with matching albums, artists, tracks, and other content based on the query. The structure includes separate sections for each content type that had matching results.Err(QobuzApiError)- If the API request fails due to network issues, authentication problems, invalid parameters, or other API-related errors.
§Errors
This function will return an error in the following cases:
- Network connectivity issues preventing the API request
- Invalid API credentials (app ID or app secret)
- Invalid parameters passed to the API
- API rate limiting
- Server-side errors from the Qobuz API
- JSON parsing errors when processing the API response
§API Endpoint
This method calls the /catalog/search endpoint of the Qobuz API.
Source§impl QobuzApiService
impl QobuzApiService
Sourcepub async fn search_articles(
&self,
query: &str,
limit: Option<i32>,
offset: Option<i32>,
with_auth: Option<bool>,
) -> Result<SearchResult, QobuzApiError>
pub async fn search_articles( &self, query: &str, limit: Option<i32>, offset: Option<i32>, with_auth: Option<bool>, ) -> Result<SearchResult, QobuzApiError>
Searches for articles using the specified query.
This method allows you to search for articles on the Qobuz platform using a text query. The results can be paginated and limited to a specific number of entries.
§Parameters
query: The search query string to match against article titles, descriptions, and contentlimit: Optional maximum number of results to return (defaults to 50 if not specified)offset: Optional offset for pagination (defaults to 0 if not specified)with_auth: Optional flag to execute the search with user authentication (defaults to false)
§Returns
Ok(SearchResult): Contains the search results including articles that match the queryErr(QobuzApiError): If the API request fails due to network issues, authentication problems, or invalid parameters
§Examples
Basic search for articles:
let results = api.search_articles("classical music", None, None, None).await?;
println!("Found {} articles", results.articles.as_ref().map(|a| a.total.unwrap_or(0)).unwrap_or(0));Search with custom limit and offset for pagination:
let results = api.search_articles("jazz", Some(10), Some(20), None).await?;
// Gets 10 articles starting from the 20th resultSourcepub async fn get_label(
&self,
label_id: &str,
with_auth: Option<bool>,
extra: Option<&str>,
limit: Option<i32>,
offset: Option<i32>,
) -> Result<Label, QobuzApiError>
pub async fn get_label( &self, label_id: &str, with_auth: Option<bool>, extra: Option<&str>, limit: Option<i32>, offset: Option<i32>, ) -> Result<Label, QobuzApiError>
Gets Label with the specified label ID.
This method retrieves detailed information about a specific music label using its unique ID.
Additional related content can be included in the response based on the extra parameter.
§Parameters
label_id: The unique identifier of the label to retrievewith_auth: Optional flag to execute the request with user authentication (defaults to false)extra: Optional string specifying additional data to include (e.g., “albums”, “news”, “articles”)limit: Optional maximum number of extra results to return (defaults to 25 if not specified)offset: Optional offset for pagination of extra results (defaults to 0 if not specified)
§Returns
Ok(Label): Contains the detailed information about the requested labelErr(QobuzApiError): If the API request fails due to network issues, authentication problems, or invalid parameters
§Examples
Basic label retrieval:
let label = api.get_label("12345", None, None, None, None).await?;
println!("Label name: {:?}", label.name);Get label with additional albums:
let label = api.get_label("12345", None, Some("albums"), Some(10), Some(0)).await?;
// Gets label info with up to 10 associated albumsSource§impl QobuzApiService
impl QobuzApiService
Sourcepub async fn get_playlist(
&self,
playlist_id: &str,
with_auth: Option<bool>,
extra: Option<&str>,
limit: Option<i32>,
offset: Option<i32>,
) -> Result<Playlist, QobuzApiError>
pub async fn get_playlist( &self, playlist_id: &str, with_auth: Option<bool>, extra: Option<&str>, limit: Option<i32>, offset: Option<i32>, ) -> Result<Playlist, QobuzApiError>
Retrieves a specific playlist by its ID from the Qobuz API.
This method fetches detailed information about a single playlist, including its metadata, tracks, and other associated information. The playlist ID uniquely identifies the playlist in the Qobuz system.
§Arguments
playlist_id- The unique identifier of the playlist to retrievewith_auth- Optional boolean to execute request with user authentication token. IfNoneorSome(false), the request is made without authentication. IfSome(true), the request uses the stored authentication token if available.extra- Optional string specifying additional information to include in the response. This can be used to request additional metadata or related content.limit- Optional integer specifying the maximum number of extra results to return. Defaults to 25 if not specified.offset- Optional integer specifying the offset of the first extra result to return. Defaults to 0 if not specified.
§Examples
let service = QobuzApiService::new().await?;
// Get a playlist by ID without additional parameters
let playlist = service.get_playlist("12345", None, None, None, None).await?;
println!("Playlist name: {:?}", playlist.name);
// Get a playlist with authentication and extra data
let playlist = service.get_playlist(
"12345",
Some(true),
Some("tracks,owner"),
Some(50),
Some(0)
).await?;§Returns
Ok(Playlist)- Successfully retrieved playlist with all available informationErr(QobuzApiError)- If the API request fails due to network issues, invalid parameters, authentication problems, or if the playlist doesn’t exist
Sourcepub async fn search_playlists(
&self,
query: &str,
limit: Option<i32>,
offset: Option<i32>,
with_auth: Option<bool>,
) -> Result<SearchResult, QobuzApiError>
pub async fn search_playlists( &self, query: &str, limit: Option<i32>, offset: Option<i32>, with_auth: Option<bool>, ) -> Result<SearchResult, QobuzApiError>
Searches for playlists using a text query through the Qobuz API.
This method allows you to search for playlists based on a text query, which can match playlist names, descriptions, or other relevant metadata. The results are returned as a paginated list of playlists that match the search criteria.
§Arguments
query- The search query string to match against playlist names, descriptions, etc.limit- Optional integer specifying the maximum number of results to return. Defaults to 50 if not specified. Maximum values may be enforced by the API.offset- Optional integer specifying the offset of the first result to return, used for pagination. Defaults to 0 if not specified.with_auth- Optional boolean to execute search with user authentication token. IfNoneorSome(false), the search is made without authentication. IfSome(true), the search uses the stored authentication token if available.
§Examples
let service = QobuzApiService::new().await?;
// Search for playlists containing "chill" without authentication
let results = service.search_playlists("chill", None, None, None).await?;
if let Some(playlists) = &results.playlists {
println!("Found {} playlists", playlists.total.unwrap_or(0));
}
// Search with pagination and authentication
let results = service.search_playlists("jazz", Some(20), Some(40), Some(true)).await?;§Returns
Ok(SearchResult)- Successfully retrieved search results containing matching playlists and metadata about the search (total count, pagination info, etc.)Err(QobuzApiError)- If the API request fails due to network issues, invalid parameters, authentication problems, or other API-related errors
Source§impl QobuzApiService
impl QobuzApiService
Sourcepub async fn get_track(
&self,
track_id: &str,
with_auth: Option<bool>,
) -> Result<Track, QobuzApiError>
pub async fn get_track( &self, track_id: &str, with_auth: Option<bool>, ) -> Result<Track, QobuzApiError>
Retrieves detailed information about a specific track by its ID.
This function fetches comprehensive metadata about a track including its title, duration, album information, performer details, and audio specifications. The request can optionally be made with authentication for access to additional content or features.
§Arguments
track_id- The unique identifier of the track to retrievewith_auth- Whether to execute the request with the user authentication token (optional, defaults to false). Whentrue, the request includes the user’s authentication token if available.
§Returns
Ok(Track)- The complete track information if the request succeedsErr(QobuzApiError)- If the API request fails due to network issues, invalid parameters, or API errors
§Example
let service = QobuzApiService::new().await?;
let track = service.get_track("12345", None).await?;
println!("Track title: {:?}", track.title);Sourcepub async fn get_track_file_url(
&self,
track_id: &str,
format_id: &str,
) -> Result<FileUrl, QobuzApiError>
pub async fn get_track_file_url( &self, track_id: &str, format_id: &str, ) -> Result<FileUrl, QobuzApiError>
Retrieves the download URL for a track in a specific audio format.
This function obtains a direct URL to download the audio file for a track in the specified format. The Qobuz API requires a signature for this endpoint, which is automatically generated and validated. If the signature is invalid (which may happen with expired app credentials), the function will attempt to refresh the credentials and retry the request.
§Arguments
track_id- The unique identifier of the trackformat_id- The format ID specifying the audio quality:5for MP3 320 kbps6for FLAC Lossless (16-bit/44.1kHz)7for FLAC Hi-Res (24-bit, ≤96kHz)27for FLAC Hi-Res (24-bit, >96kHz & ≤192kHz)
§Returns
Ok(FileUrl)- Contains the download URL and metadata about the audio file if successfulErr(QobuzApiError)- If the API request fails, credentials are invalid, or the track/format is unavailable
§Note
This endpoint requires authentication and may automatically refresh app credentials if needed.
§Example
let service = QobuzApiService::new().await?;
let file_url = service.get_track_file_url("12345", "6").await?;
if let Some(url) = file_url.url {
println!("Download URL: {}", url);
}Sourcepub async fn search_tracks(
&self,
query: &str,
limit: Option<i32>,
offset: Option<i32>,
with_auth: Option<bool>,
) -> Result<SearchResult, QobuzApiError>
pub async fn search_tracks( &self, query: &str, limit: Option<i32>, offset: Option<i32>, with_auth: Option<bool>, ) -> Result<SearchResult, QobuzApiError>
Searches for tracks based on a text query with optional pagination and authentication.
This function performs a text-based search across Qobuz’s track catalog, allowing users to find tracks by title, artist, album, or other metadata. The search can be customized with pagination parameters and optional authentication for enhanced results.
§Arguments
query- The search term to look for in track metadata (title, artist, etc.)limit- The maximum number of results to return (optional, defaults to 50, maximum 500)offset- The offset of the first result to return (optional, defaults to 0) Use this for pagination to retrieve subsequent result setswith_auth- Whether to execute the search with the user authentication token (optional, defaults to false). Whentrue, the request includes the user’s authentication token if available, potentially returning personalized or higher-quality results.
§Returns
Ok(SearchResult)- Contains the search results with track information and metadataErr(QobuzApiError)- If the API request fails due to network issues, invalid parameters, or API errors
§Example
let service = QobuzApiService::new().await?;
let results = service.search_tracks("Bohemian Rhapsody", Some(10), None, None).await?;
if let Some(tracks) = results.tracks {
println!("Found {} tracks", tracks.total.unwrap_or(0));
}Sourcepub async fn download_track(
&self,
track_id: &str,
format_id: &str,
path: &str,
config: &MetadataConfig,
) -> Result<(), QobuzApiError>
pub async fn download_track( &self, track_id: &str, format_id: &str, path: &str, config: &MetadataConfig, ) -> Result<(), QobuzApiError>
Downloads a track to the specified file path with embedded metadata.
This function downloads a track from Qobuz in the specified audio format and saves it to the provided file path. After downloading, it automatically embeds comprehensive metadata (title, artist, album, cover art, etc.) into the audio file using the metadata embedding functionality.
§Arguments
track_id- The unique identifier of the track to downloadformat_id- The format ID specifying the audio quality:5for MP3 320 kbps6for FLAC Lossless (16-bit/44.1kHz)7for FLAC Hi-Res (24-bit, ≤96kHz)27for FLAC Hi-Res (24-bit, >96kHz & ≤192kHz)
path- The file system path where the track should be saved
§Returns
Ok(())- If the track was successfully downloaded and metadata was embeddedErr(QobuzApiError)- If the API request fails, download fails, directory creation fails, or metadata embedding fails
§Note
This function displays download progress in the console. The function will attempt to create the target directory if it doesn’t exist.
§Example
let service = QobuzApiService::new().await?;
service.download_track("12345", "6", "./downloads/track.flac").await?;
println!("Track downloaded successfully!");Source§impl QobuzApiService
impl QobuzApiService
Sourcepub async fn add_user_favorites(
&self,
track_ids: Option<&str>,
album_ids: Option<&str>,
artist_ids: Option<&str>,
) -> Result<QobuzApiStatusResponse, QobuzApiError>
pub async fn add_user_favorites( &self, track_ids: Option<&str>, album_ids: Option<&str>, artist_ids: Option<&str>, ) -> Result<QobuzApiStatusResponse, QobuzApiError>
Add tracks, albums & artists to the authenticated user’s favorites. At least 1 type of favorite to add is required as parameter.
§Arguments
track_ids- IDs of the tracks to add, comma separated list (optional)album_ids- IDs of the albums to add, comma separated list (optional)artist_ids- IDs of the artists to add, comma separated list (optional)
§Returns
Ok(QobuzApiStatusResponse)- Response indicating if the request was successfulErr(QobuzApiError)- If the API request fails
§Example
// Add a track to favorites
let response = service.add_user_favorites(
Some("123456789"),
None,
None,
).await?;Sourcepub async fn delete_user_favorites(
&self,
track_ids: Option<&str>,
album_ids: Option<&str>,
artist_ids: Option<&str>,
) -> Result<QobuzApiStatusResponse, QobuzApiError>
pub async fn delete_user_favorites( &self, track_ids: Option<&str>, album_ids: Option<&str>, artist_ids: Option<&str>, ) -> Result<QobuzApiStatusResponse, QobuzApiError>
Removes tracks, albums & artists from the authenticated user’s favorites. At least 1 type of favorite to remove is required as parameter.
§Arguments
track_ids- IDs of the tracks to remove, comma separated list (optional)album_ids- IDs of the albums to remove, comma separated list (optional)artist_ids- IDs of the artists to remove, comma separated list (optional)
§Returns
Ok(QobuzApiStatusResponse)- Response indicating if the request was successfulErr(QobuzApiError)- If the API request fails
§Example
// Remove a track from favorites
let response = service.delete_user_favorites(
Some("123456789"),
None,
None,
).await?;Sourcepub async fn get_user_favorite_ids(
&self,
user_id: Option<&str>,
limit: Option<i32>,
offset: Option<i32>,
) -> Result<UserFavoritesIds, QobuzApiError>
pub async fn get_user_favorite_ids( &self, user_id: Option<&str>, limit: Option<i32>, offset: Option<i32>, ) -> Result<UserFavoritesIds, QobuzApiError>
Gets the IDs of the user favorites for the authenticated user or user with the specified user ID.
§Arguments
user_id- The User ID to fetch the favorites from. If omitted, returns favorites of the logged in user using user_auth_token (optional)limit- The maximum number of extra results to return. Defaults to 5000, minimum 1, maximum 99999 (optional)offset- The offset of the first extra result to return. Defaults to 0 (optional)
§Returns
Ok(UserFavoritesIds)- The IDs of the user favoritesErr(QobuzApiError)- If the API request fails
§Example
// Get favorite IDs with default parameters
let favorites = service.get_user_favorite_ids(None, None, None).await?;
// Get favorite IDs with custom parameters
let favorites = service.get_user_favorite_ids(
Some("123456789"),
Some(100),
Some(50),
).await?;Sourcepub async fn get_user_favorites(
&self,
user_id: Option<&str>,
type_param: Option<&str>,
limit: Option<i32>,
offset: Option<i32>,
) -> Result<UserFavorites, QobuzApiError>
pub async fn get_user_favorites( &self, user_id: Option<&str>, type_param: Option<&str>, limit: Option<i32>, offset: Option<i32>, ) -> Result<UserFavorites, QobuzApiError>
Gets user favorites of the authenticated user or user with the specified user ID.
§Arguments
user_id- The User ID to fetch the favorites from. If omitted, returns favorites of the logged in user using user_auth_token (optional)type_param- Type of favorites to include in the response (optional). Possible values are ‘tracks’, ‘albums’, ‘artists’ & ‘articles’. If no type defined, all types are returnedlimit- The maximum number of extra results to return. Defaults to 50, minimum 1, maximum 500 (optional)offset- The offset of the first extra result to return. Defaults to 0 (optional)
§Returns
Ok(UserFavorites)- The user favoritesErr(QobuzApiError)- If the API request fails
§Example
// Get all favorite types with default parameters
let favorites = service.get_user_favorites(None, None, None, None).await?;
// Get only favorite albums with custom parameters
let album_favorites = service.get_user_favorites(
None,
Some("albums"),
Some(100),
Some(20),
).await?;Source§impl QobuzApiService
impl QobuzApiService
Sourcepub async fn get<T>(
&self,
endpoint: &str,
params: &[(String, String)],
) -> Result<T, QobuzApiError>where
T: DeserializeOwned,
pub async fn get<T>(
&self,
endpoint: &str,
params: &[(String, String)],
) -> Result<T, QobuzApiError>where
T: DeserializeOwned,
Sends a GET request to the Qobuz API.
This method handles the complete request lifecycle including parameter formatting, authentication token injection, response parsing, and error handling. It automatically includes common parameters and checks for API error responses.
§Arguments
endpoint- The API endpoint to call (e.g., “/album/get”)params- A slice of key-value parameter pairs to include in the query string
§Type Parameters
T- The expected response type that must implementDeserializeOwned
§Returns
Returns Ok(T) with the deserialized response data if the request is successful,
or Err(QobuzApiError) if the request fails due to network issues, API errors,
or response parsing problems.
§Examples
let album_id = "12345";
let params = vec![("album_id".to_string(), album_id.to_string())];
let album: Album = service.get("/album/get", ¶ms).await?;§Errors
This function will return an error if:
- The HTTP request fails (network issues)
- The API returns an error response (status: “error”)
- The response cannot be parsed as the expected type
T - The response cannot be deserialized from JSON
Sourcepub async fn post<T>(
&self,
endpoint: &str,
params: &[(String, String)],
) -> Result<T, QobuzApiError>where
T: DeserializeOwned,
pub async fn post<T>(
&self,
endpoint: &str,
params: &[(String, String)],
) -> Result<T, QobuzApiError>where
T: DeserializeOwned,
Sends a POST request to the Qobuz API.
This method handles POST requests to the Qobuz API, automatically including required parameters like the application ID and user authentication token if available. It manages the complete request lifecycle including parameter formatting, response parsing, and error handling.
§Arguments
endpoint- The API endpoint to call (e.g., “/user/login”)params- A slice of key-value parameter pairs to include in the form body
§Type Parameters
T- The expected response type that must implementDeserializeOwned
§Returns
Returns Ok(T) with the deserialized response data if the request is successful,
or Err(QobuzApiError) if the request fails due to network issues, API errors,
or response parsing problems.
§Examples
let params = vec![
("email".to_string(), "user@example.com".to_string()),
("password".to_string(), "hashed_password".to_string()),
];
let login_response: Login = service.post("/user/login", ¶ms).await?;§Errors
This function will return an error if:
- The HTTP request fails (network issues)
- The API returns an error response (status: “error”)
- The response cannot be parsed as the expected type
T - The response cannot be deserialized from JSON
Sourcepub async fn signed_get<T>(
&self,
endpoint: &str,
params: &[(String, String)],
) -> Result<T, QobuzApiError>where
T: DeserializeOwned,
pub async fn signed_get<T>(
&self,
endpoint: &str,
params: &[(String, String)],
) -> Result<T, QobuzApiError>where
T: DeserializeOwned,
Sends a GET request to the Qobuz API with signature authentication.
This method is used for protected endpoints that require signature-based authentication. It automatically generates the required signature using the Qobuz API’s authentication scheme, includes the necessary parameters (app_id, user_auth_token if available), and handles the complete request lifecycle including response parsing and error handling.
§Arguments
endpoint- The API endpoint to call (e.g., “/album/get”)params- A slice of key-value parameter pairs to include in the query string
§Type Parameters
T- The expected response type that must implementDeserializeOwned
§Returns
Returns Ok(T) with the deserialized response data if the request is successful,
or Err(QobuzApiError) if the request fails due to network issues, API errors,
or response parsing problems.
§Examples
let album_id = "12345";
let params = vec![("album_id".to_string(), album_id.to_string())];
let album: Album = service.signed_get("/album/get", ¶ms).await?;§Errors
This function will return an error if:
- The HTTP request fails (network issues)
- The API returns an error response (status: “error”)
- The response cannot be parsed as the expected type
T - The response cannot be deserialized from JSON
Source§impl QobuzApiService
impl QobuzApiService
Sourcepub async fn new() -> Result<Self, QobuzApiError>
pub async fn new() -> Result<Self, QobuzApiError>
Initializes a new instance of the QobuzApiService using cached credentials from .env file or by dynamically retrieving them from the Qobuz Web Player if not available.
This method attempts to initialize the service in the following order:
- Try to use cached credentials from the .env file
- If cached credentials fail, fetch new ones from the web player
§Errors
Returns an error if:
- Failed to fetch credentials from the web player
- Failed to create an HTTP client
- Both cached and fetched credentials are invalid
§Examples
use qobuz_api_rust::QobuzApiService;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let service = QobuzApiService::new().await?;
Ok(())
}Sourcepub async fn with_credentials(
app_id: Option<String>,
app_secret: Option<String>,
) -> Result<Self, QobuzApiError>
pub async fn with_credentials( app_id: Option<String>, app_secret: Option<String>, ) -> Result<Self, QobuzApiError>
Initializes a new instance of the QobuzApiService with custom app_id and app_secret.
This method allows you to provide your own application credentials instead of automatically fetching them from the web player.
§Arguments
app_id- Optional application ID. If None, initialization will fail.app_secret- Optional application secret. If None, initialization will fail.
§Errors
Returns an error if:
- Either app_id or app_secret is None
- Failed to create an HTTP client with the provided credentials
§Examples
use qobuz_api_rust::QobuzApiService;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let service = QobuzApiService::with_credentials(
Some("your_app_id".to_string()),
Some("your_app_secret".to_string())
).await?;
Ok(())
}Sourcepub fn set_user_auth_token(&mut self, token: String)
pub fn set_user_auth_token(&mut self, token: String)
Sets the user authentication token for the service
This method is used to set the user authentication token after successful user authentication. The token will be used for subsequent API requests that require user context.
§Arguments
token- The user authentication token to set
§Examples
use qobuz_api_rust::QobuzApiService;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut service = QobuzApiService::new().await?;
service.set_user_auth_token("your_auth_token".to_string());
Ok(())
}Sourcepub async fn authenticate_with_env(&mut self) -> Result<Login, QobuzApiError>
pub async fn authenticate_with_env(&mut self) -> Result<Login, QobuzApiError>
Attempts to authenticate using environment variables.
Checks for QOBUZ_USER_ID and QOBUZ_USER_AUTH_TOKEN first, then falls back to QOBUZ_EMAIL and QOBUZ_PASSWORD, then to QOBUZ_USERNAME and QOBUZ_PASSWORD. Both email and username are treated as identifiers for authentication.
§Returns
Ok(Login)- If authentication was successfulErr(QobuzApiError)- If authentication failed or no valid credentials were found
§Environment Variables
This method looks for the following environment variables:
QOBUZ_USER_IDandQOBUZ_USER_AUTH_TOKENfor token-based authenticationQOBUZ_EMAILandQOBUZ_PASSWORDfor email/password authenticationQOBUZ_USERNAMEandQOBUZ_PASSWORDfor username/password authentication
§Errors
Returns an error if no valid credentials are found in environment variables or if authentication fails with the provided credentials.
§Examples
use qobuz_api_rust::QobuzApiService;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut service = QobuzApiService::new().await?;
let login_result = service.authenticate_with_env().await?;
Ok(())
}Sourcepub async fn refresh_app_credentials(&self) -> Result<Self, QobuzApiError>
pub async fn refresh_app_credentials(&self) -> Result<Self, QobuzApiError>
Refreshes the app credentials by fetching new ones from the web player and updating the .env file
This method creates a new instance of the service with fresh credentials obtained from the Qobuz web player, while preserving the current user authentication token.
§Errors
Returns an error if:
- Failed to fetch new credentials from the web player
- Failed to create a new service instance with the fetched credentials
§Examples
use qobuz_api_rust::QobuzApiService;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let service = QobuzApiService::new().await?;
let updated_service = service.refresh_app_credentials().await?;
Ok(())
}