Does OpenAPI 3.0 allow to reference server variables?

Viewed 3307

Say my OpenAPI definition has two servers. Both share the same variables. Thus I want to reference these variables to prevent duplicate code.

Actually I split my OpenAPI into files and combine it with swagger-cli bundle. This is what it creates:

openapi: 3.0.2
info:
  title: My API
  description: 'some description'
  version: 1.0.0
servers:
  - url: 'https://stage-api.domain.com/foo/{v1}/{v2}/{v3}'
    description: Staging API server for QA
    variables:
      v1:
        description: 'variable 1'
        default: 'something'
        enum:
          - 'foo1'
          - 'foo2'
      v2:
        description: 'variable 2'
        default: 'something'
        enum:
          - 'foo1'
          - 'foo2'
      v3:
        description: 'variable 3'
        default: 'something'
        enum:
          - 'foo1'
          - 'foo2'
  - url: 'https://api.domain.com/foo/{v1}/{v2}/{v3}'
    description: PRODUCTION API server
    variables:
      region:
        $ref: '#/servers/0/variables/v1'
      brand:
        $ref: '#/servers/0/variables/v2'
      locale:
        $ref: '#/servers/0/variables/v3'
paths: {}

Trying to validate this in Swagger Editor I get the following error:

Structural error at servers.1.variables.v1 should NOT have additional properties additionalProperty: $ref Jump to line xx

Structural error at servers.1.variables.v1 should have required property 'default' missingProperty: default Jump to line xx

Is it possible to reference the server variables or reuse them in another way?

Of course I could run swagger-cli bundle -r but I would want to prevent using that.

1 Answers

No, this is not supported. You can request changes to the OpenAPI Specification at
https://github.com/OAI/OpenAPI-Specification/issues

In your example, the server paths are almost the same except for the subdomain, so you can use a single server definition and make the subdomain a variable:

servers:
  - url: 'https://{env}.domain.com/foo/{v1}/{v2}/{v3}'
    variables:
      env:
        description: Environment - staging or production
        default: stage-api
        enum:
          - stage-api
          - api
      # other variables
      # ...
Related