Installation
Run composer require blitzr/api-client-bundle and enable the bundle in config/bundles.php:
Blitzr\ApiClientBundle\BlitzrApiClientBundle::class => ['all' => true],
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.
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);
}
blitzr_api_client.client) with all API methods.Dependency Injection
Prefer constructor injection for the BlitzrClientInterface in services, controllers, or commands:
public function __construct(private BlitzrClientInterface $client) {}
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());
}
Pagination
Use the getPaginatedResults() method for endpoints returning collections:
$tracks = $this->client->getPaginatedResults('tracks', [
'page' => 1,
'limit' => 20,
]);
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);
}
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...
}
Artist, Tag) to forms using DataTransformer or FormType extensions.$this->messageBus->dispatch(new FetchArtistMessage('artist-id'));
$cache = $this->container->get('cache.app');
$artist = $cache->get('artist:'.$id, function() use ($id) {
return $this->client->getArtist($id);
});
API Key Exposure
%env(BLITZR_API_KEY)%) and restrict .env to .gitignore.Rate Limiting
$attempts = 0;
while ($attempts < 3) {
try {
return $this->client->getTrack($id);
} catch (RateLimitException $e) {
$attempts++;
sleep(2 ** $attempts);
}
}
Deprecated Methods
Webhook Delays
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)));
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());
}
Common HTTP Errors
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'
Middleware Add request/response middleware to the client:
$client = new BlitzrClient($apiKey);
$client->getHttpClient()->getEmitter()->addSubscriber(new YourMiddleware());
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()]);
});
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);
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'
How can I help you explore Laravel packages today?