calliostro / lastfm-client
Ultra-lightweight Last.fm API client for PHP 8.1+ with modern Guzzle-based implementation - Only two classes, service descriptions, zero bloats
Requires
- php: ^8.1
- guzzlehttp/guzzle: ^6.5 || ^7.0
Requires (Dev)
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.0
- squizlabs/php_codesniffer: ^3.7
README
๐ ONLY 2 CLASSES! The most lightweight Last.fm API client for PHP. Zero bloats, maximum performance.
An ultra-minimalist Last.fm API client that proves you don't need 20+ classes to build a great API client. Built with modern PHP 8.1+ features, service descriptions, and powered by Guzzle.
๐ฆ Installation
composer require calliostro/lastfm-client
Important: You need to register your application at Last.fm to get your API key and secret. All API calls require a valid API key.
Symfony Users: For easier integration, there's also a Symfony Bundle available (currently supports only pre-configured sessions, but sufficient if you don't need dynamic authentication or scrobbling).
๐ Quick Start
Basic Usage
<?php require __DIR__ . '/vendor/autoload.php'; use Calliostro\LastFm\ClientFactory; // Basic client for read-only operations $lastfm = ClientFactory::create('your-api-key', 'your-secret'); // Fetch track information $track = $lastfm->trackGetInfo([ 'artist' => 'Coldplay', 'track' => 'Viva La Vida' ]); $artist = $lastfm->artistGetInfo([ 'artist' => 'Ed Sheeran' ]); echo "Track: " . $track['track']['name'] . "\n"; echo "Artist: " . $artist['artist']['name'] . "\n";
Scrobbling and Now Playing
// Authenticated client for write operations (scrobbling, loving tracks) $lastfm = ClientFactory::createWithAuth( 'your-api-key', 'your-secret', 'session-key' ); $lastfm->trackUpdateNowPlaying([ 'artist' => 'Linkin Park', 'track' => 'In the End' ]); $lastfm->trackScrobble([ 'artist' => 'Linkin Park', 'track' => 'In the End', 'timestamp' => time() ]); // Mark tracks as loved/unloved $lastfm->trackLove(['artist' => 'Linkin Park', 'track' => 'In the End']); $lastfm->trackUnlove(['artist' => 'Eminem', 'track' => 'Lose Yourself']);
Discovery and Charts
// Find similar artists and top tracks $similar = $lastfm->artistGetSimilar(['artist' => 'Imagine Dragons']); $topTracks = $lastfm->artistGetTopTracks(['artist' => 'Adele']); // Fetch user listening history $recentTracks = $lastfm->userGetRecentTracks(['user' => 'username']); $topArtists = $lastfm->chartGetTopArtists(['limit' => 10]); // Explore music by genre/tag $rockTracks = $lastfm->tagGetTopTracks(['tag' => 'rock']);
โจ Key Features
- Ultra-Lightweight โ Only 2 classes, ~130 lines of logic + service descriptions
- Complete API Coverage โ All 60+ Last.fm API endpoints supported
- Direct API Calls โ
$client->trackGetInfo()
maps totrack.getInfo
, no abstractions - Type Safe + IDE Support โ Full PHP 8.1+ types, PHPStan Level 8, method autocomplete
- Future-Ready โ PHP 8.5 compatible (beta/dev testing)
- Pure Guzzle โ Modern HTTP client, no custom transport layers
- Well Tested โ 100% test coverage, PSR-12 compliant
- Secure Authentication โ Full OAuth and API key support
๐ต All Last.fm API Methods as Direct Calls
- Track Methods โ trackGetInfo(), trackScrobble(), trackUpdateNowPlaying(), trackLove(), trackUnlove()
- Artist Methods โ artistGetInfo(), artistGetTopTracks(), artistGetSimilar(), artistSearch()
- User Methods โ userGetInfo(), userGetRecentTracks(), userGetLovedTracks(), userGetTopArtists()
- Chart Methods โ chartGetTopArtists(), chartGetTopTracks()
- Album Methods โ albumGetInfo(), albumSearch()
- Tag Methods โ tagGetInfo(), tagGetTopTracks(), tagGetTopTags()
- Auth Methods โ authGetToken(), authGetSession()
- Geo Methods โ geoGetTopArtists(), geoGetTopTracks()
- Library Methods โ libraryGetArtists()
All 60+ Last.fm API endpoints are supported with clean documentation โ see Last.fm API Documentation for complete method reference
๐ Requirements
- php ^8.1
- guzzlehttp/guzzle ^6.5 || ^7.0
๐ง Advanced Configuration
Option 1: Simple Configuration (Recommended)
For basic customizations like timeout or User-Agent, use the ClientFactory:
use Calliostro\LastFm\ClientFactory; $lastfm = ClientFactory::create('your-api-key', 'your-secret', [ 'timeout' => 30, 'headers' => [ 'User-Agent' => 'MyApp/1.0 (+https://myapp.com)', ] ]);
Option 2: Advanced Guzzle Configuration
For advanced HTTP client features (middleware, interceptors, etc.), create your own Guzzle client:
use GuzzleHttp\Client; use Calliostro\LastFm\LastFmApiClient; $httpClient = new Client([ 'timeout' => 30, 'connect_timeout' => 10, 'headers' => [ 'User-Agent' => 'MyApp/1.0 (+https://myapp.com)', ] ]); // Direct usage $lastfm = new LastFmApiClient('your-api-key', 'your-secret', $httpClient); // Or via ClientFactory $lastfm = ClientFactory::create('your-api-key', 'your-secret', $httpClient);
๐ก Note: By default, the client uses
LastFmClient/1.0 (+https://github.com/calliostro/lastfm-client)
as User-Agent. You can override this by setting custom headers as shown above.
๐ Authentication
Last.fm supports different authentication flows:
Web Application Authentication (Recommended)
For web applications, use the simplified flow where Last.fm generates the token automatically:
๐ก Quick reminder: Make sure you've configured the callback URL (e.g.,
https://yourapp.com/lastfm/callback
) in your Last.fm application settings, otherwise the redirect won't work!
// Step 1: Redirect the user to Last.fm $callbackUrl = 'https://yourapp.com/lastfm/callback'; $authUrl = "https://www.last.fm/api/auth/?api_key=your-api-key&cb=" . urlencode($callbackUrl); // Step 2: User authorizes at Last.fm (redirect to $authUrl) // Step 3: Last.fm redirects back with token parameter // Step 4: In your callback, get a session key with the received token $token = $_GET['token']; // Token from Last.fm callback $session = $lastfm->authGetSession(['token' => $token]); $sessionKey = $session['session']['key']; // Step 5: Use an authenticated client $authenticatedClient = ClientFactory::createWithAuth('your-api-key', 'your-secret', $sessionKey);
Desktop Application Authentication
For desktop/mobile applications, you may need to generate a token first:
// Step 1: Get a token (for desktop apps) $token = $lastfm->authGetToken(); $authUrl = "https://www.last.fm/api/auth/?api_key=your-api-key&token=" . $token['token']; // Step 2: User authorizes at $authUrl // Step 3: Get a session key $session = $lastfm->authGetSession(['token' => $token['token']]); $sessionKey = $session['session']['key'];
Complete Web Application Example
<?php // authorize.php $apiKey = 'your-api-key'; $callbackUrl = 'https://yourapp.com/callback.php'; $authUrl = "https://www.last.fm/api/auth/?api_key={$apiKey}&cb=" . urlencode($callbackUrl); header("Location: {$authUrl}"); exit;
<?php // callback.php require __DIR__ . '/vendor/autoload.php'; use Calliostro\LastFm\ClientFactory; $apiKey = 'your-api-key'; $secret = 'your-secret'; $token = $_GET['token']; $lastfm = ClientFactory::create($apiKey, $secret); $session = $lastfm->authGetSession(['token' => $token]); $sessionKey = $session['session']['key']; $username = $session['session']['name']; // Store $sessionKey and $username for future use (database, session, cache, etc.) $lastfm = ClientFactory::createWithAuth($apiKey, $secret, $sessionKey); $lastfm->trackScrobble([ 'artist' => 'Adele', 'track' => 'Rolling in the Deep', 'timestamp' => time() ]);
๐งช Testing
Run the test suite:
composer test
Run static analysis:
composer analyse
Check code style:
composer cs
๐ API Documentation Reference
For complete API documentation including all available parameters, visit the Last.fm API Documentation.
Popular Methods
Track Methods
trackGetInfo($params)
โ Get track informationtrackSearch($params)
โ Search for trackstrackScrobble($params)
โ Scrobble a track (auth required)trackUpdateNowPlaying($params)
โ Update now playing (auth required)trackLove($params)
โ Love a track (auth required)trackUnlove($params)
โ Remove love from track (auth required)
Artist Methods
artistGetInfo($params)
โ Get artist informationartistGetTopTracks($params)
โ Get artist's top tracksartistGetSimilar($params)
โ Get similar artistsartistSearch($params)
โ Search for artists
User Methods
userGetInfo($params)
โ Get user profile informationuserGetRecentTracks($params)
โ Get user's recent tracksuserGetLovedTracks($params)
โ Get user's loved tracksuserGetTopArtists($params)
โ Get user's top artists
๐ค Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Please ensure your code follows PSR-12 standards and includes tests.
๐ License
This project is licensed under the MIT License โ see the LICENSE file for details.
๐ Acknowledgments
- Last.fm for providing the excellent music data API
- Guzzle for the robust HTTP client
- The PHP community for continuous inspiration
โญ Star this repo if you find it useful! It helps others discover this lightweight solution.