首页 > 解决方案 > 如何通过 Swagger 装饰器在 API 平台中记录自定义 POST 操作?

问题描述

在文档中有这个例子,但它只显示了如何添加一个 GET 操作。我想知道如何将自定义 POST 路由添加到文档中。

我无法显示示例正文请求以及要发送的预期值(在此示例中为用户名和电子邮件)

我的尝试

<?php
// api/src/Swagger/SwaggerDecorator.php

namespace App\Swagger;

use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

final class SwaggerDecorator implements NormalizerInterface
{
    private $decorated;

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

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


        $customDefinition = [
            'tags' => [
                'default'
            ],
            'name' => 'fields',
            'description' => 'Testing decorator',
            'default' => 'id',
            'in' => 'query',
            'requestBody' => 
                [
                    'content' => [
                        'application/json' => [
                            'schema' => [
                                'description' => 'abcd',
                                'required' => [
                                    'username', 'email'
                                ],
                                'properties' => [
                                    'username', 'email'
                                ],
                            ]
                        ]
                    ],
                    'description' => 'testing'
                ],
        ];

        $docs['paths']['/testing']['post']['parameters'][] = $customDefinition;

        return $docs;
    }

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

但它不起作用。 在此处输入图像描述

标签: symfonyswaggeropenapiapi-platform.com

解决方案


你不应该把整个路由声明放在参数数组中,你应该像这样创建:

$docs['paths']['/testing']['post'] = $customDefinition;

推荐阅读