首页 > 解决方案 > 如何在 API 平台中使用“$ref”引用和声明来自 Swagger 的组件?

问题描述

我们可以在 Swagger 中定义组件

components:
  schemas:
    User:
      properties:
        id:
          type: integer
        name:
          type: string

稍后使用这个组件:

responses:
  '200':
    description: The response
    schema: 
      $ref: '#/components/schemas/User'

我想使用它以避免重复内容。


我尝试在 API 平台中使用这种语法:

components:
    schemas:
        Part:
            description: Array of Part
            type: array
            items:
                type: object
                properties:
                    name:
                        type: string

App\Entity\Item:
    collectionOperations:
        post:
            method: 'POST'
            swagger_context:
                parameters:
                    - name: body
                      description: Item data
                      in: body
                      schema:
                          type: object
                          properties:
                              name:
                                  description: Part
                                  type: string
                                  required: true
                              part:
                                  $ref: '#/components/schemas/Part'

它给了我一个错误:

处理异常时抛出异常(Symfony\Component\Config\Exception\FileLoaderLoadException: Resource "components" not found in .(从 "/app/config/routes/api_platform.yaml" 导入)。确保有支持“api_platform”类型的加载器。)

看起来 YAML 加载程序无法识别该components项目。


如何在 API 平台中定义和使用引用?如何定义引用并在多个 YAML 文件中使用它?

标签: symfonyapi-platform.com

解决方案


你不能这样做。

components密钥属于 Swagger/OpenAPI 格式,不属于 API Platform 配置(映射)格式。API 平台配置文件和 Swagger 定义都可以用 YAML 编写,但它们并不相关。

因此,正如错误消息所述,components无法将 Swagger 直接注入 API 平台的配置文件中,就像您尝试做的那样。

API 平台的配置允许使用密钥在生成的 Swagger 文件中注入一些上下文,但您不能在此结构之外swagger_context编写随机 Swagger 定义(例如您的密钥)。component

做你想要实现的swagger_context关键是不够的(组件必须在 Swagger 文件的根目录中注入,而 . 是不可能的swagger_context)。

如本文档条目中所述,您必须为 Swagger 文档生成器创建装饰器,而不是使用此密钥:https ://api-platform.com/docs/core/swagger/#overriding-the-swagger-文件

装饰器允许访问整个 Swagger 结构并对其进行修改。因此,您将能够添加您的components结构。


推荐阅读