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

aymdev/api-client-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the bundle**:
   ```bash
   composer require aymdev/api-client-bundle
  1. Configure basic features in config/packages/aymdev_api_client.yaml:
    aymdev_api_client:
        logger: app.logger  # Optional: Enable logging
        cache: app.cache.pool  # Optional: Enable caching
    
  2. Inject the client into your service:
    use AymDev\ApiClientBundle\Client\ApiClientInterface;
    
    class MyService {
        public function __construct(
            private ApiClientInterface $apiClient
        ) {}
    }
    

First Use Case: Simple API Call with Request ID

public function fetchData(): ResponseInterface {
    return $this->apiClient->request('GET', 'https://api.example.com/data', [
        'user_data' => [
            ApiClientInterface::REQUEST_ID => 'api.example.com.data',
        ],
    ]);
}

Implementation Patterns

Authentication Workflow

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',
        ],
    ]);
}

Caching Strategy

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
        ],
    ]);
}

Logging and Validation

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');
                }
            },
        ],
    ]);
}

DTO Integration (Future-Proofing)

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());
}

Gotchas and Tips

Pitfalls

  1. Request ID Uniqueness:

    • Ensure REQUEST_ID is unique per request to avoid cache collisions.
    • Example: Use api.example.com.{endpoint}.{params} format.
  2. Logging Overhead:

    • Logging request/response bodies (LOG_REQUEST_BODY, LOG_RESPONSE_BODY) can impact performance.
    • Disable in production if not needed:
      aymdev_api_client:
          logger: null  # Disable logging
      
  3. Cache Key Conflicts:

    • If REQUEST_ID is not unique, cached responses may overwrite each other.
    • Use dynamic values (e.g., IDs, timestamps) in the REQUEST_ID.
  4. Validation Order:

    • VALIDATE_CALLBACK implies VALIDATE_JSON. If you only need JSON validation, use VALIDATE_JSON alone.
  5. Error Handling:

    • Cached error responses (CACHE_ERROR_DURATION) may hide transient errors.
    • Use CACHE_EXPIRATION for time-sensitive error caching.

Debugging Tips

  1. Check Logs:

    • Enable detailed logging to debug failed requests:
      aymdev_api_client:
          logger: app.logger
      
    • Look for error field in logs for exceptions.
  2. Cache Inspection:

    • Manually clear cache to test uncached responses:
      $this->cachePool->delete('api.example.com.data'); // Replace with your cache key
      
  3. Request ID Validation:

    • Log REQUEST_ID to verify uniqueness:
      $this->apiClient->request('GET', '...', [
          'user_data' => [
              ApiClientInterface::REQUEST_ID => 'test.unique.id',
              ApiClientInterface::LOG_REQUEST_BODY => true,
          ],
      ]);
      

Extension Points

  1. Custom Validation:

    • Extend validation logic by creating a reusable callback:
      private function validateRequiredFields(array $data): ?string {
          if (empty($data['field1']) || empty($data['field2'])) {
              return 'Fields field1 and field2 are required';
          }
      }
      
  2. Dynamic Cache Keys:

    • Generate REQUEST_ID dynamically based on request parameters:
      ApiClientInterface::REQUEST_ID => 'api.example.com.' . md5(serialize($params)),
      
  3. Middleware Integration:

    • Use Symfony’s HttpClient middleware to add headers or transform responses:
      $client = $this->apiClient->getClient()->withOptions([
          'headers' => ['X-Custom-Header' => 'value'],
      ]);
      
  4. Testing:

    • Mock the ApiClientInterface in tests to avoid real API calls:
      $this->createMock(ApiClientInterface::class)
          ->method('request')
          ->willReturn($this->createMock(ResponseInterface::class));
      

---
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle