商店用品6:如何使工作我自己的请求在 Postman 使用管理API

5jvtdoz2  于 2023-01-13  发布在  Postman
关注(0)|答案(2)|浏览(124)

我创建了自己的请求API(POST:{{baseUrl}}/products/create)。此API用于创建许多产品,并且仅返回Shopware中现有产品的总数。我想在Postman中执行我的请求,但我不能。有办法在Postman中处理请求吗?
ApiController.php

<?php declare(strict_types=1);

namespace TestApi\Controller\Api;

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

/**
 * @RouteScope(scopes={"api"})
 */
class ApiController extends AbstractController
{
    protected EntityRepositoryInterface $productRepository;

    public function __construct(EntityRepositoryInterface $productRepository)
    {
        $this->productRepository = $productRepository;
    }
    /**
     * @Route("/products/create", name="api.product.create", methods={"POST"})
     */
    public function createProducts(Context $context): JsonResponse
    {
        $this->productRepository->create([
            [
                'name' => 'Product 1',
                'productNumber' => 'SW1231',
                'stock' => 10,
                'taxId' => 'bc3f1ba6f75749c79b5b4a9d673cf9d4',
                'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 50, 'net' => 25, 'linked' => false]],
            ],[
                'name' => 'Product 2',
                'productNumber' => 'SW1232',
                'stock' => 10,
                'taxId' => 'bc3f1ba6f75749c79b5b4a9d673cf9d4',
                'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 50, 'net' => 25, 'linked' => false]],
            ]
        ], $context);

        $criteria = new Criteria();
        $products = $this->productRepository->search($criteria, $context);

        return new JsonResponse($products->count());
    }
}

Postman :

有关信息,我在请求中提供了Authorization头。

tvokkenx

tvokkenx1#

实际上,问题出在控制器内部,您使用api route作用域,这意味着应该使用api身份验证机制,但是所有具有api route作用域的路由都需要在路径中以/api前缀开头。
没有/api/store-api前缀的路由被认为是具有店面授权的店面请求。由于路由作用域和实际API路径不匹配,您也应该得到一个错误,但可能在验证之前抛出CSRF错误。
要修复代码,请使用/api/products/create作为自定义控制器操作的路径,并在postman中使用/api前缀来访问您的路线。

iyzzxitl

iyzzxitl2#

您正在对店面而不是API端点发出请求。CSRF保护仅在店面中起作用。您的baseUrl是否缺少/api前缀?该值应类似于http://localhost/api

相关问题