如何重用 swagger 2.0 字符串模式定义?

Bin*_*Ren 3 swagger swagger-2.0

我在 swagger 2.0“定义”部分定义了以下内容。我首先定义了时间戳的格式,我将在许多对象的属性中出于不同目的使用该格式,例如创建的时间戳和上次更新的时间戳。

definitions:
  TimeStamp:
    title: Timestamp format
    description: ISO 8681, "2016-08-18T17:33:00Z"
    type: string
    pattern: \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z
  Application:
    title: An application
    type: object
    properties:
      cDtm:
        title: Creation timestamp
        description: Some description
        type: string
        pattern:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z
Run Code Online (Sandbox Code Playgroud)

但是,在定义“Application”对象的“cDtm”属性时,我找不到重用时间戳定义的方法。如果我将“$ref”与“标题”和“描述”一起使用,则会收到警告“不允许与“$ref”一起使用同级值”。如果我不使用“$ref”,我需要重复上面的类型和模式定义。

所以,我的问题是,有没有办法使用 $ref 重用字符串模式定义,但仍然能够为定义的属性提供新的标题和描述?

谢谢!

必应

Hel*_*len 6

OpenAPI 规范包含此格式的内置内容format: date-time,因此您实际上不需要此处pattern。相反,使用:

type: string
format: date-time
Run Code Online (Sandbox Code Playgroud)


如果由于某种原因您想坚持使用pattern,则可以使用以下解决方法。$ref基本上,如果将 a 包装$ref到 中,则可以向 a“添加”属性allOf。这适用于 Swagger 编辑器和 Swagger UI,但其他工具支持可能有所不同。

  Application:
    title: An application
    type: object
    properties:
      cDtm:
        title: Creation timestamp
        description: Some description

        allOf:
          - $ref: '#/definitions/TimeStamp'
Run Code Online (Sandbox Code Playgroud)

另请记住,pattern默认情况下它是部分匹配的。要强制精确匹配,请将模式表达式括入^..$

pattern: ^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$
Run Code Online (Sandbox Code Playgroud)