在$ ref open api 3.0上引用远程“响应”和“参数”

时间:2018-12-19 13:06:26

标签: swagger openapi swaggerhub

我正在swaggerhub上创建井井有条的OAS3 swagger文档。对于每个端点,我正在写所有可能的答案,例如200、201、204、400、401、403、404、500等。此外,所有方法都具有默认参数,例如X语言代码等。 在这样一个地方,我现在使用的响应,模型,参数开始在每个文件中重复。经过一番研究,我了解到我可以创建一个域和对其的远程绝对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'

但是,显然您不能在$refresponses等下方使用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/'

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

1 个答案:

答案 0 :(得分:1)

截至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.0info部分和空白的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(不是APP.swaggerhub.com),并且链接包含/apis/(不是/domains/)。