Magento 2 Custom GET REST API ready store code from url
-
14-04-2021 - |
Frage
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!
Lösung
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();
....
}
Andere Tipps
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>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit magento.stackexchange