Search by

calliostro / lastfm-client

calliostro

Lightweight Last.fm API client for PHP 8.1+ with built-in resilience and minimal dependencies.

Package info

github.com/calliostro/lastfm-client

pkg:composer/calliostro/lastfm-client

Statistics

Installs: 1 196

Dependents: 1

Suggesters: 0

Stars: 1

Open Issues: 0

v2.1.0 2026-09-18 19:21 UTC

This package is auto-updated.

Last update: 2026-09-18 19:23:45 UTC


README

Package Version Total Downloads License PHP Version Guzzle CI Code Coverage PHPStan Level Code Style

A lightweight, modern PHP client for the Last.fm API, supporting all 55+ endpoints with built-in resilience, session and mobile authentication, and PHP 8.1+ compatibility.

๐Ÿ“ฆ Installation

composer require calliostro/lastfm-client

Do You Need to Register?

For ALL API calls: Registration required

  • Register your application at Last.fm to get credentials
  • API Key needed for: ALL methods (artist info, search, charts, etc.)

For write operations: Session authentication required

  • Session Key needed for: scrobbling, loving tracks, personal collections, tagging

๐Ÿš€ Quick Start

Read-Only Data (API key required for all methods)

use Calliostro\LastFm\LastFmClientFactory;

$lastfm = LastFmClientFactory::createWithApiKey('your-api-key', 'your-secret');

$artist = $lastfm->getArtistInfo('Billie Eilish');          // Get artist info
$release = $lastfm->getAlbumInfo('The Weeknd', 'Dawn FM');  // Album info  
$charts = $lastfm->getTopArtistsChart();                    // Global charts

Search with API Credentials

use Calliostro\LastFm\LastFmClientFactory;

$lastfm = LastFmClientFactory::createWithApiKey('your-api-key', 'your-secret');

// Positional parameters (traditional)
$results = $lastfm->searchArtists('Taylor Swift', 20);
$tracks = $lastfm->searchTracks('Anti-Hero', 'Taylor Swift');

// Named parameters (PHP 8.0+, recommended for clarity)
$results = $lastfm->searchArtists(artist: 'Taylor Swift', limit: 20);
$tracks = $lastfm->searchTracks(track: 'Anti-Hero', artist: 'Taylor Swift');

Your Scrobbles (Session Authentication)

use Calliostro\LastFm\LastFmClientFactory;

$lastfm = LastFmClientFactory::createWithSession('your-api-key', 'your-secret', 'your-session-key');

$collection = $lastfm->getUserRecentTracks('your-username');
$loved = $lastfm->getUserLovedTracks('your-username');

// Scrobble and love tracks with named parameters
$lastfm->scrobbleTrack(
    artist: 'Bad Bunny',
    track: 'Un Verano Sin Ti',
    timestamp: time()
);

Multi-User Apps (Mobile Auth)

use Calliostro\LastFm\LastFmClientFactory;

$lastfm = LastFmClientFactory::createWithMobileAuth('your-api-key', 'your-secret', 'your-username', 'your-password');

$identity = $lastfm->getUserInfo();

โœจ Key Features

  • Simple Setup โ€“ Works immediately with an API key, easy authentication for user actions.
  • Complete API Coverage โ€“ All 55+ Last.fm API endpoints supported.
  • Built-in Resilience โ€“ Automatic retries on 503 Service Temporarily Unavailable, 429 Too Many Requests, and connection errors with exponential backoff.
  • Clean Parameter API โ€“ Natural method calls: $client->getArtistInfo('Billie Eilish') with PHP 8 named parameter support.
  • Lightweight Focus โ€“ Minimal codebase with only essential dependencies (guzzlehttp/guzzle: ^7.0 || ^8.0).
  • Modern PHP Comfort โ€“ Full IDE auto-completion, type safety, and PHPStan Level 8 clean.
  • Authentication Support โ€“ Full API key, Session Key, and Mobile Authentication flows supported.
  • Well Tested โ€“ Comprehensive test suite, PSR-12 compliant.
  • Future-Ready โ€“ PHP 8.1โ€“8.6 compatible.
  • Pure Guzzle โ€“ Standard Guzzle 7/8 HTTP client without proprietary transport wrappers.

๐ŸŽต All Last.fm API Methods as Direct Calls

  • Album Methods โ€“ getAlbumInfo(), searchAlbums(), getAlbumTopTags(), addAlbumTags(), removeAlbumTag(), getAlbumTags()
  • Artist Methods โ€“ getArtistInfo(), getArtistTopTracks(), getSimilarArtists(), searchArtists(), getArtistTopAlbums(), getArtistCorrection(), addArtistTags(), removeArtistTag(), getArtistTags(), getArtistTopTags()
  • Track Methods โ€“ getTrackInfo(), searchTracks(), getSimilarTracks(), scrobbleTrack(), updateNowPlaying(), loveTrack(), unloveTrack(), getTrackCorrection(), addTrackTags(), removeTrackTag(), getTrackTags(), getTrackTopTags()
  • User Methods โ€“ getUserInfo(), getUserRecentTracks(), getUserLovedTracks(), getUserTopArtists(), getUserTopTracks(), getUserTopAlbums(), getUserFriends(), getUserArtistTracks(), getUserPersonalTags(), getUserTopTags()
  • Chart Methods โ€“ getTopArtistsChart(), getTopTracksChart(), getTopTagsChart()
  • Geography Methods โ€“ getTopArtistsByCountry(), getTopTracksByCountry()
  • Tag Methods โ€“ getTagInfo(), getSimilarTags(), getTagTopArtists(), getTagTopTracks(), getTagTopAlbums(), getTopTags(), getTagWeeklyChartList()
  • Authentication Methods โ€“ getToken(), getSession(), getMobileSession()
  • Library Methods โ€“ getLibraryArtists()
  • User Charts โ€“ getUserWeeklyArtistChart(), getUserWeeklyAlbumChart(), getUserWeeklyTrackChart(), getUserWeeklyChartList()

All Last.fm API endpoints are supported โ€” see the Last.fm API Documentation for complete parameter and response details.

Note

Some endpoints require session authentication (e.g., scrobbling, loved tracks, tagging) or specific permissions.

๐Ÿ“‹ Requirements

  • PHP ^8.1
  • guzzlehttp/guzzle ^7.0 || ^8.0

โš™๏ธ Configuration

Rate Limiting & Retries

Last.fm enforces rate limits and may occasionally return 503 Service Temporarily Unavailable or 429 Too Many Requests. By default (auto_retry => true, max_retries => 3), the client automatically retries temporary 503, 429, and connection failures using exponential backoff while respecting any Retry-After header.

You can customize or disable retries:

use Calliostro\LastFm\LastFmClientFactory;

// Custom retry count
$lastfm = LastFmClientFactory::createWithApiKey('your-api-key', 'your-secret', [
    'auto_retry' => true,   // Automatically wait and retry on 429/503 (default: true)
    'max_retries' => 5,     // Maximum number of retry attempts (default: 3)
]);

// Disable automatic retries (e.g. in tests or to handle exceptions immediately)
$lastfm = LastFmClientFactory::createWithApiKey('your-api-key', 'your-secret', [
    'auto_retry' => false,
]);

Advanced Configuration (Custom Guzzle handler, timeouts, headers)

use Calliostro\LastFm\LastFmClientFactory;

$lastfm = LastFmClientFactory::createWithApiKey('your-api-key', 'your-secret', [
    'timeout' => 30,
    'proxy' => 'http://proxy.example.com:8080',
    'verify' => true,
    'auto_retry' => true,
    'max_retries' => 3,
    'headers' => [
        'User-Agent' => 'MyApp/1.0 (+https://myapp.com)',
    ],
]);

Note

By default, the client uses LastFmClient/2.1.0 +https://github.com/calliostro/lastfm-client as its User-Agent. You can override this by providing custom headers in the configuration array.

๐Ÿ” Authentication

Get credentials at Last.fm API Registration.

Quick Reference

What you want to do Method What you need
Get artist/track/chart info createWithApiKey() API key + secret
Search the database createWithApiKey() API key + secret
Scrobble tracks createWithSession() API key + secret + session
Access user collections createWithSession() API key + secret + session
Mobile app createWithMobileAuth() API key + secret + user/pass

Complete Session Flow Example

Step 1: authorize.php โ€“ Redirect user to Last.fm

<?php
// authorize.php

use Calliostro\LastFm\AuthHelper;

$apiKey = 'your-api-key';
$secret = 'your-secret';
$callbackUrl = 'https://yourapp.com/callback.php';

$auth = new AuthHelper($apiKey, $secret);

// For web apps, you can skip token generation and redirect directly:
$authUrl = "https://www.last.fm/api/auth/?api_key={$apiKey}&cb=" . urlencode($callbackUrl);

// For desktop apps, generate token first:
// $tokenData = $auth->getToken();
// $authUrl = $auth->getAuthorizationUrl($tokenData['token']);

header("Location: {$authUrl}");
exit;

Step 2: callback.php โ€“ Handle Last.fm callback

<?php
// callback.php

require __DIR__ . '/vendor/autoload.php';

use Calliostro\LastFm\{AuthHelper, LastFmClientFactory};

$apiKey = 'your-api-key';
$secret = 'your-secret';
$token = $_GET['token'];

$auth = new AuthHelper($apiKey, $secret);
$sessionData = $auth->getSession($token);

$sessionKey = $sessionData['session']['key'];
$username = $sessionData['session']['name'];

// Store tokens for future use
$_SESSION['lastfm_session_key'] = $sessionKey;
$_SESSION['lastfm_username'] = $username;

$lastfm = LastFmClientFactory::createWithSession($apiKey, $secret, $sessionKey);
$user = $lastfm->getUserInfo();
echo "Hello " . $user['user']['name'];

๐Ÿงช Development & Testing Guide

See DEVELOPMENT.md for detailed setup instructions, test suite commands, static analysis, and contribution guidelines.

๐Ÿค Contributing

Contributions are welcome! Please ensure all tests pass and coding standards are maintained:

composer cs-fix
composer analyse
composer test

๐Ÿ“„ License

MIT License โ€“ see LICENSE file for details.

โš–๏ธ Disclaimer

Last.fm is a registered trademark of CBS Interactive (or Paramount Global). This project is an independent, unofficial open-source library and is not affiliated with, endorsed by, or sponsored by Last.fm.

๐Ÿ™ Acknowledgments