To create a custom API for fetching a category list without requiring an access token in a Spryker-based project, you can follow these steps to create the necessary files and structure for your custom module. Below is a detailed guide for each part of the module and its purpose.
Step 1: Create Custom Category API Module
Your module will be located in the src/Pyz/Glue/CustomCategoryApi directory. The goal is to create a module that exposes an API endpoint for fetching the category list. Here’s how to structure it.
- CustomCategoryApiFactory.php
- CustomCategoryApiDependencyProvider.php
- CustomCategoryReader.php
- CustomCategoryApiResourcePlugin.php
- CustomCategoryResourceController.php
- custom_category.transfer.xml
- GlueApplicationDependencyProvider.php
This file is the factory class for your custom API module. It will be responsible for creating instances of the processors and plugins required for the API functionality.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php namespace Pyz\Glue\CustomCategoryApi; use Pyz\Glue\CustomCategoryApi\Processor\CustomCategoryReader; use Spryker\Client\CategoryStorage\CategoryStorageClientInterface; use Spryker\Client\Store\StoreClientInterface; use Spryker\Client\Locale\LocaleClientInterface; use Spryker\Glue\GlueApplication\Rest\JsonApi\RestResourceBuilderInterface; use Spryker\Glue\Kernel\AbstractFactory; class CustomCategoryApiFactory extends AbstractFactory { public function createCustomCategoryReader(): CustomCategoryReader { return new CustomCategoryReader( $this->getCategoryStorageClient(), $this->getRestResourceBuilder(), $this->getStoreClient(), $this->getLocaleClient() ); } protected function getCategoryStorageClient(): CategoryStorageClientInterface { return $this->getProvidedDependency(CustomCategoryApiDependencyProvider::CLIENT_CATEGORY_STORAGE); } protected function getRestResourceBuilder(): RestResourceBuilderInterface { return $this->getProvidedDependency(CustomCategoryApiDependencyProvider::RESOURCE_BUILDER); } protected function getStoreClient(): StoreClientInterface { return $this->getProvidedDependency(CustomCategoryApiDependencyProvider::STORE_CLIENT); } protected function getLocaleClient(): LocaleClientInterface { return $this->getProvidedDependency(CustomCategoryApiDependencyProvider::LOCALE_CLIENT); } } ?> |
This file will define the dependencies that your API will rely on. It allows you to define things like services and other modules that your custom API depends on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
<?php namespace Pyz\Glue\CustomCategoryApi; use Spryker\Client\CategoryStorage\CategoryStorageClientInterface; use Spryker\Client\Store\StoreClientInterface; use Spryker\Client\Locale\LocaleClientInterface; use Spryker\Glue\GlueApplication\Rest\JsonApi\RestResourceBuilder; use Spryker\Glue\GlueApplication\Rest\JsonApi\RestResourceBuilderInterface; use Spryker\Glue\Kernel\AbstractBundleDependencyProvider; use Spryker\Glue\Kernel\Container; class CustomCategoryApiDependencyProvider extends AbstractBundleDependencyProvider { public const CLIENT_CATEGORY_STORAGE = 'CLIENT_CATEGORY_STORAGE'; public const RESOURCE_BUILDER = 'RESOURCE_BUILDER'; public const STORE_CLIENT = 'STORE_CLIENT'; public const LOCALE_CLIENT = 'LOCALE_CLIENT'; /** * @param \Spryker\Glue\Kernel\Container $container * * @return \Spryker\Glue\Kernel\Container */ public function provideDependencies(Container $container): Container { $container = parent::provideDependencies($container); $container = $this->addCategoryStorageClient($container); $container = $this->addRestResourceBuilder($container); $container = $this->addStoreClient($container); $container = $this->addLocaleClient($container); return $container; } /** * @param \Spryker\Glue\Kernel\Container $container * * @return \Spryker\Glue\Kernel\Container */ protected function addCategoryStorageClient(Container $container): Container { $container->set(static::CLIENT_CATEGORY_STORAGE, function (Container $container): CategoryStorageClientInterface { return $container->getLocator()->categoryStorage()->client(); }); return $container; } /** * @param \Spryker\Glue\Kernel\Container $container * * @return \Spryker\Glue\Kernel\Container */ protected function addRestResourceBuilder(Container $container): Container { $container->set(static::RESOURCE_BUILDER, function (Container $container): RestResourceBuilderInterface { return new RestResourceBuilder(); }); return $container; } protected function addStoreClient(Container $container): Container { $container->set(static::STORE_CLIENT, function (Container $container): StoreClientInterface { return $container->getLocator()->store()->client(); }); return $container; } protected function addLocaleClient(Container $container): Container { $container->set(static::LOCALE_CLIENT, function (Container $container): LocaleClientInterface { return $container->getLocator()->locale()->client(); }); return $container; } } ?> |
This file will handle the logic of fetching categories. It will interact with the business layer and return the response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<?php namespace Pyz\Glue\CustomCategoryApi\Processor; use Spryker\Client\CategoryStorage\CategoryStorageClientInterface; use Spryker\Glue\GlueApplication\Rest\JsonApi\RestResponseInterface; use Spryker\Glue\GlueApplication\Rest\JsonApi\RestResourceBuilderInterface; use Spryker\Glue\GlueApplication\Rest\JsonApi\RestResourceInterface; use Generated\Shared\Transfer\RestCustomCategoryAttributesTransfer; // Import the Transfer Object use Spryker\Client\Store\StoreClientInterface; use Spryker\Client\Locale\LocaleClientInterface; class CustomCategoryReader { protected CategoryStorageClientInterface $categoryStorageClient; protected RestResourceBuilderInterface $restResourceBuilder; protected StoreClientInterface $storeClient; protected LocaleClientInterface $localeClient; public function __construct( CategoryStorageClientInterface $categoryStorageClient, RestResourceBuilderInterface $restResourceBuilder, StoreClientInterface $storeClient, LocaleClientInterface $localeClient, ) { $this->categoryStorageClient = $categoryStorageClient; $this->restResourceBuilder = $restResourceBuilder; $this->storeClient = $storeClient; $this->localeClient = $localeClient; } public function getCategoryTree(): RestResponseInterface { $storeName = $this->storeClient->getCurrentStore()->getName(); $localeName = $this->localeClient->getCurrentLocale(); $categoryTree = $this->categoryStorageClient->getCategories($localeName, $storeName); $categoryTreeArray = $categoryTree->getArrayCopy(); // Convert ArrayObject to array // Create a transfer object and populate it $categoryAttributesTransfer = new RestCustomCategoryAttributesTransfer(); $categoryAttributesTransfer->setCategoryNodesStorage(new \ArrayObject($this->formatCategories($categoryTreeArray))); // Build a REST resource with the transfer object $restResource = $this->restResourceBuilder->createRestResource( 'custom-category-trees', null, $categoryAttributesTransfer ); // Create a response and add the resource return $this->restResourceBuilder->createRestResponse()->addResource($restResource); } protected function formatCategories($categories): array { if ($categories instanceof \ArrayObject) { $categories = $categories->getArrayCopy(); } $formattedCategories = []; foreach ($categories as $category) { // Check if 'idCategoryNode' exists in the data if (isset($category['idCategory'])) { $formattedCategories[] = [ 'nodeId' => $category['idCategory'], // Accessing the field correctly 'order' => $category['order'], 'name' => $category['name'], 'url' => $category['url'], 'children' => $this->formatCategories($category['children'] ?? []) ]; } else { // Handle the case where 'idCategoryNode' does not exist \Spryker\Shared\Log\Logger::error('Missing idCategoryNode in category data: ' . print_r($category, true)); } } // Return as a regular array, not ArrayObject return $formattedCategories; // Keep this as an array } } ?> |
This file is a plugin for the Glue application, responsible for formatting the response from the CustomCategoryReader.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?php namespace Pyz\Glue\CustomCategoryApi\Plugin\GlueApplication; use Spryker\Glue\Kernel\AbstractPlugin; use Spryker\Glue\GlueApplicationExtension\Dependency\Plugin\ResourceRoutePluginInterface; use Spryker\Glue\GlueApplicationExtension\Dependency\Plugin\ResourceRouteCollectionInterface; use Generated\Shared\Transfer\RestCustomCategoryAttributesTransfer; use Pyz\Glue\CustomCategoryApi\Processor\CustomCategoryReader; /** * @method \Pyz\Glue\CustomCategoryApi\CustomCategoryApiFactory getFactory() */ class CustomCategoryApiResourcePlugin extends AbstractPlugin implements ResourceRoutePluginInterface { /** * {@inheritDoc} */ public function configure(ResourceRouteCollectionInterface $resourceRouteCollection): ResourceRouteCollectionInterface { return $resourceRouteCollection->addGet('get', false); } /** * {@inheritDoc} */ public function getResourceType(): string { return 'custom-category-trees'; } /** * {@inheritDoc} */ public function getController(): string { return 'custom-category-resource'; } /** * {@inheritDoc} */ public function getResourceAttributesClassName(): string { return RestCustomCategoryAttributesTransfer::class; } /** * {@inheritDoc} */ public function get(): array { return $this->getFactory()->createCustomCategoryReader()->getCategoryTree(); } } ?> |
This file will define the controller for the custom category API resource. It will use the plugin to handle incoming requests and return responses.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php namespace Pyz\Glue\CustomCategoryApi\Controller; use Spryker\Glue\GlueApplication\Rest\JsonApi\RestResponseInterface; use Spryker\Glue\GlueApplication\Rest\Request\Data\RestRequestInterface; use Pyz\Glue\CustomCategoryApi\Processor\CustomCategoryReader; use Spryker\Glue\Kernel\Controller\AbstractController; /** * @method \Pyz\Glue\CustomCategoryApi\CustomCategoryApiFactory getFactory() */ class CustomCategoryResourceController extends AbstractController { /** * @param \Spryker\Glue\GlueApplication\Rest\Request\Data\RestRequestInterface $restRequest * @return \Spryker\Glue\GlueApplication\Rest\JsonApi\RestResponseInterface */ public function getAction(RestRequestInterface $restRequest): RestResponseInterface { return $this->getFactory() ->createCustomCategoryReader() ->getCategoryTree(); } } ?> |
This file defines the structure of the transfer objects used for categories. It will include attributes like id, name, and others that you wish to include.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<?xml version="1.0"?> <transfers xmlns="spryker:transfer-01" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="spryker:transfer-01 http://static.spryker.com/transfer-01.xsd"> <transfer name="RestCustomCategoryAttributesTransfer"> <property name="categoryNodesStorage" type="RestCategoryTreesAttributes[]" singular="categoryNodesStorage"/> </transfer> <transfer name="RestCategoryTreesAttributes"> <property name="nodeId" type="int"/> <property name="order" type="int"/> <property name="name" type="string"/> <property name="children" type="RestCategoryTreesAttributes[]" singular="children"/> <property name="url" type="string"/> </transfer> <transfer name="RestCategoryNodesAttributes"> <property name="nodeId" type="int"/> <property name="name" type="string"/> <property name="metaTitle" type="string"/> <property name="metaKeywords" type="string"/> <property name="metaDescription" type="string"/> <property name="isActive" type="bool"/> <property name="children" type="RestCategoryNodesAttributes[]" singular="children"/> <property name="parents" type="RestCategoryNodesAttributes[]" singular="parents"/> <property name="order" type="int"/> <property name="url" type="string"/> </transfer> <transfer name="CategoryNodeStorage"> <property name="idCategory" type="int"/> <property name="nodeId" type="int"/> </transfer> <transfer name="RestErrorMessage"> <property name="status" type="int"/> <property name="code" type="string"/> <property name="detail" type="string"/> </transfer> <transfer name="UrlStorage"> <property name="fkResourceCategorynode" type="int"/> <property name="localeName" type="string"/> <property name="localeUrls" type="UrlStorage[]" singular="urlStorage"/> <property name="fkLocale" type="int"/> </transfer> <transfer name="RestUrlResolverAttributes"> <property name="entityType" type="string"/> <property name="entityId" type="string"/> </transfer> <transfer name="Store"> <property name="name" type="string"/> </transfer> </transfers> |
This file is where you register the necessary resources for the Glue application to use. If your custom category API uses any specific services or dependencies, you can add them here.
src/Pyz/Glue/GlueApplication/GlueApplicationDependencyProvider.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php namespace Pyz\Glue\GlueApplication; use Pyz\Glue\CustomCategoryApi\Plugin\GlueApplication\CustomCategoryApiResourcePlugin; use Spryker\Glue\GlueApplication\GlueApplicationDependencyProvider as SprykerGlueApplicationDependencyProvider; class GlueApplicationDependencyProvider extends SprykerGlueApplicationDependencyProvider { protected function getResourceRoutePlugins(): array { return [ new CustomCategoryApiResourcePlugin(), ]; } } ?> |
Step 8: Generate Transfer Objects and Clear Cache
Run the following command to clear caches:
docker/sdk cli
console transfer:generate
console cache:empty-all
Step 9: Custom Category API
Api Endpoint:
http://glue.eu.spryker.local/custom-category-trees
Method
GET
Response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
{ "data": [ { "type": "custom-category-trees", "id": null, "attributes": { "categoryNodesStorage": [ { "nodeId": 38, "order": 80, "name": "Cables", "url": "/en/cables", "children": [] }, { "nodeId": 35, "order": 50, "name": "Foods", "url": "/en/foods", "children": [ { "nodeId": 36, "order": 50, "name": "Fish", "url": "/en/foods/fish", "children": [] }, { "nodeId": 37, "order": 50, "name": "Vegetables", "url": "/en/foods/vegetables", "children": [] } ] }, { "nodeId": 2, "order": 40, "name": "Stationery", "url": "/en/stationery", "children": [ { "nodeId": 3, "order": 20, "name": "Writing Materials", "url": "/en/stationery/writing-materials", "children": [ { "nodeId": 4, "order": 30, "name": "Pens", "url": "/en/stationery/writing-materials/pens", "children": [] }, { "nodeId": 5, "order": 20, "name": "Markers & Highlighters", "url": "/en/stationery/writing-materials/markers-&-highlighters", "children": [] }, { "nodeId": 6, "order": 10, "name": "Pencils & Chalk", "url": "/en/stationery/writing-materials/pencils-&-chalk", "children": [] } ] }, { "nodeId": 7, "order": 10, "name": "Paper", "url": "/en/stationery/paper", "children": [ { "nodeId": 8, "order": 30, "name": "Blocks & Notebooks", "url": "/en/stationery/paper/blocks-&-notebooks", "children": [] }, { "nodeId": 9, "order": 20, "name": "Copy Paper", "url": "/en/stationery/paper/copy-paper", "children": [] }, { "nodeId": 10, "order": 10, "name": "Sticky Notes", "url": "/en/stationery/paper/sticky-notes", "children": [] } ] } ] }, { "nodeId": 11, "order": 30, "name": "Office furniture", "url": "/en/office-furniture", "children": [ { "nodeId": 12, "order": 30, "name": "Chairs", "url": "/en/office-furniture/chairs", "children": [ { "nodeId": 13, "order": 30, "name": "Office Chairs", "url": "/en/office-furniture/chairs/office-chairs", "children": [] }, { "nodeId": 14, "order": 20, "name": "Swivel Chairs", "url": "/en/office-furniture/chairs/swivel-chairs", "children": [] }, { "nodeId": 15, "order": 10, "name": "Armchair", "url": "/en/office-furniture/chairs/armchair", "children": [] } ] }, { "nodeId": 16, "order": 20, "name": "Tables", "url": "/en/office-furniture/tables", "children": [ { "nodeId": 17, "order": 30, "name": "Conference Tables", "url": "/en/office-furniture/tables/conference-tables", "children": [] }, { "nodeId": 18, "order": 20, "name": "Desks", "url": "/en/office-furniture/tables/desks", "children": [] }, { "nodeId": 19, "order": 10, "name": "Podiums", "url": "/en/office-furniture/tables/podiums", "children": [] } ] }, { "nodeId": 20, "order": 10, "name": "Storage", "url": "/en/office-furniture/storage", "children": [ { "nodeId": 21, "order": 20, "name": "Universal Cabinets", "url": "/en/office-furniture/storage/universal-cabinets", "children": [] }, { "nodeId": 22, "order": 10, "name": "Lockers", "url": "/en/office-furniture/storage/lockers", "children": [] } ] } ] }, { "nodeId": 23, "order": 20, "name": "Office equipment", "url": "/en/office-equipment", "children": [ { "nodeId": 24, "order": 40, "name": "Shredder", "url": "/en/office-equipment/shredder", "children": [] }, { "nodeId": 25, "order": 30, "name": "Money Counters and Validators", "url": "/en/office-equipment/money-counters-and-validators", "children": [] }, { "nodeId": 26, "order": 20, "name": "Flipcharts", "url": "/en/office-equipment/flipcharts", "children": [] }, { "nodeId": 27, "order": 10, "name": "Computer Accessories", "url": "/en/office-equipment/computer-accessories", "children": [ { "nodeId": 28, "order": 30, "name": "Keyboards & Mice", "url": "/en/office-equipment/computer-accessories/keyboards-&-mice", "children": [] }, { "nodeId": 29, "order": 20, "name": "USB Sticks & SD Cards", "url": "/en/office-equipment/computer-accessories/usb-sticks-&-sd-cards", "children": [] }, { "nodeId": 30, "order": 10, "name": "Cables", "url": "/en/office-equipment/computer-accessories/cables", "children": [] } ] } ] }, { "nodeId": 31, "order": 10, "name": "Transport", "url": "/en/transport", "children": [ { "nodeId": 32, "order": 20, "name": "Lift Carts", "url": "/en/transport/lift-carts", "children": [] }, { "nodeId": 33, "order": 10, "name": "Sack Trucks", "url": "/en/transport/sack-trucks", "children": [] } ] } ] }, "links": { "self": "http://glue.eu.spryker.local/custom-category-trees" } } ], "links": { "self": "http://glue.eu.spryker.local/custom-category-trees" } } |
Step 10: No Access Token
Since you requested that the API should not require an access token, ensure that your controller or resource doesn’t enforce authentication middleware. If the default authentication mechanisms are enabled, you’ll need to override or disable them for this specific API endpoint.
Conclusion
Once you’ve created these files and registered them in your Spryker application, you can access the custom category list via an endpoint like /custom-category without requiring an access token. You may also customize the category response format and logic to meet the requirements of your application.
bluethinkinc_blog
2025-03-28