1

I have a custom REST API url:

<route url="/V1/vendor/module/id/:Id" method="GET">
        <service class="Vendor\Module\Api\ModuleRepositoryInterface" method="get"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>

my get method the same as Magento/Catalog : CategoryRepository

GET URL: ...rest/en_gb/V1/vendor/module/id/1

public function get($id, $storeId = null )
    {
        print_r($id);//OK This prints id = 1
        print_r($storeId);die; //NOT printing `en_gb` or store id
        $cacheKey = $storeId ?? 'all';
        if (!isset($this->instances[$categoryId][$cacheKey])) {
            /** @var Category $category */
            $category = $this->categoryFactory->create();
            if (null !== $storeId) {
                $category->setStoreId($storeId);
            }
            $category->load($categoryId);
            if (!$category->getId()) {
                throw NoSuchEntityException::singleField('id', $categoryId);
            }
            $this->instances[$categoryId][$cacheKey] = $category;
        }
        return $this->instances[$categoryId][$cacheKey];
    }

This ?storeId=1 works but it's not as is called in API Native Magento Module/Catalog:

Any Ideas Anyone? Appreciated!

2 Answers 2

5

Your class should have an instance of \Magento\Store\Model\StoreManagerInterface as a dependency that will give you the current store and id.

private $storeManager;
public function __construct(
    ...
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    ...
) {
    ...
    $this->storeManager = $storeManager;
    ....
}

public function get($id, $storeId = null)
{
    $storeId = $storeId ?? $this->storeManager->getStore()->getId();
    ....
}
1
  • Awesome thx that works :) ! Commented Jun 9, 2020 at 12:30
0

change in xml code with this

<route url="/V1/vendor/module/id/:Id/store_id/:storeId" method="GET">
    <service class="Vendor\Module\Api\ModuleRepositoryInterface" method="get"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.