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 Php Client Laravel Package

akeneo/api-php-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require akeneo/api-php-client
    

    Check the official documentation for version compatibility with your Akeneo PIM instance.

  2. First API Call

    use Akeneo\ApiClient\AkeneoApiClient;
    use Akeneo\ApiClient\Configuration;
    
    $config = Configuration::create(
        'https://your-akeneo-instance.com/api/rest/v1',
        'username',
        'api-key',
        'client-id' // Optional for OAuth2
    );
    
    $client = new AkeneoApiClient($config);
    
    // Fetch product list (first use case)
    $response = $client->getProductList();
    $products = $response->getData();
    
  3. Key Files to Review

    • src/Akeneo/ApiClient/Configuration.php (API endpoint, auth, and defaults)
    • src/Akeneo/ApiClient/Api/AkeneoApi.php (core API methods)
    • src/Akeneo/ApiClient/Model/ (response models like Product, Family, Attribute)

Implementation Patterns

Common Workflows

1. Product Management

// Create a product
$product = new \Akeneo\ApiClient\Model\Product();
$product->setEnabled(true);
$product->setFamilies(['electronics']);
$product->setValues([
    'sku' => 'PROD-123',
    'name' => 'Wireless Headphones',
    'weight' => '0.5'
]);

$createdProduct = $client->createProduct($product);

// Update a product
$updatedProduct = $client->updateProduct('PROD-123', $product);

// Get product by identifier
$product = $client->getProduct('PROD-123');

2. Batch Operations

// Export products (CSV/JSON)
$client->exportProducts('csv', ['enabled' => true]);

// Import products (CSV/JSON)
$client->importProducts('path/to/file.csv', 'csv');

3. Attribute/Family Management

// Get all families
$families = $client->getFamilyList();

// Create a family
$family = new \Akeneo\ApiClient\Model\Family();
$family->setCode('electronics');
$family->setLabels(['en_US' => 'Electronics']);
$createdFamily = $client->createFamily($family);

4. Media Management

// Upload media file
$client->uploadMediaFile(
    'PROD-123',
    'image',
    'path/to/image.jpg',
    'image/jpeg'
);

5. Search and Filtering

// Search products with filters
$searchCriteria = new \Akeneo\ApiClient\Model\SearchCriteria();
$searchCriteria->addFilter('enabled', true);
$searchCriteria->addFilter('family', 'electronics');

$products = $client->searchProducts($searchCriteria);

Integration Tips

  1. Error Handling Use try-catch with Akeneo\ApiClient\Exception\ApiException for API errors:

    try {
        $client->getProduct('PROD-999');
    } catch (\Akeneo\ApiClient\Exception\ApiException $e) {
        if ($e->getCode() === 404) {
            // Handle "not found"
        }
    }
    
  2. Pagination Akeneo API uses cursor-based pagination. Use getNextPage() on responses:

    $response = $client->getProductList();
    while ($response->getData() !== null) {
        $products = $response->getData();
        $response = $client->getProductList($response->getNextPage());
    }
    
  3. Custom Headers Add headers via Configuration:

    $config = Configuration::create(
        'https://your-akeneo-instance.com/api/rest/v1',
        'username',
        'api-key'
    )->setDefaultHeader('X-Custom-Header', 'value');
    
  4. Logging Enable Guzzle logging for debugging:

    $config->setDebug(true);
    
  5. Testing Use the AkeneoApiClient with mock responses in PHPUnit:

    $mockHandler = HandlerStack::create();
    $mockHandler->push(Middleware::mock(function ($request) {
        return new Response(200, [], json_encode(['data' => []]));
    }));
    
    $client = new AkeneoApiClient($config, $mockHandler);
    

Gotchas and Tips

Pitfalls

  1. Authentication Quirks

    • OAuth2: If using OAuth2, ensure client_id and client_secret are correctly set in Configuration. The token must be refreshed manually if expired.
    • Basic Auth: For basic auth, use Configuration::create() with username and password (not api-key).
    • API Key: Some Akeneo instances require the API key to be prefixed (e.g., Bearer YOUR_API_KEY). Check your instance’s docs.
  2. Rate Limiting Akeneo may throttle requests. Implement exponential backoff for retries:

    $client->setRetryConfig([
        'max_retries' => 3,
        'delay' => 100, // ms
    ]);
    
  3. Data Validation

    • The API rejects malformed requests (e.g., missing required fields). Use Model classes to validate data before sending:
      if (!$product->isValid()) {
          throw new \InvalidArgumentException('Invalid product data');
      }
      
    • Check Model::getErrors() for validation feedback.
  4. Media File Size Limits Large media files may fail silently. Validate file sizes before upload:

    $maxSize = 5 * 1024 * 1024; // 5MB
    if (filesize('path/to/file.jpg') > $maxSize) {
        throw new \RuntimeException('File too large');
    }
    
  5. Deprecated Methods Some older Akeneo versions use deprecated endpoints (e.g., /api/rest/v1/products vs. /api/rest/v1/product). Verify your Akeneo version’s API docs.


Debugging Tips

  1. Enable Verbose Logging

    $config->setDebug(true);
    

    Logs will show raw requests/responses in storage/logs/laravel.log.

  2. Inspect Response Headers Use getHeaders() on responses to debug pagination or caching:

    $response = $client->getProductList();
    $headers = $response->getHeaders();
    
  3. Validate API Responses Always check getStatusCode() and getData():

    $response = $client->getProduct('PROD-123');
    if ($response->getStatusCode() !== 200) {
        throw new \RuntimeException('Failed to fetch product');
    }
    
  4. Common HTTP Errors

    • 401 Unauthorized: Invalid credentials or expired token.
    • 403 Forbidden: Lack of permissions (check Akeneo user roles).
    • 404 Not Found: Resource doesn’t exist (e.g., product/attribute).
    • 422 Unprocessable Entity: Validation errors (check response body for details).

Extension Points

  1. Custom API Clients Extend AkeneoApiClient for domain-specific methods:

    class CustomAkeneoClient extends AkeneoApiClient {
        public function getEnabledElectronicsProducts() {
            $searchCriteria = new \Akeneo\ApiClient\Model\SearchCriteria();
            $searchCriteria->addFilter('enabled', true);
            $searchCriteria->addFilter('family', 'electronics');
            return $this->searchProducts($searchCriteria);
        }
    }
    
  2. Middleware for Requests Add middleware to modify requests (e.g., logging, auth):

    $stack = HandlerStack::create();
    $stack->push(Middleware::tap(function ($request) {
        $request->getHeaders()->addHeader('X-Request-ID', uniqid());
    }));
    
    $client = new AkeneoApiClient($config, $stack);
    
  3. Response Transformers Override response handling for custom data shaping:

    $response = $client->getProduct('PROD-123');
    $productData = $response->getData()->toArray(); // Convert to array
    
  4. Event Listeners Use Laravel events to react to API calls (e.g., log imports/exports):

    // In a service provider
    $client->getProductList(); // Trigger event
    event(new \App\Events\AkeneoApiCalled($client, 'getProductList'));
    
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon