Installation:
composer require doctrine/doctrine-cache-bundle da/api-client-bundle:dev-master
Enable in AppKernel.php:
new Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle(),
new Da\ApiClientBundle\DaApiClientBundle(),
Configuration:
Define API endpoints in config.yml:
da_api_client:
clients:
my_api:
base_url: "https://api.example.com/v1"
timeout: 30
auth:
type: "basic"
username: "%env(API_USERNAME)%"
password: "%env(API_PASSWORD)%"
First Use Case: Inject the client in a service/controller:
use Da\ApiClientBundle\Client\ClientInterface;
class MyService {
private $client;
public function __construct(ClientInterface $client) {
$this->client = $client;
}
public function fetchData() {
return $this->client->get('my_api', '/endpoint');
}
}
Service Integration: Use dependency injection to pass the client to services:
// services.yml
services:
my_service:
arguments:
$apiClient: '@da_api_client.client.my_api'
Request Customization: Override default headers/params per request:
$response = $this->client->get('my_api', '/endpoint', [
'headers' => ['X-Custom-Header' => 'value'],
'query' => ['filter' => 'active']
]);
Response Handling: Parse JSON responses with built-in helpers:
$data = $this->client->getJson('my_api', '/data');
Authentication:
Support for basic, oauth, and custom auth:
auth:
type: "oauth"
consumer_key: "%env(OAUTH_KEY)%"
consumer_secret: "%env(OAUTH_SECRET)%"
Rate Limiting: Use Symfony’s cache layer to implement throttling:
$cache = $this->get('doctrine_cache.providers.api_rate_limit');
if (!$cache->fetch('api_calls')) {
$response = $this->client->get('my_api', '/endpoint');
$cache->save('api_calls', 1, 60); // 1 call per minute
}
Retry Logic: Wrap calls in a retry decorator:
$retryClient = new RetryClient($this->client, 3);
$retryClient->get('my_api', '/endpoint');
Deprecated Symfony2:
composer.json for symfony/*: ~2.7 constraints.Cache Misconfiguration:
doctrine_cache.providers in config.yml:
doctrine_cache:
providers:
api_cache:
type: file_system
file_system:
directory: "%kernel.cache_dir%/api"
Authentication Quirks:
Da\ApiClientBundle\Event\AuthEvent to hook into auth failures.Response Parsing:
Da\ApiClientBundle\Response\Response for custom formats.Enable Verbose Logging:
da_api_client:
debug: true
Logs requests/responses to var/log/dev.log.
Test Locally:
Use bin/console debug:config da_api_client to validate config.
Custom Clients:
Implement Da\ApiClientBundle\Client\ClientInterface for non-HTTP APIs (e.g., gRPC):
class CustomClient implements ClientInterface {
public function get($name, $endpoint, array $options = []) {
// Custom logic
}
}
Middleware: Add request/response filters via events:
$dispatcher->addListener(
DaApiClientEvents::PRE_REQUEST,
function (PreRequestEvent $event) {
$event->getRequest()->setHeader('X-App-Version', '1.0');
}
);
Response Transformers:
Override Da\ApiClientBundle\Response\Transformer\JsonTransformer for custom JSON handling.
How can I help you explore Laravel packages today?