Hide endpoint in docs for a specific role

38 views Asked by At

I have an API that has multiple roles, and I want to hide some endpoints for specific roles in docs and also in the /api entrypoint. Is there an easy way to do so?

I found this question

How to hide a route from API Platform documentation

But it hides the endpoint entirely.

1

There are 1 answers

0
fredriktv On

You should do as mentioned here.

Also you should implement role check using Symfony security component to decide whether or not to show the endpoint.

<?php

namespace App\OpenApi;

use ApiPlatform\Core\OpenApi\Factory\OpenApiFactoryInterface;
use ApiPlatform\Core\OpenApi\Model\PathItem;
use ApiPlatform\Core\OpenApi\OpenApi;
use Symfony\Component\Security\Core\Security;

class OpenApiFactory implements OpenApiFactoryInterface
{
    public function __construct(
        private readonly OpenApiFactoryInterface $decorated
        private readonly Security $security
    ) {
    }

    public function __invoke(array $context = []): OpenApi
    {
        $openApi = $this->decorated->__invoke($context);

        /** @var PathItem $path */
        foreach ($openApi->getPaths()->getPaths() as $key => $path) {
            if ($this->security->isGranted('ROLE_USER')) {
                // Add logic to hide or modify the path for non-admin users
            }
        }

        return $openApi;
    }
}