Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add own ADMIN API route and controller?

Tags:

shopware

I know shopware 6 has powerful builtin admin api. But I need to add own route/controller to admin api.

Here is what I have tried:

Controller:

<?php declare(strict_types=1);

namespace GIW\LiqPay\Controller\Api;

use Shopware\Core\Framework\Context;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Shopware\Core\Framework\Api\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;

class ExampleApiController extends AbstractController
{
    /**
     * @Route("/api/example", name="api.action.boilerplate.example-api-action", methods={"GET"})
     */
    public function exampleApi(Request $request, Context $context): JsonResponse
    {
        return new JsonResponse(['You successfully created your first controller route']);
    }
}

Added to my plugin services.xml:

<service id="GIW\LiqPay\Controller\Api\ExampleApiController" public="true">
<call method="setContainer">
<argument type="service" id="service_container"/>
</call>
</service>

Added to my plugin routes.xml:

<import resource="@GIWLiqPay/Controller/Api/ExampleApiController.php" type="annotation" />

But when I make GET request to /api/example I get this error:

{"errors":[{"status":"412","code":"FRAMEWORK__ROUTING_INVALID_ROUTE_SCOPE","title":"Precondition Failed","detail":"Invalid route scope for route api.action.boilerplate.example-api-action.","meta":{"parameters":{"routeName":"api.action.boilerplate.example-api-action"}}}]}

what the problem ?

like image 803
Mikael Avatar asked Feb 11 '26 01:02

Mikael


1 Answers

I found the problem:

The controller has to look like this:

<?php declare(strict_types=1);

namespace GIW\LiqPay\Controller\Api;

use Shopware\Core\Framework\Context;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Shopware\Core\Framework\Api\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Shopware\Core\Framework\Routing\Annotation\RouteScope;

/**
 * @RouteScope(scopes={"api"})
 */
class ExampleApiController extends AbstractController
{
    /**
     * @Route("/api/liqpay/example", name="api.action.liqpay.example-api-action", methods={"GET"})
     */
    public function exampleApi(Request $request, Context $context): JsonResponse
    {
        return new JsonResponse(['You successfully created your first controller route']);
    }
}

So I had to add scope annotation:

/**
 * @RouteScope(scopes={"api"})
 */
like image 92
Mikael Avatar answered Feb 15 '26 06:02

Mikael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!