Search by

calliostro / spotify-bundle

calliostro

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

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-09-21 09:13 UTC

This package is auto-updated.

Last update: 2026-09-21 09:16:43 UTC


README

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

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_id and client_secret; bearer tokens are automatically fetched and renewed.
  • Authorization Code Flow (User Auth): For user-specific actions (e.g. /me, playlists, player control). Inject Calliostro\Spotify\AuthHelper to 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