lastfm-client
A modern, async Rust library for fetching and analyzing Last.fm user data with ease.
Version 2.0 introduces a brand new builder-pattern API with retry logic, rate limiting, and improved ergonomics, while maintaining 100% backward compatibility with the 1.x API.
🚀 New in v2.0
- 🎯 Specialized API Clients:
RecentTracksClient,LovedTracksClient,TopTracksClient - 🔧 Builder Pattern: Fluent, discoverable API design
- 📊 Built-in Analytics: Track analysis and statistics methods
- 💾 File Operations: Built-in save and export functionality
- 🎵 Currently Playing: Real-time track detection
- ⚡ Performance: Optimized HTTP client with retry logic
- 🔄 Backward Compatible: V1.x API still works (with deprecation warnings)
Installation
Add this to your Cargo.toml:
[]
= "2.0"
Features
V2.0 API (New!)
- Builder Pattern: Fluent, discoverable API design
- Automatic Retries: Configurable retry logic with exponential or linear backoff
- Rate Limiting: Prevent API abuse with built-in rate limiting
- Enhanced Error Handling: Rich error types with retry hints and context
- Testable: HTTP abstraction layer for easy mocking
- Type Safe: Leverages Rust's type system for compile-time guarantees
Data Fetching
- Async API Integration: Modern asynchronous Last.fm API communication
- Flexible Track Fetching: Get recent tracks, loved tracks, and top tracks with configurable limits
- Advanced Filtering: Time-based filtering (
from/totimestamps) and period-based filtering for top tracks - Extended Data Support: Fetch extended track information with additional artist details
- Efficient Pagination: Smart handling of Last.fm's pagination system with chunked concurrent requests
Analytics
- Comprehensive Statistics:
- Total play counts
- Artist-level analytics
- Track-level analytics
- Most played artists/tracks
- Play count thresholds
- Custom Analysis: Extensible analysis framework with the
TrackAnalyzabletrait
Data Export
- Multiple Formats: Export data in JSON and CSV formats
- Timestamp-based Filenames: Automatic file naming with timestamps
- Organized Storage: Structured data directory management
Error Handling
- Robust Error Types: Custom error handling for API and file operations
- Graceful Failure Recovery: Proper handling of API and parsing errors
Configuration
Create a .env file in your project root:
LAST_FM_API_KEY=your_api_key_here
Usage
Choose between the v2.0 API (recommended for new projects) or the v1.x API (fully supported for existing projects).
V2.0 API (Recommended)
Quick Start
use LastFmClient;
async
Alternative: Using Builder Pattern
use LastFmClient;
async
Advanced Configuration
use LastFmClient;
use Duration;
let client = builder
.api_key
.user_agent
.timeout
.max_concurrent_requests
.retry_attempts
.rate_limit // 10 requests per second
.build_client?;
Fetching Recent Tracks
// Limited tracks
let tracks = client
.recent_tracks
.limit
.fetch
.await?;
// All available tracks
let all_tracks = client
.recent_tracks
.unlimited
.fetch
.await?;
// Tracks from specific date
let since_timestamp = 1704067200; // Jan 1, 2024
let recent = client
.recent_tracks
.since
.fetch
.await?;
// Tracks between two dates
let from = 1704067200; // Jan 1, 2024
let to = 1706745600; // Feb 1, 2024
let tracks = client
.recent_tracks
.between
.fetch
.await?;
// Extended track information (includes full artist details)
let extended_tracks = client
.recent_tracks
.limit
.extended
.fetch_extended
.await?;
// Check if user is currently playing
let currently_playing = client
.recent_tracks
.check_currently_playing
.await?;
// Analyze tracks and get statistics
let stats = client
.recent_tracks
.limit
.analyze
.await?;
// Fetch and save to file
let filename = client
.recent_tracks
.limit
.fetch_and_save
.await?;
Fetching Loved Tracks
// Limited loved tracks
let loved_tracks = client
.loved_tracks
.limit
.fetch
.await?;
// All loved tracks
let all_loved = client
.loved_tracks
.unlimited
.fetch
.await?;
// Analyze loved tracks
let stats = client
.loved_tracks
.analyze
.await?;
// Fetch and save loved tracks
let filename = client
.loved_tracks
.fetch_and_save
.await?;
Fetching Top Tracks
use Period;
// Top tracks with period filter
let top_tracks = client
.top_tracks
.limit
.period
.fetch
.await?;
// All-time top tracks
let all_time_top = client
.top_tracks
.unlimited
.period
.fetch
.await?;
// Fetch and save top tracks
let filename = client
.top_tracks
.limit
.period
.fetch_and_save
.await?;
Error Handling with Retry Hints
use LastFmError;
match client.recent_tracks.limit.fetch.await
Friendly error messages (Display vs Debug)
If you see output like MissingEnvVar("LAST_FM_API_KEY"), the error is being printed with Debug formatting ({:?}) somewhere. This library implements friendly Display messages (via #[error("...")]), so prefer Display ({}) when printing errors.
Use an explicit main error handler to guarantee Display formatting:
use dotenv;
use LastFmClient;
async
async
Tips:
- Use
eprintln!("{}", err)oreprintln!("Error: {err}")(Display), avoid{:?}/{:#?}(Debug). - If you keep
fn main() -> Result<…>, your runtime may show Debug output on failure. The explicit handler above guarantees Display. - This applies to all errors from this library, including configuration errors like missing
LAST_FM_API_KEY.
V1.x API (Legacy, Deprecated but Fully Supported)
⚠️ Deprecation Notice: The V1.x API methods are now deprecated and will show deprecation warnings when used. We recommend migrating to the new V2.0 API clients for better performance, features, and maintainability. The V1.x API will continue to work indefinitely for backward compatibility.
Basic Example
use ;
async
Fetching & Saving Example
use FileFormat;
use ;
use dotenv;
async
This example shows how to:
- Load environment variables (including your Last.fm API key)
- Create a handler for a specific Last.fm user
- Fetch all scrobbled tracks (using
TrackLimit::Unlimited) - Save them to a JSON file with a custom name prefix
- Handle potential errors during the process
Analytics Example
use ;
// Save and analyze tracks
let filename = handler
.get_and_save_recent_tracks
.await?;
let stats = ?;
print_analysis;
Advanced Fetching with Options
The library provides comprehensive *_with_options methods that expose all available Last.fm API parameters:
Recent Tracks with Options
use ;
let handler = new.unwrap;
// Get last 50 tracks (basic usage)
let tracks = handler
.get_user_recent_tracks_with_options
.await?;
// Get tracks from the last week
let one_week_ago = .timestamp;
let tracks = handler
.get_user_recent_tracks_with_options
.await?;
// Get tracks between two dates with extended info
let tracks = handler
.get_user_recent_tracks_with_options
.await?;
// Get extended track information (alternative method)
let extended_tracks = handler
.get_user_recent_tracks_extended
.await?;
Recent Tracks Between Dates
Convenience methods for fetching all tracks within a specific time range:
use LastFMHandler;
use ;
let handler = new.unwrap;
// Get all tracks from January 2024
let start = Utc.with_ymd_and_hms.unwrap.timestamp;
let end = Utc.with_ymd_and_hms.unwrap.timestamp;
let tracks = handler
.get_user_recent_tracks_between
.await?;
// Get all tracks from last week with extended info
let one_week_ago = .timestamp;
let now = now.timestamp;
let tracks = handler
.get_user_recent_tracks_between
.await?;
// Get all tracks between dates with extended information
let tracks = handler
.get_user_recent_tracks_between_extended
.await?;
Top Tracks with Options
use ;
let handler = new.unwrap;
// Get all-time top 50 tracks
let tracks = handler
.get_user_top_tracks_with_options
.await?;
// Get top tracks from the last week
let tracks = handler
.get_user_top_tracks_with_options
.await?;
// Get top 100 tracks from the last 3 months
let tracks = handler
.get_user_top_tracks_with_options
.await?;
Loved Tracks with Options
use ;
let handler = new.unwrap;
// Get all loved tracks
let tracks = handler
.get_user_loved_tracks_with_options
.await?;
// Get first 100 loved tracks
let tracks = handler
.get_user_loved_tracks_with_options
.await?;
Available Period Options
When using get_user_top_tracks_with_options, you can filter by these time periods:
Period::Overall- All time (default if None)Period::Week- Last 7 daysPeriod::Month- Last monthPeriod::ThreeMonth- Last 3 monthsPeriod::SixMonth- Last 6 monthsPeriod::TwelveMonth- Last 12 months
Migration Guide (v1.x → v2.0)
The v2.0 API is completely optional and backward compatible. You can migrate gradually or continue using the v1.x API indefinitely (though it will show deprecation warnings).
Before (v1.x)
// Multiple methods for different use cases
let handler = new?;
// Limited tracks
handler.get_user_recent_tracks?;
// With date filtering
handler.get_user_recent_tracks_with_options?;
// Extended information
handler.get_user_recent_tracks_extended?;
// Between dates
handler.get_user_recent_tracks_between?;
// Top tracks
handler.get_user_top_tracks?;
// Loved tracks
handler.get_user_loved_tracks?;
After (v2.0)
use LastFmClient;
// Create client with defaults (loads API key from environment)
let client = new?;
// Limited tracks
client.recent_tracks.limit.fetch.await?;
// With date filtering
client.recent_tracks.limit.between.fetch.await?;
// Extended information
client.recent_tracks.limit.fetch_extended.await?;
// Between dates
client.recent_tracks.between.fetch.await?;
// Top tracks
client.top_tracks.limit.period.fetch.await?;
// Loved tracks
client.loved_tracks.limit.fetch.await?;
Key Benefits of v2.0
- Simpler API: One method instead of 6+ variants
- Discoverable: Builder pattern makes options obvious
- Automatic Retries: Built-in exponential backoff
- Rate Limiting: Prevent API throttling
- Better Errors: Rich error types with retry hints
- Testable: Mock HTTP client for testing
API Methods Reference
V2.0 API
Client Creation
use LastFmClient;
// Simple: with defaults (loads API key from LAST_FM_API_KEY env var)
let client = new?;
// With custom configuration
let client = builder
.api_key
.retry_attempts
.rate_limit
.build_client?;
Recent Tracks
client.recent_tracks
.limit // Limit number of tracks
.unlimited // Fetch all available tracks
.since // Tracks since timestamp
.between // Tracks between two timestamps
.extended // Include extended info
.fetch // Execute and get Vec<RecentTrack>
.fetch_extended // Execute and get Vec<RecentTrackExtended>
.check_currently_playing // Check if currently playing
.analyze // Analyze tracks and get statistics
.analyze_and_print // Analyze and print statistics
.fetch_and_save // Fetch and save to file
.fetch_extended_and_save // Fetch extended and save
Loved Tracks
client.loved_tracks
.limit // Limit number of tracks
.unlimited // Fetch all available tracks
.fetch // Execute and get Vec<LovedTrack>
.analyze // Analyze tracks and get statistics
.analyze_and_print // Analyze and print statistics
.fetch_and_save // Fetch and save to file
Top Tracks
client.top_tracks
.limit // Limit number of tracks
.unlimited // Fetch all available tracks
.period // Time period filter
.fetch // Execute and get Vec<TopTrack>
.fetch_and_save // Fetch and save to file
V1.x API (Deprecated)
⚠️ All V1.x methods are deprecated and will show deprecation warnings. Use the V2.0 API clients instead.
Recent Tracks Methods
| Method | Parameters | Returns | Description | Status |
|---|---|---|---|---|
get_user_recent_tracks |
limit |
Vec<RecentTrack> |
Simple method to fetch recent tracks | ⚠️ Deprecated |
get_user_recent_tracks_with_options |
limit, from, to, extended |
Vec<RecentTrack> |
Full control over all API parameters | ⚠️ Deprecated |
get_user_recent_tracks_extended |
limit, from, to |
Vec<RecentTrackExtended> |
Fetch recent tracks with extended info | ⚠️ Deprecated |
get_user_recent_tracks_since |
from, to, limit |
Vec<RecentTrack> |
Fetch tracks since a timestamp | ⚠️ Deprecated |
get_user_recent_tracks_between |
from, to, extended |
Vec<RecentTrack> |
Fetch all tracks between two dates | ⚠️ Deprecated |
get_user_recent_tracks_between_extended |
from, to |
Vec<RecentTrackExtended> |
Fetch all tracks between dates with extended info | ⚠️ Deprecated |
Top Tracks Methods
| Method | Parameters | Returns | Description | Status |
|---|---|---|---|---|
get_user_top_tracks |
limit, period |
Vec<TopTrack> |
Simple method to fetch top tracks | ⚠️ Deprecated |
get_user_top_tracks_with_options |
limit, period |
Vec<TopTrack> |
Full control over all API parameters | ⚠️ Deprecated |
Loved Tracks Methods
| Method | Parameters | Returns | Description | Status |
|---|---|---|---|---|
get_user_loved_tracks |
limit |
Vec<LovedTrack> |
Simple method to fetch loved tracks | ⚠️ Deprecated |
get_user_loved_tracks_with_options |
limit |
Vec<LovedTrack> |
Full control over all API parameters | ⚠️ Deprecated |
get_user_loved_tracks_since |
timestamp, limit |
Vec<LovedTrack> |
Fetch loved tracks since a timestamp | ⚠️ Deprecated |
Helper Methods
| Method | Parameters | Returns | Description |
|---|---|---|---|
get_and_save_recent_tracks |
limit, format, filename_prefix |
Result<String> |
Fetch and save recent tracks to file |
get_and_save_loved_tracks |
limit, format |
Result<String> |
Fetch and save loved tracks to file |
export_recent_play_counts |
limit |
Result<String> |
Export play counts for recent tracks |
update_recent_play_counts |
limit, file_path |
Result<String> |
Update play counts in existing file |
is_currently_playing |
- | Result<Option<RecentTrack>> |
Check if user is currently playing |
update_currently_listening |
file_path |
Result<Option<RecentTrack>> |
Update currently listening file |
Parameter Types
limit:impl Into<TrackLimit>- UseSome(n)for limited tracks,NoneorTrackLimit::Unlimitedfor allfrom/to:Option<i64>- Unix timestamps in secondsextended:bool- Whether to fetch extended track informationperiod:Option<Period>- Time period filter (Week, Month, ThreeMonth, etc.)format:FileFormat-FileFormat::JsonorFileFormat::Csv
Testing
Run the test suite:
The v2.0 API includes extensive test coverage with mock HTTP clients for reliable testing.
Advanced Features (v2.0)
Retry Logic
Configure automatic retries with exponential or linear backoff:
use ;
use Duration;
// Exponential backoff: 100ms → 200ms → 400ms → 800ms
let client = builder
.api_key
.retry_attempts
.build_client?;
// Custom retry policy
let policy = exponential
.with_base_delay
.with_max_delay;
Rate Limiting
Prevent API throttling with sliding window rate limiting:
use Duration;
let client = builder
.api_key
.rate_limit // 10 requests per second
.build_client?;
Testing with Mocks
Use mock HTTP clients for testing:
use MockClient;
use HashMap;
let mut responses = new;
responses.insert;
let mock_client = new;
// Use mock_client in your tests
Architecture (v2.0)
The v2.0 API is built with a modular, testable architecture:
src/
├── client/
│ ├── client.rs # Main LastFmClient entry point
│ ├── http.rs # HTTP abstraction (trait + implementations)
│ ├── retry.rs # Retry logic with backoff strategies
│ └── rate_limiter.rs # Rate limiting with sliding window
├── api/
│ └── recent_tracks.rs # RecentTracksClient with builder pattern
├── types/
│ ├── tracks.rs # Track type definitions
│ └── period.rs # Period and TrackLimit enums
├── config.rs # Configuration with builder
└── error.rs # Rich error types with retry hints
Key Design Principles
- Trait-based HTTP abstraction: Easy to test with mocks
- Builder patterns: Fluent, discoverable APIs
- Type safety: Leverages Rust's type system
- Zero-cost abstractions: No runtime overhead
- Backward compatibility: v1.x API remains fully functional
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
Built with Rust and powered by the Last.fm API.