没有Item GET的API平台集合POST操作

时间:2021-01-13 14:54:01

标签: api-platform.com

我想使用集合操作“POST”和“GET”创建一个资源,而没有项目操作。

/**
 * @ApiResource(
 *     collectionOperations={
 *          "get",
 *          "post"
 *     },
 *     itemOperations={}
 * )
 */

当我尝试发布一个项目时,我收到以下错误:“没有与 App\Entity\MyEntity 类型关联的项目路由”。

我似乎 API 平台正在尝试创建 IRI,但它不能,因为没有项目“GET”操作。

我不需要 IRI,普通的 Id 对我来说就可以了。有没有办法做到这一点?

编辑:我在文档中找到了一个解决方案:https://api-platform.com/docs/core/operations/#enabling-and-disabling-operations

我可以像这样禁用 GET 操作:

 *     itemOperations={
 *         "get"={
 *             "controller"=NotFoundAction::class,
 *             "read"=false,
 *             "output"=false,
 *         },
 *     },

但是它不会像文档所说的那样返回 404。相反,它返回 500 错误并带有消息“Controller NotFoundAction 既不作为服务也不作为类存在。”。我怎样才能让它返回 404。

如果 GET 操作不会出现在我的 Swagger 文档中,那就太好了。

编辑:我发现 404 错误。我忘了包括 use ApiPlatform\Core\Action\NotFoundAction;

现在我只需要一种方法来从我的文档中删除路由。

编辑:我使用 Swagger 装饰器从文档中删除了路由。

<?php

declare(strict_types=1);

namespace App\Swagger;

use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

final class SwaggerDecorator implements NormalizerInterface
{
    private NormalizerInterface $decorated;

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

    public function supportsNormalization($data, string $format = null): bool
    {
        return $this->decorated->supportsNormalization($data, $format);
    }

    public function normalize($object, string $format = null, array $context = [])
    {
        $docs = $this->decorated->normalize($object, $format, $context);

        unset($docs['paths']['/products/{id}']);

        return $docs;
    }
}

在 services.yaml 中:

App\Swagger\SwaggerDecorator:
        decorates: 'api_platform.swagger.normalizer.documentation'
        arguments: [ '@App\Swagger\SwaggerDecorator.inner' ]
        autoconfigure: false

我的解决方案有效,但我不确定它是否是最佳解决方案。因此,如果有人有其他想法,请随时回答。

0 个答案:

没有答案
相关问题