calliostro / spotify-bundle
Lightweight Symfony bundle for the Spotify Web API with autowiring, resilience, and rate limiting support.
Package info
github.com/calliostro/spotify-bundle
Type:symfony-bundle
pkg:composer/calliostro/spotify-bundle
Requires
- php: ^8.1
- calliostro/spotify-client: ^1.0
- symfony/config: ^6.4 || ^7.0 || ^8.0
- symfony/dependency-injection: ^6.4 || ^7.0 || ^8.0
- symfony/http-kernel: ^6.4 || ^7.0 || ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpstan/phpstan: ^2.0
- symfony/phpunit-bridge: ^6.4 || ^7.0 || ^8.0
- symfony/rate-limiter: ^6.4 || ^7.0 || ^8.0
- symfony/security-core: ^6.4 || ^7.0 || ^8.0
Suggests
- symfony/rate-limiter: For proactive client-side rate limiting and traffic shaping
Provides
None
Conflicts
None
Replaces
None
README
A lightweight Symfony bundle integrating calliostro/spotify-client into your Symfony application. Provides dependency injection, autowiring, Client Credentials and Authorization Code Flow support, built-in retry resilience, and optional rate limiting for PHP 8.1+ and Symfony 6.4, 7.x, and 8.x.
๐ฆ Installation
Install via Composer:
composer require calliostro/spotify-bundle
โ๏ธ Configuration
Configure the bundle in config/packages/calliostro_spotify.yaml:
calliostro_spotify: # Required for Client Credentials Flow (get from https://developer.spotify.com/dashboard) client_id: '%env(SPOTIFY_CLIENT_ID)%' client_secret: '%env(SPOTIFY_CLIENT_SECRET)%' # Optional: HTTP User-Agent header for API requests # user_agent: 'MyApp/1.0 (+https://myapp.com)' # Optional: Retry resilience settings (enabled by default) # auto_retry: true # Automatically wait and retry on 429 rate limits (default: true) # max_retries: 3 # Maximum number of retry attempts (default: 3) # proactive_refresh: true # Proactively renew tokens before expiration (default: true) # Optional: Proactive rate limiting (requires symfony/rate-limiter) # rate_limiter: spotify_api
Note
By default, the client uses SpotifyClient/1.0.x as User-Agent. You can override this in the configuration if needed.
Authentication Methods
- Client Credentials Flow (Server-to-Server): Ideal for backend processes, cron jobs, and public catalog endpoints (search, artists, albums, tracks). Provide
client_idandclient_secret; bearer tokens are automatically fetched and renewed. - Authorization Code Flow (User Auth): For user-specific actions (e.g.
/me, playlists, player control). InjectCalliostro\Spotify\AuthHelperto build authorization URLs and exchange authorization codes for access and refresh tokens.
๐ Quick Start
Basic Usage (Client Credentials)
Inject SpotifyClient directly into your controllers or services:
<?php namespace App\Controller; use Calliostro\Spotify\SpotifyClient; use Symfony\Component\HttpFoundation\JsonResponse; final class MusicController { public function search(string $query, SpotifyClient $spotify): JsonResponse { $results = $spotify->search(query: $query, type: ['artist', 'album'], limit: 5); return new JsonResponse($results); } public function artist(string $id, SpotifyClient $spotify): JsonResponse { $artist = $spotify->getArtist($id); $topTracks = $spotify->getArtistTopTracks($id); return new JsonResponse([ 'artist' => $artist, 'top_tracks' => $topTracks['tracks'] ?? [], ]); } }
Authorization Code Flow (OAuth)
Inject Calliostro\Spotify\AuthHelper to handle OAuth user authorization:
<?php namespace App\Controller; use Calliostro\Spotify\AuthHelper; use Calliostro\Spotify\SpotifyClientFactory; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; final class SpotifyAuthController { public function login(AuthHelper $authHelper, UrlGeneratorInterface $urlGenerator): RedirectResponse { $redirectUri = $urlGenerator->generate('spotify_callback', [], UrlGeneratorInterface::ABSOLUTE_URL); $authorizeUrl = $authHelper->getAuthorizationUrl($redirectUri, [ 'user-read-private', 'user-read-email', ]); return new RedirectResponse($authorizeUrl); } public function callback( Request $request, AuthHelper $authHelper, UrlGeneratorInterface $urlGenerator ): Response { $code = $request->query->getString('code'); $redirectUri = $urlGenerator->generate('spotify_callback', [], UrlGeneratorInterface::ABSOLUTE_URL); // Exchange authorization code for access & refresh tokens $tokenData = $authHelper->requestAccessToken($code, $redirectUri); // Create a user-authenticated client $userClient = SpotifyClientFactory::createWithUserAuth( clientId: $authHelper->getClientId() ?? '', clientSecret: $authHelper->getClientSecret() ?? '', accessToken: $tokenData['access_token'], refreshToken: $tokenData['refresh_token'], expiresAt: time() + $tokenData['expires_in'] ); $me = $userClient->getCurrentUser(); return new Response('Hello, ' . ($me['display_name'] ?? 'User')); } }
โฑ๏ธ Rate Limiting with symfony/rate-limiter
To proactively shape and throttle requests before sending them to Spotify:
1. Install the Component
composer require symfony/rate-limiter
2. Configure the Rate Limiter
# config/packages/rate_limiter.yaml framework: rate_limiter: spotify_api: policy: 'sliding_window' limit: 20 interval: '1 second'
3. Assign to the Bundle
# config/packages/calliostro_spotify.yaml calliostro_spotify: client_id: '%env(SPOTIFY_CLIENT_ID)%' client_secret: '%env(SPOTIFY_CLIENT_SECRET)%' rate_limiter: spotify_api
๐ Requirements
- PHP
^8.1(tested on PHP 8.1โ8.6) - Symfony
^6.4 || ^7.0 || ^8.0 - calliostro/spotify-client
^1.0
๐งช Development & Testing Guide
See DEVELOPMENT.md for detailed setup instructions, test suite commands, static analysis, and contribution guidelines.
๐ค Contributing
Contributions are welcome! Please ensure that all tests pass and coding standards are maintained:
composer cs-fix composer analyse composer test-all
๐ License
This project is licensed under the MIT License โ see the LICENSE file for details.
โ๏ธ Disclaimer
Spotify is a registered trademark of Spotify AB. This project is an independent, unofficial open-source library and is not affiliated with, endorsed by, or sponsored by Spotify or Spotify AB.
๐ Acknowledgments
calliostro/spotify-clientfor the underlying Spotify Web API client.- Spotify Developer Platform for providing the Web API.
- Symfony for the web framework and dependency injection container.
- Sister Symfony bundles:
calliostro/spotify-web-api-bundleโ Closely related Spotify integration using the alternativejwilsson/spotify-web-api-phpclient.calliostro/discogs-bundleโ Symfony bundle for the Discogs API.calliostro/lastfm-bundleโ Symfony bundle for the Last.fm API.calliostro/musicbrainz-bundleโ Symfony bundle for the MusicBrainz API.