Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 30 ยท APIs

Custom Store API Routes

Build a custom Shopware 6 Store API route with the abstract route pattern, getDecorated(), sales channel context, responses and cache invalidation.

Shopware 6 has two HTTP APIs. The Admin API is for back-office tools and integrations (the next lessons cover it). The Store API is the public, sales-channel-aware API that the storefront, mobile apps and headless front ends call to browse products, manage a cart and check out. When your plugin owns data that a shop front end must read or change, such as a wishlist, a store locator or product badges, you add your own Store API route.

This lesson shows the pattern the core itself uses: an abstract route class, one concrete implementation, a response object, and a way to cache and decorate it. The real Shopware code is read-only, because Shopware cannot run on this site. The runnable examples are PHP stand-ins that reproduce the structure with a tiny router and JSON output, and each one says what is simplified. You should know services and decoration from Services and the Dependency Injection Container and entity reads from Reading and Writing with Repositories.

The abstract route pattern

Almost every Store API route in the core comes as three parts:

  1. An abstract class (AbstractBadgeRoute) that defines the contract and one method, getDecorated().
  2. A concrete class (BadgeRoute) with the real work and the HTTP route attribute.
  3. A response class (BadgeRouteResponse) that wraps the result and extends StoreApiResponse.

Why an abstract class and not an interface? The core wants other plugins to decorate a route: wrap it to add caching, logging or extra data, without editing its code. Each decorator holds the next route in the chain, and getDecorated() returns that inner route. The abstract class forces every implementation to answer the question "who do you wrap?". The innermost implementation throws an exception, because it has nothing to wrap.

flowchart LR
    C["Controller or HTTP kernel"] --> D2["CachedBadgeRoute<br/>(decorator)"]
    D2 -->|"cache miss"| D1["BadgeRoute<br/>(core implementation)"]
    D1 --> R["Repository"]
    D2 -.->|"getDecorated()"| D1

A request enters the outermost decorator; on a cache miss it falls through to the real implementation.

The abstract class (read-only):

PHP
namespace Acme\Badges\Store\Route;

use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\SalesChannel\SalesChannelContext;

abstract class AbstractBadgeRoute
{
    abstract public function getDecorated(): AbstractBadgeRoute;

    abstract public function load(Criteria $criteria, SalesChannelContext $context): BadgeRouteResponse;
}

The concrete route (read-only):

PHP
use Shopware\Core\Framework\Routing\StoreApiRouteScope;
use Shopware\Core\PlatformRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

#[Route(defaults: [PlatformRequest::ATTRIBUTE_ROUTE_SCOPE => [StoreApiRouteScope::ID]])]
class BadgeRoute extends AbstractBadgeRoute
{
    public function __construct(
        private readonly SalesChannelRepository $badgeRepository,
    ) {
    }

    public function getDecorated(): AbstractBadgeRoute
    {
        throw new DecorationPatternException(self::class);
    }

    #[Route(path: '/store-api/acme/badge', name: 'store-api.acme.badge.search', methods: ['GET', 'POST'])]
    public function load(Criteria $criteria, SalesChannelContext $context): BadgeRouteResponse
    {
        $result = $this->badgeRepository->search($criteria, $context);

        return new BadgeRouteResponse($result);
    }
}

A few points deserve attention:

  • The route scope default (store-api) tells Shopware to run this route through the Store API pipeline: it checks the sw-access-key header, resolves the sales channel and builds a SalesChannelContext. Without the scope, the route behaves like an ordinary Symfony route.
  • Route paths start with /store-api/. Use your vendor name in the path (/store-api/acme/badge) so you never collide with another plugin or a future core route.
  • Route names are global. The convention store-api.<vendor>.<thing>.<action> keeps them unique.
  • The route file is loaded through Resources/config/routes.xml, which points at the directory of controller classes. Check the file layout of your target version; the core and the plugin skeletons show the exact syntax.
  • SalesChannelContext carries the current sales channel, currency, language, customer (if logged in), tax rules and context token. Use it instead of reading Request data yourself. Criteria for reading entities are the same object you know from the DAL, but the SalesChannelRepository also applies sales-channel rules, such as hiding inactive or not visible products.

The response object

StoreApiResponse wraps a Struct (most often an EntitySearchResult or a custom struct) and turns it into JSON. A typical response class is nearly empty (read-only):

PHP
use Shopware\Core\System\SalesChannel\StoreApiResponse;

class BadgeRouteResponse extends StoreApiResponse
{
    /** @var EntitySearchResult<BadgeCollection> */
    protected $object;

    public function getBadges(): BadgeCollection
    {
        return $this->object->getEntities();
    }
}

Giving the response a typed getter matters, because decorators and other PHP callers use it instead of parsing JSON. The JSON shape is created by Shopware's serializer from the struct; expect fields like elements, total and aggregations for search results. Treat that shape as a public contract once your route is released: adding fields is safe, removing or renaming them breaks front ends.

A stand-in router

The first stand-in builds the same three-part structure with plain PHP: an abstract route, a concrete route, a response that encodes JSON, and a minimal router that matches paths. It is real in its structure; the router, context object and array "repository" are simplified inventions.

PHP Abstract route, response and a tiny router

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Change the sales channel in the second call and watch the result change: the same route returns different data per channel, which is the whole point of passing the context along.

Registering the route as a service

The route class is a normal service in services.xml. Controllers in Shopware are public services; for Store API route classes the route attribute is picked up when the class is registered with the controller tag or lives in a controller-scanned folder. Follow the skeleton of your Shopware version for the exact tag (read-only):

XML
<service id="Acme\Badges\Store\Route\BadgeRoute" public="true">
    <argument type="service" id="sales_channel.acme_badge.repository"/>
</service>

The repository id sales_channel.<entity>.repository exists for entities that have a sales-channel-aware definition. If your entity is not exposed to sales channels, you must register that variant yourself or use the plain repository, and then you are responsible for the visibility rules. A common security bug is to use the plain repository in a public route and leak data from other customers or channels. See Security and Performance.

Decorating a route and caching

Because the route is abstract, a plugin can wrap it. A decorator receives the inner route in its constructor, returns it from getDecorated() and forwards or changes load() (read-only):

PHP
class CachedBadgeRoute extends AbstractBadgeRoute
{
    public function __construct(
        private readonly AbstractBadgeRoute $inner,
        private readonly CacheInterface $cache,
    ) {
    }

    public function getDecorated(): AbstractBadgeRoute
    {
        return $this->inner;
    }

    public function load(Criteria $criteria, SalesChannelContext $context): BadgeRouteResponse
    {
        // build a key from the criteria and the context, then
        // $this->cache->get($key, fn () => $this->inner->load($criteria, $context))
    }
}
XML
<service id="Acme\Badges\Store\Route\CachedBadgeRoute"
         decorates="Acme\Badges\Store\Route\BadgeRoute"
         decoration-priority="-1000">
    <argument type="service" id="Acme\Badges\Store\Route\CachedBadgeRoute.inner"/>
    <argument type="service" id="cache.object"/>
</service>

The core uses this exact structure for its own cached routes. The cache key must contain everything that changes the answer: the criteria, the sales channel, the language, the currency and, if the answer depends on rules, the rule ids. Leave out one of these and shoppers see another shopper's data. The other half of caching is invalidation: when a badge changes, the cached entries that include it must go away. Shopware does this with cache tags. Each cached entry is stored with tags such as acme-badge-b1, and a subscriber on your entity's written event asks the cache invalidator to remove everything carrying the changed tags. The wiring of the invalidator service differs between versions, so check the API of the version you target; the concept does not change.

The second stand-in implements tag-based caching and invalidation, with a counter that shows how often the "database" is hit.

PHP A caching decorator with tag invalidation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Remove the invalidate() call and run it again: the stale badge list stays visible. That is exactly the bug you get in a real shop when invalidation is forgotten. The stand-in keeps entries in an array; the real cache is a shared service with expiry times and tag support.

Calling the route

From the outside, a Store API call is plain HTTP with the sales channel's access key (read-only):

Terminal
curl -X POST "https://shop.example.com/store-api/acme/badge" \
  -H "sw-access-key: SWSCXXXXXXXXXXXX" \
  -H "Content-Type: application/json" \
  -d '{"filter": [{"type": "equals", "field": "productId", "value": "0188a1b2c3d4"}], "limit": 10}'

Routes that accept POST with a criteria JSON body get filtering, sorting and paging for free, because Shopware turns the body into a Criteria object before your method runs. To protect your data, decide which fields a public caller may filter on, and never expose internal or personal fields.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do core Store API routes extend an abstract class with getDecorated() instead of implementing an interface?

    The abstract class defines the contract and the decoration chain. A decorator returns the route it wraps from getDecorated(), and the innermost route throws.
  2. 2. What decides that a route runs through the Store API pipeline with a SalesChannelContext?

    The store-api route scope makes Shopware check the access key and build the sales channel context. Names and namespaces play no role.
  3. 3. A cached route returns another sales channel's data. What is the most likely mistake?

    A cache key must contain everything that changes the answer, such as channel, language, currency and criteria.
  4. 4. What is the purpose of cache tags?

    Entries are stored with tags, and a subscriber invalidates the tags of the entities that were written, so only affected entries disappear.

Summary

  • A Store API route is usually an abstract route, a concrete route with the route attribute, and a response extending StoreApiResponse.
  • getDecorated() makes the route decoratable; the innermost implementation throws.
  • The route scope and SalesChannelContext give you the sales channel, language, currency and customer; use sales-channel-aware repositories for public data.
  • Cache with a complete key and invalidate with tags when data changes.
  • The JSON shape is a public contract: add fields freely, never remove them casually.

Next, learn how back-office tools and integrations talk to Shopware in The Admin API and Integrations.