## Getting Started
### Minimal Setup
1. **Install the bundle**:
```bash
composer require aymdev/api-client-bundle
config/packages/aymdev_api_client.yaml:
aymdev_api_client:
logger: app.logger # Optional: Enable logging
cache: app.cache.pool # Optional: Enable caching
use AymDev\ApiClientBundle\Client\ApiClientInterface;
class MyService {
public function __construct(
private ApiClientInterface $apiClient
) {}
}
public function fetchData(): ResponseInterface {
return $this->apiClient->request('GET', 'https://api.example.com/data', [
'user_data' => [
ApiClientInterface::REQUEST_ID => 'api.example.com.data',
],
]);
}
Use the user_data option to pass authentication tokens or headers:
public function authenticatedCall(): ResponseInterface {
return $this->apiClient->request('GET', 'https://api.example.com/protected', [
'headers' => [
'Authorization' => 'Bearer ' . $this->getAuthToken(),
],
'user_data' => [
ApiClientInterface::REQUEST_ID => 'api.example.com.protected',
],
]);
}
Cache responses with dynamic TTL or expiration:
public function cachedCall(int $id): ResponseInterface {
return $this->apiClient->request('GET', 'https://api.example.com/items/{$id}', [
'user_data' => [
ApiClientInterface::REQUEST_ID => 'api.example.com.item.' . $id,
ApiClientInterface::CACHE_DURATION => 3600, // 1 hour
ApiClientInterface::CACHE_ERROR_DURATION => 86400, // 24 hours for errors
],
]);
}
Enable logging and validate responses:
public function validatedCall(): ResponseInterface {
return $this->apiClient->request('GET', 'https://api.example.com/validate', [
'user_data' => [
ApiClientInterface::REQUEST_ID => 'api.example.com.validate',
ApiClientInterface::LOG_REQUEST_BODY => true,
ApiClientInterface::LOG_RESPONSE_BODY => true,
ApiClientInterface::VALIDATE_JSON => true,
ApiClientInterface::VALIDATE_CALLBACK => function ($data) {
if (!isset($data['required_field'])) {
throw new \UnexpectedValueException('Missing required field');
}
},
],
]);
}
Use the ResponseInterface to transform responses into DTOs:
public function fetchAsDto(): MyDto {
$response = $this->apiClient->request('GET', 'https://api.example.com/data', [
'user_data' => [ApiClientInterface::REQUEST_ID => 'api.example.com.data'],
]);
return MyDto::fromArray($response->toArray());
}
Request ID Uniqueness:
REQUEST_ID is unique per request to avoid cache collisions.api.example.com.{endpoint}.{params} format.Logging Overhead:
LOG_REQUEST_BODY, LOG_RESPONSE_BODY) can impact performance.aymdev_api_client:
logger: null # Disable logging
Cache Key Conflicts:
REQUEST_ID is not unique, cached responses may overwrite each other.REQUEST_ID.Validation Order:
VALIDATE_CALLBACK implies VALIDATE_JSON. If you only need JSON validation, use VALIDATE_JSON alone.Error Handling:
CACHE_ERROR_DURATION) may hide transient errors.CACHE_EXPIRATION for time-sensitive error caching.Check Logs:
aymdev_api_client:
logger: app.logger
error field in logs for exceptions.Cache Inspection:
$this->cachePool->delete('api.example.com.data'); // Replace with your cache key
Request ID Validation:
REQUEST_ID to verify uniqueness:
$this->apiClient->request('GET', '...', [
'user_data' => [
ApiClientInterface::REQUEST_ID => 'test.unique.id',
ApiClientInterface::LOG_REQUEST_BODY => true,
],
]);
Custom Validation:
private function validateRequiredFields(array $data): ?string {
if (empty($data['field1']) || empty($data['field2'])) {
return 'Fields field1 and field2 are required';
}
}
Dynamic Cache Keys:
REQUEST_ID dynamically based on request parameters:
ApiClientInterface::REQUEST_ID => 'api.example.com.' . md5(serialize($params)),
Middleware Integration:
HttpClient middleware to add headers or transform responses:
$client = $this->apiClient->getClient()->withOptions([
'headers' => ['X-Custom-Header' => 'value'],
]);
Testing:
ApiClientInterface in tests to avoid real API calls:
$this->createMock(ApiClientInterface::class)
->method('request')
->willReturn($this->createMock(ResponseInterface::class));
---
How can I help you explore Laravel packages today?