如何从 API 平台文档中隐藏路由

Chr*_*391 4 api-platform.com symfony4

我正在用 Symfony4 下的 API 平台构建一个 API,

我想在文档中隐藏一个实体,该实体只能由打击的 ROLE_ADMIN 访问,而没有兴趣在文档中可见。

这是我想隐藏的实体:

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ApiResource(
 *     attributes={"access_control"="is_granted('ROLE_ADMIN')"}
 * )
 * @ORM\Entity(repositoryClass="App\Repository\OrderStatusRepository")
 */
class OrderStatus
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("orderGET")
     */
    private $label;

    /**
     * @return int|null
     */
    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return null|string
     */
    public function getLabel(): ?string
    {
        return $this->label;
    }

    /**
     * @param string $label
     * @return OrderStatus
     */
    public function setLabel(string $label): self
    {
        $this->label = $label;

        return $this;
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助

Dyl*_*bel 11

Symfony允许装饰服务,这里我们需要装饰api_platform.openapi.factory

src/OpenApi/OpenApiFactory.php使用以下内容创建:

<?php

namespace App\OpenApi;

use ApiPlatform\Core\OpenApi\Factory\OpenApiFactoryInterface;
use ApiPlatform\Core\OpenApi\Model\PathItem;
use ApiPlatform\Core\OpenApi\OpenApi;

class OpenApiFactory implements OpenApiFactoryInterface
{
    /**
     * @var OpenApiFactoryInterface
     */
    private $decorated;

    public function __construct(OpenApiFactoryInterface $decorated)
    {
        $this->decorated = $decorated;
    }

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

        /** @var PathItem $path */
        foreach ($openApi->getPaths()->getPaths() as $key => $path) {
            if ($path->getGet() && $path->getGet()->getSummary() === 'hidden') {
                $openApi->getPaths()->addPath($key, $path->withGet(null));
            }
        }

        return $openApi;
    }
}
Run Code Online (Sandbox Code Playgroud)

注册一下

services:
    App\OpenApi\OpenApiFactory:
        decorates: 'api_platform.openapi.factory'
        arguments: ['@App\OpenApi\OpenApiFactory.inner']
        autoconfigure: false
Run Code Online (Sandbox Code Playgroud)

添加openapi_context到您想要隐藏的每条路线

 * @ApiResource(
 *   itemOperations={
 *          "get"={
 *              ...
 *              "openapi_context"={
 *                  "summary"="hidden"
 *              }
 *          }
 *   }
 * )
Run Code Online (Sandbox Code Playgroud)


Kév*_*las 5

这不是开箱即用的支持(但这将是一个很好的贡献)。您可以做的是将 装饰DocumentationNormalizerunset()您不想出现在 OpenAPI 文档中的路径。

有关覆盖API 平台 OpenAPI 文档中的规范的更多信息