首页 > 解决方案 > 如何使用 swagger 文档在 api-platform 的端点中请求额外的 GET 参数?

问题描述

我有一个 symfony 项目,我在其中使用 api-platform。

我有一个实体,我有它的数据提供者。我在为集合端点定义附加参数时遇到了麻烦。

实体称为建议。它必须从弹性搜索返回文档集合。

一个端点是:

/suggestion

此端点侦听其他 GET 参数:

页面、级别

每次请求端点时都会读取这两个参数。

在我的SuggestionsCollectionDataProvider.php课堂上,我有:

/**
     * Retrieves a collection.
     *
     * @param string $resourceClass
     * @param string|null $operationName
     * @return \Generator
     */
    public function getCollection(string $resourceClass, string $operationName = null): \Generator
    {
        $query = $this->requestStack->getCurrentRequest()->query;
        // I am reading these two parameters from RequestStack
        
        // this one is built-in
        $page = max($query->get('page', 1), 1); 

        // this is a custom one
        $level = $query->get('level', 0); 
        ...

在我的SuggestionRepository.php课堂上:

/**
     * @return \Generator
     */
    public function find(int $page, int $level): \Generator
    {
        // here I can process with $level without problems

页面参数是默认参数,即为集合swagger生成。

API 平台生成的 Swagger 文档的屏幕截图:

在此处输入图像描述

但是页面参数现在是唯一可以在网页版中编辑的参数。

我需要添加更多参数(level在这种情况下)来招摇和描述它们,以便用户/测试人员知道哪个参数实际上到达了这个端点。

主要问题:

如何告诉 api-platform,我希望 API 的用户/测试人员(从客户端)输入一些其他参数,level例如?

标签: phpsymfonyswaggeropenapiapi-platform.com

解决方案


终于想通了。

我还没有找到它的文档,但我找到了一种方法。

在实体类Suggestion.php中,我添加了一些注释行:

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class Suggestion. Represents an entity for an item from the suggestion result set.
 * @package App\Entity
 * @ApiResource(
 *     collectionOperations={
 *          "get"={
 *              "method"="GET",
 *              "swagger_context" = {
 *                  "parameters" = {
 *                      {
 *                          "name" = "level",
 *                          "in" = "query",
 *                          "description" = "Levels available in result",
 *                          "required" = "true",
 *                          "type" : "array",
 *                          "items" : {
 *                              "type" : "integer"
 *                          }
 *                      }
 *                  }
 *               }
 *          }
 *     },
 *     itemOperations={"get"}
 * )
 */

API平台swagger DOCs中的结果视图:

在此处输入图像描述


推荐阅读