首页 > 解决方案 > 在 $ref open api 3.0 上引用远程“响应”和“参数”

问题描述

我正在 swaggerhub 上创建一个组织良好的 OAS3 swagger 文档。对于每个端点,我都在写所有可能的答案,如 200、201、204、400、401、403、404、500 等。此外,所有方法都有默认参数,如 X-Language-Code 等。我在这样一个地方我现在使用的响应、模型、参数开始在每个文件中重复。经过一番研究,我了解到我可以创建一个域和对它们的远程绝对 url 引用。当我像这样远程使用“定义”时没有错误:

/example:
    get:
        #some other informations here
        responses:
            200:
                description: 'example description'
                content:
                    application/json:
                        schema:
                            $ref: 'https://remote.example/url/2.0#/definitions/ExampleResponse'

但是,显然你不能$ref在下面使用关键字responses等等400。关键字是这样的:

这个没有出错但没有呈现远程参考

responses:
    400:
        $ref: 'https://remote.example/url/2.0#/responses/Error400'

或这个:

这个给出错误

responses:
    $ref: 'https://remote.example/url/2.0#/responses'

甚至,我不能像预期的那样使用“参数”:

/example:
    get:
        parameters:
            - languageCode:
                $ref: 'https://remote.example/url/2.0#/parameters/languageCode'

/example:
    get:
        parameters:
            - $ref: 'https://remote.example/url/2.0#/parameters/'

我不想重写每个文档下面的所有参考定义。我对使用和引用“域”感到困惑。有人可以解释或参考有关这种情况的文档,因为我找不到任何有关它的文档。

标签: swaggeropenapiswaggerhub

解决方案


更新: SwaggerHub 现在支持 OpenAPI 3.0 域。


截至 2018 年 12 月,SwaggerHub 域仅支持 OpenAPI 2.0 语法,但不支持 OpenAPI 3.0。OpenAPI 3.0 和 2.0 对参数、响应等使用略有不同的语法,这意味着您不能从 OAS3 API 定义中引用 OAS2 域。

解决方法是在 SwaggerHub 中创建另一个 OpenAPI 3.0 API 并将其用作“域”。您需要添加一个带有openapi: 3.0.0,info部分和空的虚拟标头,paths: {}以使验证器满意。

openapi: 3.0.0
info:
  title: Common components
  version: 1.0.0
paths: {}

# Put your common components here:
components:
  schemas:
    ...
  parameters:
    ...
  responses:
    ...

$ref然后,您可以使用通常的语法从这个“域”中引用组件:

$ref: 'https://api.swaggerhub.com/apis/USERNAME/API-NAME/VERSION#/components/responses/Error400'

确保 $refs 中的主机名是API.swaggerhub.com(not APP.swaggerhub.com) 并且链接包含/apis/(not /domains/)。


推荐阅读