I want to create a new own route API using admin API. I tried this code :
<?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("/api/product", name="api.product.search", methods={"GET"})
*/
public function getProducts(Context $context): JsonResponse
{
$criteria = new Criteria();
return new JsonResponse($this->productRepository->search($criteria, $context));
}
}
When I try this request {baseUrl}/api/product in storefront I get this error:
{"errors":[{"code":"9","status":"401","title":"The resource owner or authorization server denied the request.","detail":"Missing \u0022Authorization\u0022 header","meta":{"trace":[{"file":"\/var\/www\/html\/vendor\/league\/oauth2-server\/src\/AuthorizationValidators\/BearerTokenValidator.php","line":93,"function":"accessDenied","class":"League\\OAuth2\\Server\\Exception\\OAuthServerException","type":"::","args":["Missing \u0022Authorization\u0022 header"]}
Could you help me please ?
CodePudding user response:
There are two API's, one for Admin use (starts with /api/
), one for Storefront (/store-api/
). As you can see, you are not using the storefront API, and therefore expected to provide the appropriate Bearer
token.
Moreover, please check that /api/product
route already exists in the admin API.
Another thing, I think there is some confusion between a controller & an API route implementation. Maybe you could follow the official documentation on it or look it up online?
CodePudding user response:
You'll have to provide the Authorization
header in the request to your admin-api endpoint. The header should include a valid token. To retrieve the token you must first request the corresponding endpoint:
// POST /api/oauth/token
{
"grant_type": "client_credentials",
"client_id": "...",
"client_secret": "..."
}
You'll get a client_id
and client_secret
by creating an integration in the administration of your shop.
This endpoint will then return a temporarily valid token:
{
"token_type": "Bearer",
"expires_in": 600,
"access_token": "xxxxxxxxxxxxxx"
}
You then take the access_token
and in all your following requests to the api you set it for Authorization
in the request header, prepended by Bearer
:
Authorization: Bearer xxxxxxxxxxxxxx
If you're using a javascript client like axios the object for the headers then would look like this for example:
{
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
}