Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Api Client Bundle Laravel Package

blitzr/api-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require blitzr/api-client-bundle and enable the bundle in config/bundles.php:

    Blitzr\ApiClientBundle\BlitzrApiClientBundle::class => ['all' => true],
    
  2. Configuration Add your API key to config/packages/blitzr_api_client.yaml:

    blitzr_api_client:
        api_key: '%env(BLITZR_API_KEY)%'
    

    Store the key in .env for security.

  3. First Use Case Inject the client service into a controller or command:

    use Blitzr\ApiClientBundle\Client\BlitzrClientInterface;
    
    public function __construct(private BlitzrClientInterface $blitzrClient) {}
    
    public function index(): Response
    {
        $artist = $this->blitzrClient->getArtist('year-of-no-light');
        return $this->json($artist);
    }
    

Where to Look First

  • Service Reference: The bundle provides a single service (blitzr_api_client.client) with all API methods.
  • Documentation: Use the Blitzr PHP client docs as a reference for available methods.
  • API Reference: Cross-check with the official Blitzr API docs for endpoints and payloads.

Implementation Patterns

Core Workflows

  1. Dependency Injection Prefer constructor injection for the BlitzrClientInterface in services, controllers, or commands:

    public function __construct(private BlitzrClientInterface $client) {}
    
  2. Error Handling Wrap API calls in try-catch blocks to handle exceptions (e.g., BlitzrApiException):

    try {
        $track = $this->client->getTrack('track-id');
    } catch (\Blitzr\ApiClientBundle\Exception\BlitzrApiException $e) {
        $this->addFlash('error', $e->getMessage());
    }
    
  3. Pagination Use the getPaginatedResults() method for endpoints returning collections:

    $tracks = $this->client->getPaginatedResults('tracks', [
        'page' => 1,
        'limit' => 20,
    ]);
    
  4. Async Operations For long-running tasks (e.g., uploads), use the createJob() method and poll status via getJob():

    $job = $this->client->createJob('upload', ['file' => $file]);
    while ($job['status'] !== 'completed') {
        $job = $this->client->getJob($job['id']);
        sleep(2);
    }
    
  5. Webhook Integration Validate Blitzr webhook signatures using the validateWebhook() method in your webhook endpoint:

    public function handleWebhook(Request $request): Response
    {
        $payload = json_decode($request->getContent(), true);
        if (!$this->client->validateWebhook($payload, $request->headers->get('X-Signature'))) {
            return new Response('Invalid signature', 403);
        }
        // Process payload...
    }
    

Integration Tips

  • Symfony Forms: Bind Blitzr entities (e.g., Artist, Tag) to forms using DataTransformer or FormType extensions.
  • Messenger Component: Dispatch Blitzr API calls as messages for async processing:
    $this->messageBus->dispatch(new FetchArtistMessage('artist-id'));
    
  • Cache Responses: Cache frequent API calls (e.g., artist/track details) using Symfony’s cache system:
    $cache = $this->container->get('cache.app');
    $artist = $cache->get('artist:'.$id, function() use ($id) {
        return $this->client->getArtist($id);
    });
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Risk: Hardcoding API keys in config files or version control.
    • Fix: Use environment variables (%env(BLITZR_API_KEY)%) and restrict .env to .gitignore.
  2. Rate Limiting

    • Issue: Blitzr may throttle requests during high-volume operations.
    • Solution: Implement exponential backoff in retries:
      $attempts = 0;
      while ($attempts < 3) {
          try {
              return $this->client->getTrack($id);
          } catch (RateLimitException $e) {
              $attempts++;
              sleep(2 ** $attempts);
          }
      }
      
  3. Deprecated Methods

  4. Webhook Delays

    • Behavior: Blitzr webhooks may have slight delays (e.g., 1-5 seconds).
    • Workaround: Implement idempotency in your webhook handlers (e.g., track processed events).

Debugging

  1. Enable Verbose Logging Configure Monolog to log Blitzr API requests/responses:

    # config/packages/monolog.yaml
    monolog:
        handlers:
            blitzr:
                type: stream
                path: "%kernel.logs_dir%/blitzr.log"
                level: debug
                channels: ["blitzr"]
    

    Then enable the channel in the client:

    $this->client->setLogger($this->container->get('logger')->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG)));
    
  2. Inspect Raw Responses Use the getLastResponse() method to debug failed requests:

    try {
        $this->client->getArtist('invalid-id');
    } catch (BlitzrApiException $e) {
        $response = $this->client->getLastResponse();
        dump($response->getContent());
    }
    
  3. Common HTTP Errors

    • 401 Unauthorized: Invalid API key or expired token.
    • 404 Not Found: Resource does not exist (validate IDs).
    • 500 Server Error: Blitzr API issue; check their status page.

Extension Points

  1. Custom HTTP Client Override the default Guzzle client by binding your own implementation:

    # config/services.yaml
    services:
        Blitzr\ApiClientBundle\Client\BlitzrClient:
            arguments:
                $httpClient: '@your_custom_guzzle_client'
    
  2. Middleware Add request/response middleware to the client:

    $client = new BlitzrClient($apiKey);
    $client->getHttpClient()->getEmitter()->addSubscriber(new YourMiddleware());
    
  3. Event Listeners Subscribe to Blitzr events (e.g., blitzr.api.request, blitzr.api.response) for logging/auditing:

    $dispatcher->addListener('blitzr.api.request', function (RequestEvent $event) {
        $this->logger->info('API Request', ['endpoint' => $event->getRequest()->getUri()]);
    });
    
  4. Testing Mock the client in tests using PHPUnit’s createMock:

    $mockClient = $this->createMock(BlitzrClientInterface::class);
    $mockClient->method('getArtist')->willReturn(['id' => 'test']);
    $this->container->set('blitzr_api_client.client', $mockClient);
    
  5. Configuration Overrides Dynamically override the API key or base URL per environment:

    # config/packages/dev/blitzr_api_client.yaml
    blitzr_api_client:
        api_key: '%env(BLITZR_API_KEY_DEV)%'
        base_uri: 'https://dev.blitzr.io/api'
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope