Magento 2 : How to create custom webapi?Magento 2: How to put authorization to custom module APImagento2 webapi authorization for admin usersclass [] does not exist for custom extension_attributes over webapiOverride default model webapi output magento2How to structured data in custom WebAPI?Admin User unable to access webapiHow to override webapi.xml in custom module?Magento2 Create Account with password Webapi not workingMagento 2.2 - Custom WEBAPI - Custom JSON StructureMagento2 - How to assign custom Certification to my extension?

Do native speakers use ZVE or CPU?

Is this floating-point optimization allowed?

nginx serves wrong domain site. It doenst shows default site if no configuration applies

Professor falsely accusing me of cheating in a class he does not teach, two months after end of the class. What precautions should I take?

Alternatives to using writing paper for writing practice

Draw 3D Cubes around centre

When did the Roman Empire fall according to contemporaries?

Is killing off one of my queer characters homophobic?

Rearranging the formula

Occasus nescius

Why would an Inquisitive rogue choose to use Insightful Fighting as opposed to using their Cunning Action to Hide?

Bob's unnecessary trip to the shops

In which ways do anagamis still experience ignorance?

Can I intentionally omit previous work experience or pretend it doesn't exist when applying for jobs?

As a DM, how to avoid unconscious metagaming when dealing with a high AC character?

Did any of the founding fathers anticipate Lysander Spooner's criticism of the constitution?

Why does the trade federation become so alarmed upon learning the ambassadors are Jedi Knights?

How do Windows version numbers work?

What would the EU do if an EU member declared war on another EU member?

What is a printer console?

wavelength of seismic wave with a gaussian source

Cubic programming and beyond?

Was adding milk to tea started to reduce employee tea break time?

Filtering fine silt/mud from water (not necessarily bacteria etc.)



Magento 2 : How to create custom webapi?


Magento 2: How to put authorization to custom module APImagento2 webapi authorization for admin usersclass [] does not exist for custom extension_attributes over webapiOverride default model webapi output magento2How to structured data in custom WebAPI?Admin User unable to access webapiHow to override webapi.xml in custom module?Magento2 Create Account with password Webapi not workingMagento 2.2 - Custom WEBAPI - Custom JSON StructureMagento2 - How to assign custom Certification to my extension?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I am fresher in magento2, How to implement webapi in custom extension in magento2?



Thanks in advance.










share|improve this question






















  • did you find solution?

    – Muhammad Hasham
    Jul 10 at 12:46

















1















I am fresher in magento2, How to implement webapi in custom extension in magento2?



Thanks in advance.










share|improve this question






















  • did you find solution?

    – Muhammad Hasham
    Jul 10 at 12:46













1












1








1








I am fresher in magento2, How to implement webapi in custom extension in magento2?



Thanks in advance.










share|improve this question














I am fresher in magento2, How to implement webapi in custom extension in magento2?



Thanks in advance.







magento2 webapi






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jul 5 at 11:41









pankaj parmarpankaj parmar

61 bronze badge




61 bronze badge












  • did you find solution?

    – Muhammad Hasham
    Jul 10 at 12:46

















  • did you find solution?

    – Muhammad Hasham
    Jul 10 at 12:46
















did you find solution?

– Muhammad Hasham
Jul 10 at 12:46





did you find solution?

– Muhammad Hasham
Jul 10 at 12:46










1 Answer
1






active

oldest

votes


















2














First you need to create webapi.xml under your custom module VendorModuleetc



<route url="/V1/custom/:categoryId/products" method="GET">
<service class="VendorModuleApiCategoryLinkManagementInterface" method="getAssignedProducts" />
<resources>
<resource ref="self"/>
</resources>
</route>


– Route – This is the URL which will be used to call our API




https://MagentoBaseURL/index.php/rest/V1/custom/categoryId/products




– Service Class – This is the interface class of our API and the main method “getAssignedProducts” will be called with categoryId as the parameter



– Resources- This defines who has the permission to call this API. It could be anonymous (everyone) or self (customer) or specific admin user with specific permission for example Vendor_Module::custom which can be added in acl.xml



Lets now create the main interface file for your web API CategoryLinkManagementInterface.php under VendorModuleApi as specified in webapi.xml.



<?php
namespace VendorModuleApi;

/**
* @api
*/
interface CategoryLinkManagementInterface

/**
* Get products assigned to a category
*
* @param int $categoryId
* @return ScommerceCustomApiDataCategoryProductLinkInterface[]
*/
public function getAssignedProducts($categoryId);



In the above code, we have created an interface and define the main method i.e. getAssignedProducts as specified in webapi.xml. The other thing to notice here is the@return parameter which is the data interface VendorModuleApiDataCategoryProductLinkInterface[]. Will explain what is data interface in our next step.



Based on the return parameter, let’s create our data interface CategoryProductLinkInterface.php under VendorModuleApiData



<?php
namespace VendorModuleApiData;

/**
* @api
*/
interface CategoryProductLinkInterface

/**
* @return string


The above data interface class allows you define the response/output of our API request, so as you can see this API will return sku, name, price, position and category description as an output.



Now your interface files are created, let’s create our model classes where we can put the actual business logic, to do so we would need to specify this in our di.xml file under VendorModuleetc



<config ...>
<preference for="VendorModuleApiCategoryLinkManagementInterface" type="VendorModuleModelCategoryLinkManagement" />
<preference for="VendorModuleApiDataCategoryProductLinkInterface" type="VendorModuleModelCategoryProductLink" />
</config>


In the above step, we have specified which model classes will be created against our interfaces to add our business logic.



Let’s create our first model class CategoryLinkManagement.php under VendorModuleModel as specified in di.xml



<?php
namespace VendorModuleModel;

/**
* Class CategoryLinkManagement
*/
class CategoryLinkManagement implements VendorModuleApiCategoryLinkManagementInterface

/**
* @var MagentoCatalogApiCategoryRepositoryInterface
*/
protected $categoryRepository;

/**
* @var VendorModuleApiDataCategoryProductLinkInterfaceFactory
*/
protected $productLinkFactory;

/**
* CategoryLinkManagement constructor.
*
* @param MagentoCatalogApiCategoryRepositoryInterface $categoryRepository
* @param ScommerceCustomApiDataCategoryProductLinkInterfaceFactory $productLinkFactory
*/
public function __construct(
MagentoCatalogApiCategoryRepositoryInterface $categoryRepository,
ScommerceCustomApiDataCategoryProductLinkInterfaceFactory $productLinkFactory
)
$this->categoryRepository = $categoryRepository;
$this->productLinkFactory = $productLinkFactory;


/**
* @inheritdoc
*/
public function getAssignedProducts($categoryId)

$category = $this->categoryRepository->get($categoryId);
if (!$category->getIsActive())
return [[
'error' => true,
'error_desc' => 'Category is disabled'
]];

$categoryDesc = $category->getDescription();

/** @var MagentoCatalogModelResourceModelProductCollection $products */
$products = $category->getProductCollection()
->addFieldToSelect('position')
->addFieldToSelect('name')
->addFieldToSelect('price');

/** @var ScommerceCustomApiDataCategoryProductLinkInterface[] $links */
$links = [];

/** @var MagentoCatalogModelProduct $product */
foreach ($products->getItems() as $product)
/** @var ScommerceCustomApiDataCategoryProductLinkInterface $link */
$link = $this->productLinkFactory->create();
$link->setSku($product->getSku())
->setName($product->getName())
->setPrice($product->getFinalPrice())
->setPosition($product->getData('cat_index_position'))
->setCategoryDescription($categoryDesc);
$links[] = $link;


return $links;




Lets now create our second model class CategoryProductLink.php under VendorModuleModel as specified in di.xml



<?php
namespace VendorModuleModel;

/**
* @codeCoverageIgnore
*/
class CategoryProductLink implements VendorModuleApiDataCategoryProductLinkInterface

/**#@+
* Constant for confirmation status
*/
const KEY_SKU = 'sku';
const KEY_NAME = 'name';
const KEY_PRICE = 'price';
const KEY_CATEGORY_DESC = 'category_description';
const KEY_POSITION = 'position';
/**#@-*/

/**
* @inheritdoc
*/
public function getSku()

return $this->_get(self::KEY_SKU);


/**
* @inheritdoc
*/
public function getName()

return $this->_get(self::KEY_NAME);


/**
* @inheritdoc
*/
public function getPosition()

return $this->_get(self::KEY_POSITION);


/**
* @inheritdoc
*/
public function getPrice()

return $this->_get(self::KEY_PRICE);


/**
* @inheritdoc
*/
public function getCategoryDescription()

return $this->_get(self::KEY_CATEGORY_DESC);


/**
* @param string $sku
* @return $this
*/
public function setSku($sku)

return $this->setData(self::KEY_SKU, $sku);


/**
* @param string $name
* @return $this
*/
public function setName($name)

return $this->setData(self::KEY_NAME, $name);


/**
* @param int $position
* @return $this
*/
public function setPosition($position)

return $this->setData(self::KEY_POSITION, $position);


/**
* @param float $price
* @return $this
*/
public function setPrice($price)

return $this->setData(self::KEY_PRICE, $price);


/**
* @param string $description
* @return $this
*/
public function setCategoryDescription($description)

return $this->setData(self::KEY_CATEGORY_DESC, $description);





I hope this will help






share|improve this answer



























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f280966%2fmagento-2-how-to-create-custom-webapi%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    First you need to create webapi.xml under your custom module VendorModuleetc



    <route url="/V1/custom/:categoryId/products" method="GET">
    <service class="VendorModuleApiCategoryLinkManagementInterface" method="getAssignedProducts" />
    <resources>
    <resource ref="self"/>
    </resources>
    </route>


    – Route – This is the URL which will be used to call our API




    https://MagentoBaseURL/index.php/rest/V1/custom/categoryId/products




    – Service Class – This is the interface class of our API and the main method “getAssignedProducts” will be called with categoryId as the parameter



    – Resources- This defines who has the permission to call this API. It could be anonymous (everyone) or self (customer) or specific admin user with specific permission for example Vendor_Module::custom which can be added in acl.xml



    Lets now create the main interface file for your web API CategoryLinkManagementInterface.php under VendorModuleApi as specified in webapi.xml.



    <?php
    namespace VendorModuleApi;

    /**
    * @api
    */
    interface CategoryLinkManagementInterface

    /**
    * Get products assigned to a category
    *
    * @param int $categoryId
    * @return ScommerceCustomApiDataCategoryProductLinkInterface[]
    */
    public function getAssignedProducts($categoryId);



    In the above code, we have created an interface and define the main method i.e. getAssignedProducts as specified in webapi.xml. The other thing to notice here is the@return parameter which is the data interface VendorModuleApiDataCategoryProductLinkInterface[]. Will explain what is data interface in our next step.



    Based on the return parameter, let’s create our data interface CategoryProductLinkInterface.php under VendorModuleApiData



    <?php
    namespace VendorModuleApiData;

    /**
    * @api
    */
    interface CategoryProductLinkInterface

    /**
    * @return string


    The above data interface class allows you define the response/output of our API request, so as you can see this API will return sku, name, price, position and category description as an output.



    Now your interface files are created, let’s create our model classes where we can put the actual business logic, to do so we would need to specify this in our di.xml file under VendorModuleetc



    <config ...>
    <preference for="VendorModuleApiCategoryLinkManagementInterface" type="VendorModuleModelCategoryLinkManagement" />
    <preference for="VendorModuleApiDataCategoryProductLinkInterface" type="VendorModuleModelCategoryProductLink" />
    </config>


    In the above step, we have specified which model classes will be created against our interfaces to add our business logic.



    Let’s create our first model class CategoryLinkManagement.php under VendorModuleModel as specified in di.xml



    <?php
    namespace VendorModuleModel;

    /**
    * Class CategoryLinkManagement
    */
    class CategoryLinkManagement implements VendorModuleApiCategoryLinkManagementInterface

    /**
    * @var MagentoCatalogApiCategoryRepositoryInterface
    */
    protected $categoryRepository;

    /**
    * @var VendorModuleApiDataCategoryProductLinkInterfaceFactory
    */
    protected $productLinkFactory;

    /**
    * CategoryLinkManagement constructor.
    *
    * @param MagentoCatalogApiCategoryRepositoryInterface $categoryRepository
    * @param ScommerceCustomApiDataCategoryProductLinkInterfaceFactory $productLinkFactory
    */
    public function __construct(
    MagentoCatalogApiCategoryRepositoryInterface $categoryRepository,
    ScommerceCustomApiDataCategoryProductLinkInterfaceFactory $productLinkFactory
    )
    $this->categoryRepository = $categoryRepository;
    $this->productLinkFactory = $productLinkFactory;


    /**
    * @inheritdoc
    */
    public function getAssignedProducts($categoryId)

    $category = $this->categoryRepository->get($categoryId);
    if (!$category->getIsActive())
    return [[
    'error' => true,
    'error_desc' => 'Category is disabled'
    ]];

    $categoryDesc = $category->getDescription();

    /** @var MagentoCatalogModelResourceModelProductCollection $products */
    $products = $category->getProductCollection()
    ->addFieldToSelect('position')
    ->addFieldToSelect('name')
    ->addFieldToSelect('price');

    /** @var ScommerceCustomApiDataCategoryProductLinkInterface[] $links */
    $links = [];

    /** @var MagentoCatalogModelProduct $product */
    foreach ($products->getItems() as $product)
    /** @var ScommerceCustomApiDataCategoryProductLinkInterface $link */
    $link = $this->productLinkFactory->create();
    $link->setSku($product->getSku())
    ->setName($product->getName())
    ->setPrice($product->getFinalPrice())
    ->setPosition($product->getData('cat_index_position'))
    ->setCategoryDescription($categoryDesc);
    $links[] = $link;


    return $links;




    Lets now create our second model class CategoryProductLink.php under VendorModuleModel as specified in di.xml



    <?php
    namespace VendorModuleModel;

    /**
    * @codeCoverageIgnore
    */
    class CategoryProductLink implements VendorModuleApiDataCategoryProductLinkInterface

    /**#@+
    * Constant for confirmation status
    */
    const KEY_SKU = 'sku';
    const KEY_NAME = 'name';
    const KEY_PRICE = 'price';
    const KEY_CATEGORY_DESC = 'category_description';
    const KEY_POSITION = 'position';
    /**#@-*/

    /**
    * @inheritdoc
    */
    public function getSku()

    return $this->_get(self::KEY_SKU);


    /**
    * @inheritdoc
    */
    public function getName()

    return $this->_get(self::KEY_NAME);


    /**
    * @inheritdoc
    */
    public function getPosition()

    return $this->_get(self::KEY_POSITION);


    /**
    * @inheritdoc
    */
    public function getPrice()

    return $this->_get(self::KEY_PRICE);


    /**
    * @inheritdoc
    */
    public function getCategoryDescription()

    return $this->_get(self::KEY_CATEGORY_DESC);


    /**
    * @param string $sku
    * @return $this
    */
    public function setSku($sku)

    return $this->setData(self::KEY_SKU, $sku);


    /**
    * @param string $name
    * @return $this
    */
    public function setName($name)

    return $this->setData(self::KEY_NAME, $name);


    /**
    * @param int $position
    * @return $this
    */
    public function setPosition($position)

    return $this->setData(self::KEY_POSITION, $position);


    /**
    * @param float $price
    * @return $this
    */
    public function setPrice($price)

    return $this->setData(self::KEY_PRICE, $price);


    /**
    * @param string $description
    * @return $this
    */
    public function setCategoryDescription($description)

    return $this->setData(self::KEY_CATEGORY_DESC, $description);





    I hope this will help






    share|improve this answer





























      2














      First you need to create webapi.xml under your custom module VendorModuleetc



      <route url="/V1/custom/:categoryId/products" method="GET">
      <service class="VendorModuleApiCategoryLinkManagementInterface" method="getAssignedProducts" />
      <resources>
      <resource ref="self"/>
      </resources>
      </route>


      – Route – This is the URL which will be used to call our API




      https://MagentoBaseURL/index.php/rest/V1/custom/categoryId/products




      – Service Class – This is the interface class of our API and the main method “getAssignedProducts” will be called with categoryId as the parameter



      – Resources- This defines who has the permission to call this API. It could be anonymous (everyone) or self (customer) or specific admin user with specific permission for example Vendor_Module::custom which can be added in acl.xml



      Lets now create the main interface file for your web API CategoryLinkManagementInterface.php under VendorModuleApi as specified in webapi.xml.



      <?php
      namespace VendorModuleApi;

      /**
      * @api
      */
      interface CategoryLinkManagementInterface

      /**
      * Get products assigned to a category
      *
      * @param int $categoryId
      * @return ScommerceCustomApiDataCategoryProductLinkInterface[]
      */
      public function getAssignedProducts($categoryId);



      In the above code, we have created an interface and define the main method i.e. getAssignedProducts as specified in webapi.xml. The other thing to notice here is the@return parameter which is the data interface VendorModuleApiDataCategoryProductLinkInterface[]. Will explain what is data interface in our next step.



      Based on the return parameter, let’s create our data interface CategoryProductLinkInterface.php under VendorModuleApiData



      <?php
      namespace VendorModuleApiData;

      /**
      * @api
      */
      interface CategoryProductLinkInterface

      /**
      * @return string


      The above data interface class allows you define the response/output of our API request, so as you can see this API will return sku, name, price, position and category description as an output.



      Now your interface files are created, let’s create our model classes where we can put the actual business logic, to do so we would need to specify this in our di.xml file under VendorModuleetc



      <config ...>
      <preference for="VendorModuleApiCategoryLinkManagementInterface" type="VendorModuleModelCategoryLinkManagement" />
      <preference for="VendorModuleApiDataCategoryProductLinkInterface" type="VendorModuleModelCategoryProductLink" />
      </config>


      In the above step, we have specified which model classes will be created against our interfaces to add our business logic.



      Let’s create our first model class CategoryLinkManagement.php under VendorModuleModel as specified in di.xml



      <?php
      namespace VendorModuleModel;

      /**
      * Class CategoryLinkManagement
      */
      class CategoryLinkManagement implements VendorModuleApiCategoryLinkManagementInterface

      /**
      * @var MagentoCatalogApiCategoryRepositoryInterface
      */
      protected $categoryRepository;

      /**
      * @var VendorModuleApiDataCategoryProductLinkInterfaceFactory
      */
      protected $productLinkFactory;

      /**
      * CategoryLinkManagement constructor.
      *
      * @param MagentoCatalogApiCategoryRepositoryInterface $categoryRepository
      * @param ScommerceCustomApiDataCategoryProductLinkInterfaceFactory $productLinkFactory
      */
      public function __construct(
      MagentoCatalogApiCategoryRepositoryInterface $categoryRepository,
      ScommerceCustomApiDataCategoryProductLinkInterfaceFactory $productLinkFactory
      )
      $this->categoryRepository = $categoryRepository;
      $this->productLinkFactory = $productLinkFactory;


      /**
      * @inheritdoc
      */
      public function getAssignedProducts($categoryId)

      $category = $this->categoryRepository->get($categoryId);
      if (!$category->getIsActive())
      return [[
      'error' => true,
      'error_desc' => 'Category is disabled'
      ]];

      $categoryDesc = $category->getDescription();

      /** @var MagentoCatalogModelResourceModelProductCollection $products */
      $products = $category->getProductCollection()
      ->addFieldToSelect('position')
      ->addFieldToSelect('name')
      ->addFieldToSelect('price');

      /** @var ScommerceCustomApiDataCategoryProductLinkInterface[] $links */
      $links = [];

      /** @var MagentoCatalogModelProduct $product */
      foreach ($products->getItems() as $product)
      /** @var ScommerceCustomApiDataCategoryProductLinkInterface $link */
      $link = $this->productLinkFactory->create();
      $link->setSku($product->getSku())
      ->setName($product->getName())
      ->setPrice($product->getFinalPrice())
      ->setPosition($product->getData('cat_index_position'))
      ->setCategoryDescription($categoryDesc);
      $links[] = $link;


      return $links;




      Lets now create our second model class CategoryProductLink.php under VendorModuleModel as specified in di.xml



      <?php
      namespace VendorModuleModel;

      /**
      * @codeCoverageIgnore
      */
      class CategoryProductLink implements VendorModuleApiDataCategoryProductLinkInterface

      /**#@+
      * Constant for confirmation status
      */
      const KEY_SKU = 'sku';
      const KEY_NAME = 'name';
      const KEY_PRICE = 'price';
      const KEY_CATEGORY_DESC = 'category_description';
      const KEY_POSITION = 'position';
      /**#@-*/

      /**
      * @inheritdoc
      */
      public function getSku()

      return $this->_get(self::KEY_SKU);


      /**
      * @inheritdoc
      */
      public function getName()

      return $this->_get(self::KEY_NAME);


      /**
      * @inheritdoc
      */
      public function getPosition()

      return $this->_get(self::KEY_POSITION);


      /**
      * @inheritdoc
      */
      public function getPrice()

      return $this->_get(self::KEY_PRICE);


      /**
      * @inheritdoc
      */
      public function getCategoryDescription()

      return $this->_get(self::KEY_CATEGORY_DESC);


      /**
      * @param string $sku
      * @return $this
      */
      public function setSku($sku)

      return $this->setData(self::KEY_SKU, $sku);


      /**
      * @param string $name
      * @return $this
      */
      public function setName($name)

      return $this->setData(self::KEY_NAME, $name);


      /**
      * @param int $position
      * @return $this
      */
      public function setPosition($position)

      return $this->setData(self::KEY_POSITION, $position);


      /**
      * @param float $price
      * @return $this
      */
      public function setPrice($price)

      return $this->setData(self::KEY_PRICE, $price);


      /**
      * @param string $description
      * @return $this
      */
      public function setCategoryDescription($description)

      return $this->setData(self::KEY_CATEGORY_DESC, $description);





      I hope this will help






      share|improve this answer



























        2












        2








        2







        First you need to create webapi.xml under your custom module VendorModuleetc



        <route url="/V1/custom/:categoryId/products" method="GET">
        <service class="VendorModuleApiCategoryLinkManagementInterface" method="getAssignedProducts" />
        <resources>
        <resource ref="self"/>
        </resources>
        </route>


        – Route – This is the URL which will be used to call our API




        https://MagentoBaseURL/index.php/rest/V1/custom/categoryId/products




        – Service Class – This is the interface class of our API and the main method “getAssignedProducts” will be called with categoryId as the parameter



        – Resources- This defines who has the permission to call this API. It could be anonymous (everyone) or self (customer) or specific admin user with specific permission for example Vendor_Module::custom which can be added in acl.xml



        Lets now create the main interface file for your web API CategoryLinkManagementInterface.php under VendorModuleApi as specified in webapi.xml.



        <?php
        namespace VendorModuleApi;

        /**
        * @api
        */
        interface CategoryLinkManagementInterface

        /**
        * Get products assigned to a category
        *
        * @param int $categoryId
        * @return ScommerceCustomApiDataCategoryProductLinkInterface[]
        */
        public function getAssignedProducts($categoryId);



        In the above code, we have created an interface and define the main method i.e. getAssignedProducts as specified in webapi.xml. The other thing to notice here is the@return parameter which is the data interface VendorModuleApiDataCategoryProductLinkInterface[]. Will explain what is data interface in our next step.



        Based on the return parameter, let’s create our data interface CategoryProductLinkInterface.php under VendorModuleApiData



        <?php
        namespace VendorModuleApiData;

        /**
        * @api
        */
        interface CategoryProductLinkInterface

        /**
        * @return string


        The above data interface class allows you define the response/output of our API request, so as you can see this API will return sku, name, price, position and category description as an output.



        Now your interface files are created, let’s create our model classes where we can put the actual business logic, to do so we would need to specify this in our di.xml file under VendorModuleetc



        <config ...>
        <preference for="VendorModuleApiCategoryLinkManagementInterface" type="VendorModuleModelCategoryLinkManagement" />
        <preference for="VendorModuleApiDataCategoryProductLinkInterface" type="VendorModuleModelCategoryProductLink" />
        </config>


        In the above step, we have specified which model classes will be created against our interfaces to add our business logic.



        Let’s create our first model class CategoryLinkManagement.php under VendorModuleModel as specified in di.xml



        <?php
        namespace VendorModuleModel;

        /**
        * Class CategoryLinkManagement
        */
        class CategoryLinkManagement implements VendorModuleApiCategoryLinkManagementInterface

        /**
        * @var MagentoCatalogApiCategoryRepositoryInterface
        */
        protected $categoryRepository;

        /**
        * @var VendorModuleApiDataCategoryProductLinkInterfaceFactory
        */
        protected $productLinkFactory;

        /**
        * CategoryLinkManagement constructor.
        *
        * @param MagentoCatalogApiCategoryRepositoryInterface $categoryRepository
        * @param ScommerceCustomApiDataCategoryProductLinkInterfaceFactory $productLinkFactory
        */
        public function __construct(
        MagentoCatalogApiCategoryRepositoryInterface $categoryRepository,
        ScommerceCustomApiDataCategoryProductLinkInterfaceFactory $productLinkFactory
        )
        $this->categoryRepository = $categoryRepository;
        $this->productLinkFactory = $productLinkFactory;


        /**
        * @inheritdoc
        */
        public function getAssignedProducts($categoryId)

        $category = $this->categoryRepository->get($categoryId);
        if (!$category->getIsActive())
        return [[
        'error' => true,
        'error_desc' => 'Category is disabled'
        ]];

        $categoryDesc = $category->getDescription();

        /** @var MagentoCatalogModelResourceModelProductCollection $products */
        $products = $category->getProductCollection()
        ->addFieldToSelect('position')
        ->addFieldToSelect('name')
        ->addFieldToSelect('price');

        /** @var ScommerceCustomApiDataCategoryProductLinkInterface[] $links */
        $links = [];

        /** @var MagentoCatalogModelProduct $product */
        foreach ($products->getItems() as $product)
        /** @var ScommerceCustomApiDataCategoryProductLinkInterface $link */
        $link = $this->productLinkFactory->create();
        $link->setSku($product->getSku())
        ->setName($product->getName())
        ->setPrice($product->getFinalPrice())
        ->setPosition($product->getData('cat_index_position'))
        ->setCategoryDescription($categoryDesc);
        $links[] = $link;


        return $links;




        Lets now create our second model class CategoryProductLink.php under VendorModuleModel as specified in di.xml



        <?php
        namespace VendorModuleModel;

        /**
        * @codeCoverageIgnore
        */
        class CategoryProductLink implements VendorModuleApiDataCategoryProductLinkInterface

        /**#@+
        * Constant for confirmation status
        */
        const KEY_SKU = 'sku';
        const KEY_NAME = 'name';
        const KEY_PRICE = 'price';
        const KEY_CATEGORY_DESC = 'category_description';
        const KEY_POSITION = 'position';
        /**#@-*/

        /**
        * @inheritdoc
        */
        public function getSku()

        return $this->_get(self::KEY_SKU);


        /**
        * @inheritdoc
        */
        public function getName()

        return $this->_get(self::KEY_NAME);


        /**
        * @inheritdoc
        */
        public function getPosition()

        return $this->_get(self::KEY_POSITION);


        /**
        * @inheritdoc
        */
        public function getPrice()

        return $this->_get(self::KEY_PRICE);


        /**
        * @inheritdoc
        */
        public function getCategoryDescription()

        return $this->_get(self::KEY_CATEGORY_DESC);


        /**
        * @param string $sku
        * @return $this
        */
        public function setSku($sku)

        return $this->setData(self::KEY_SKU, $sku);


        /**
        * @param string $name
        * @return $this
        */
        public function setName($name)

        return $this->setData(self::KEY_NAME, $name);


        /**
        * @param int $position
        * @return $this
        */
        public function setPosition($position)

        return $this->setData(self::KEY_POSITION, $position);


        /**
        * @param float $price
        * @return $this
        */
        public function setPrice($price)

        return $this->setData(self::KEY_PRICE, $price);


        /**
        * @param string $description
        * @return $this
        */
        public function setCategoryDescription($description)

        return $this->setData(self::KEY_CATEGORY_DESC, $description);





        I hope this will help






        share|improve this answer















        First you need to create webapi.xml under your custom module VendorModuleetc



        <route url="/V1/custom/:categoryId/products" method="GET">
        <service class="VendorModuleApiCategoryLinkManagementInterface" method="getAssignedProducts" />
        <resources>
        <resource ref="self"/>
        </resources>
        </route>


        – Route – This is the URL which will be used to call our API




        https://MagentoBaseURL/index.php/rest/V1/custom/categoryId/products




        – Service Class – This is the interface class of our API and the main method “getAssignedProducts” will be called with categoryId as the parameter



        – Resources- This defines who has the permission to call this API. It could be anonymous (everyone) or self (customer) or specific admin user with specific permission for example Vendor_Module::custom which can be added in acl.xml



        Lets now create the main interface file for your web API CategoryLinkManagementInterface.php under VendorModuleApi as specified in webapi.xml.



        <?php
        namespace VendorModuleApi;

        /**
        * @api
        */
        interface CategoryLinkManagementInterface

        /**
        * Get products assigned to a category
        *
        * @param int $categoryId
        * @return ScommerceCustomApiDataCategoryProductLinkInterface[]
        */
        public function getAssignedProducts($categoryId);



        In the above code, we have created an interface and define the main method i.e. getAssignedProducts as specified in webapi.xml. The other thing to notice here is the@return parameter which is the data interface VendorModuleApiDataCategoryProductLinkInterface[]. Will explain what is data interface in our next step.



        Based on the return parameter, let’s create our data interface CategoryProductLinkInterface.php under VendorModuleApiData



        <?php
        namespace VendorModuleApiData;

        /**
        * @api
        */
        interface CategoryProductLinkInterface

        /**
        * @return string


        The above data interface class allows you define the response/output of our API request, so as you can see this API will return sku, name, price, position and category description as an output.



        Now your interface files are created, let’s create our model classes where we can put the actual business logic, to do so we would need to specify this in our di.xml file under VendorModuleetc



        <config ...>
        <preference for="VendorModuleApiCategoryLinkManagementInterface" type="VendorModuleModelCategoryLinkManagement" />
        <preference for="VendorModuleApiDataCategoryProductLinkInterface" type="VendorModuleModelCategoryProductLink" />
        </config>


        In the above step, we have specified which model classes will be created against our interfaces to add our business logic.



        Let’s create our first model class CategoryLinkManagement.php under VendorModuleModel as specified in di.xml



        <?php
        namespace VendorModuleModel;

        /**
        * Class CategoryLinkManagement
        */
        class CategoryLinkManagement implements VendorModuleApiCategoryLinkManagementInterface

        /**
        * @var MagentoCatalogApiCategoryRepositoryInterface
        */
        protected $categoryRepository;

        /**
        * @var VendorModuleApiDataCategoryProductLinkInterfaceFactory
        */
        protected $productLinkFactory;

        /**
        * CategoryLinkManagement constructor.
        *
        * @param MagentoCatalogApiCategoryRepositoryInterface $categoryRepository
        * @param ScommerceCustomApiDataCategoryProductLinkInterfaceFactory $productLinkFactory
        */
        public function __construct(
        MagentoCatalogApiCategoryRepositoryInterface $categoryRepository,
        ScommerceCustomApiDataCategoryProductLinkInterfaceFactory $productLinkFactory
        )
        $this->categoryRepository = $categoryRepository;
        $this->productLinkFactory = $productLinkFactory;


        /**
        * @inheritdoc
        */
        public function getAssignedProducts($categoryId)

        $category = $this->categoryRepository->get($categoryId);
        if (!$category->getIsActive())
        return [[
        'error' => true,
        'error_desc' => 'Category is disabled'
        ]];

        $categoryDesc = $category->getDescription();

        /** @var MagentoCatalogModelResourceModelProductCollection $products */
        $products = $category->getProductCollection()
        ->addFieldToSelect('position')
        ->addFieldToSelect('name')
        ->addFieldToSelect('price');

        /** @var ScommerceCustomApiDataCategoryProductLinkInterface[] $links */
        $links = [];

        /** @var MagentoCatalogModelProduct $product */
        foreach ($products->getItems() as $product)
        /** @var ScommerceCustomApiDataCategoryProductLinkInterface $link */
        $link = $this->productLinkFactory->create();
        $link->setSku($product->getSku())
        ->setName($product->getName())
        ->setPrice($product->getFinalPrice())
        ->setPosition($product->getData('cat_index_position'))
        ->setCategoryDescription($categoryDesc);
        $links[] = $link;


        return $links;




        Lets now create our second model class CategoryProductLink.php under VendorModuleModel as specified in di.xml



        <?php
        namespace VendorModuleModel;

        /**
        * @codeCoverageIgnore
        */
        class CategoryProductLink implements VendorModuleApiDataCategoryProductLinkInterface

        /**#@+
        * Constant for confirmation status
        */
        const KEY_SKU = 'sku';
        const KEY_NAME = 'name';
        const KEY_PRICE = 'price';
        const KEY_CATEGORY_DESC = 'category_description';
        const KEY_POSITION = 'position';
        /**#@-*/

        /**
        * @inheritdoc
        */
        public function getSku()

        return $this->_get(self::KEY_SKU);


        /**
        * @inheritdoc
        */
        public function getName()

        return $this->_get(self::KEY_NAME);


        /**
        * @inheritdoc
        */
        public function getPosition()

        return $this->_get(self::KEY_POSITION);


        /**
        * @inheritdoc
        */
        public function getPrice()

        return $this->_get(self::KEY_PRICE);


        /**
        * @inheritdoc
        */
        public function getCategoryDescription()

        return $this->_get(self::KEY_CATEGORY_DESC);


        /**
        * @param string $sku
        * @return $this
        */
        public function setSku($sku)

        return $this->setData(self::KEY_SKU, $sku);


        /**
        * @param string $name
        * @return $this
        */
        public function setName($name)

        return $this->setData(self::KEY_NAME, $name);


        /**
        * @param int $position
        * @return $this
        */
        public function setPosition($position)

        return $this->setData(self::KEY_POSITION, $position);


        /**
        * @param float $price
        * @return $this
        */
        public function setPrice($price)

        return $this->setData(self::KEY_PRICE, $price);


        /**
        * @param string $description
        * @return $this
        */
        public function setCategoryDescription($description)

        return $this->setData(self::KEY_CATEGORY_DESC, $description);





        I hope this will help







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jul 5 at 12:07

























        answered Jul 5 at 12:02









        Muhammad HashamMuhammad Hasham

        5,43910 gold badges31 silver badges80 bronze badges




        5,43910 gold badges31 silver badges80 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f280966%2fmagento-2-how-to-create-custom-webapi%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Grendel Contents Story Scholarship Depictions Notes References Navigation menu10.1093/notesj/gjn112Berserkeree

            Area configuration aggregation error after install Porto themeMagento 2.1 CE Installed but front/backend not loading/workingCSS not loading on page within Magento 2 pageCannot install module in Magento 2no commands defined in the “setup” namespace. in Magento2Magento 2: Static files are present but shows 404Why do i have to always run the commands to clean cache in Magento 2.1.8?Failure reason: 'Unable to unserialize value.'Error 500 after magento migrationIn production mode the site does not loadMagento 2 : Error 500 after installing

            Middle Expansion Olielle Resaix Definition: Uttering songs of triumph shouting with joy triumphant exulting Sejunction Journal 붙다 달 고급 품목 외출 The stretch trades the screeching tin. Definition: The act of speaking with a drawl a drawl Cough Sand Definition: An uproar a quarrel a noisy outbreak Shake Iron Publicize Horse House Baby 사과 Resaix Flaggy Jelly Temporary Unequaled Puppet A drop in the bucket Shrew 성격 회원 성질 미팅 The burn frames the tacky quality. Materialistic The smoke reduces the way. Yammoe Nondescript Cheek 얼굴 배 약하다 날리다 타다 The illegal country shows the iron. Help Rule Drearien Smoke Teaching Meaty Wasp Abraham Lincoln Jaws 진심 수리하다 Size Cork Idea Convert Think Lark John Lennon 거울 청소 군 추천하다 아이스크림