Swagger 2.0: Multiple Path objects with different paths but same request and response

Due to some backward compatibility reasons, I need to support both the paths /ab and /a-b.

The request and response objects are going to be the same for both of the paths.

Can I have something like the following in my Swagger spec so that I do not have to repeat the request and response object definitions for both the paths.

paths:
  /ab:
  /a-b:
    post:
    ...

Yes, you can have a path item that references another path item:

paths:
  /ab:
    post:
      summary: ...
      ...
      responses:
        ...

  /a-b:
    $ref: '#/paths/~1ab'   # <------------

Here, ~1ab is an encoded version of /ab (see below).

One limitation of this approach is that you cannot have operationId in all operations of the referenced path item. This is because the copy of the path ends up with the same operationId values, but operationId must be unique.

Encoding $ref values

If the characters ~ and / are present in node names (as in case of path names, e.g. /ab) they must be encoded: ~ as ~0, and / as ~1:

  • /ab~1ab$ref: '#/paths/~1ab'
  • /foo/bar~1foo~1bar$ref: '#/paths/~1foo~1bar'
  • /ab~cd~1ab~0cd#/paths/~1ab~0cd

Additionally, { } and other characters not allowed in URI fragment identifiers (RFC 3986, section 3.5) need to be percent-encoded. For example, { becomes %7B, and } becomes %7D.

  • /{zzz}
    ~1{zzz} ( / replaced with ~1)
    ~1%7Bzzz%7D (percent-encoded)
    $ref: '#/paths/~1%7Bzzz%7D'
  • /foo/{zzz}
    ~1foo~1{zzz} ( / replaced with ~1)
    ~1foo~1%7Bzzz%7D (percent-encoded)
    $ref: '#/paths/~1foo~1%7Bzzz%7D'

Note that you need to encode just the path name and not the #/paths/ prefix.