How to implement the Magento2 API services - Sintraconsulting/pimcore-product-sync-plugin GitHub Wiki

How to implement the Magento2 API services

Magento2 provides a large set of API services to manage categories, products, attributes an so on. A complete list of service examples are avalible in Magento2 Documentation.

In order to use them, we need to integrate these services with our Pimcore solution. The most simple solution, is to generate the client implementation starting from swagger schema; to so that you can use Swagger Codegen. An Online Implementation of Swagger Codegen is available; to generate the code, you can use a stable schema version.

For Magento2, we can find a lot of client implementation generated with such method; instead of creating a new one, you could simply integrate a woking implemantation in your project. In our case, we used https://github.com/springimport/swagger-magento2-client.

Let's see how API services works with some examples of product's APIs.

Generate API Instance

Magento API services requires a token-based authentication. To keep the code configuration-independent, we punt authentication infos on a self containte MagentoConfig.php file

class MagentoConfig {
    public static function getConfig() {
        return array(
            "path" => "http://magento.base.url",
            "apiKey" => "MY-API-KEY"
        );
    }
}

To obtain a valid token, you need to create a new Integration; you can do that on Magento2 Admin Panel clicking on: System -> Integration -> Add New Integration

Once you have completed creation, your apiKey will be on "Access Token" field.

Now, you are able to generate the API Instance:

/**
  * Get API Client to Perform Rest API calls
  *
  * @return ApiClient The API Client
  */
public function getApiInstance() {
    $magentoConfig = MagentoConfig::getConfig();

    $baseUrl = $magentoConfig['path'] . '/rest';
    $token = 'bearer ' . $magentoConfig['apiKey'];

    $config = new Configuration();
    $config->setHost($baseUrl);
    $config->addDefaultHeader('Authorization', $token);

    return new ApiClient($config); 
}

We must use an API instance in all API service calls.

Create a Product

Magento2 APIs provide methods to perform CRUD operations on entities. Let's start by seeing how to retrieve a product.

public function createEntity($entity) {
    $apiClient = $this->getApiInstance();

    $productInstance = new CatalogProductRepositoryV1Api($apiClient);

    try {
        $product = array("product" => $entity, "saveOptions" => true);
        $productBody = new Body18($product);
        
        $result = $productInstance->catalogProductRepositoryV1SavePost($productBody);
        return $result;
    } catch (Exception $e) {
        Logger::err($e->getMessage());
    }
}

In "Map Pimcore objects to Magento2 objects" chapter, we will see in details how the $entity variable looks like

Get a Product

public function getEntity($sku, $editMode = null, $storeId = null, $forceReload = null) {
    $apiClient = $this->getApiInstance();

    $productInstance = new CatalogProductRepositoryV1Api($apiClient);

    try {
        $result = $productInstance->catalogProductRepositoryV1GetGet($sku, $editMode, $storeId, $forceReload);
        return $result;
    } catch (Exception $e) {
        Logger::err($e->getMessage());
        return false;
    }
}

For procuct entities, the primary key used to retrieve objects is the product's sku.

Update a Product

public function updateEntity($sku, $entity) {
    $apiClient = $this->getApiInstance();

    $productInstance = new CatalogProductRepositoryV1Api($apiClient);

    try {
        $product = array("product" => $entity, "saveOptions" => true);
        $productBody = new Body18($product);
        
        $result = $productInstance->catalogProductRepositoryV1SavePut($sku, $productBody);
        return $result;
    } catch (Exception $e) {
        Logger::err($e->getMessage());
    }
}

Delete a Product

public function deleteEntity($sku) {
    $apiClient = $this->getApiInstance();

    $productInstance = new CatalogProductRepositoryV1Api($apiClient);

    try {
        $result = $productInstance->catalogProductRepositoryV1DeleteByIdDelete($sku);
        return $result;
    } catch (Exception $e) {
        Logger::err($e->getMessage());
    }
}

Search for Products

public function searchProducts($field, $value, $conditionType = null) {
    $apiClient = $this->getApiInstance();

    $productInstance = new CatalogProductRepositoryV1Api($apiClient);

    try {
        $result = $productInstance->catalogProductRepositoryV1GetListGet($field, $value, $conditionType);
        return $result;
    } catch (Exception $e) {
        Logger::err($e->getMessage());
        return false;
    }
}

List of possible conditions is:

  • eq: Equals (default if no condition is provided).
  • finset: A value within a set of values
  • gt: Greater than
  • gteq: Greater than or equal
  • in: In. The value can contain a comma-separated list of values.
  • like: Like. The value can contain the SQL wildcard characters when like is specified.
  • lt: Less than
  • lteq: Less than or equal
  • moreq: More or equal
  • neq: Not equal
  • nin: Not in. The value can contain a comma-separated list of values.
  • notnull: Not null
  • null: Null
⚠️ **GitHub.com Fallback** ⚠️