APIDevTools / swagger-parser

Swagger 2.0 and OpenAPI 3.0 parser/validator
https://apitools.dev/swagger-parser
MIT License
1.1k stars 155 forks source link

Refs not working properly when splitting the definitions in separate files #145

Closed niklas-e closed 4 years ago

niklas-e commented 4 years ago

I'm using swagger-cli, which seems to use this library for validation and bundling. I made an OAS 3 definition with Error schema under components and then added $ref: '#/components/schemas/Error' to my response definitions which are in a separate file. This causes the following error on validation:

Error resolving $ref pointer "c:/projects/integration-service-specification/definition/responses.yaml#/components/schemas/Error".
Token "components" does not exist.

Here's a sample which is sufficient to reproduce the error.

responses.yaml

401:
  description: Unauthorized
  content:
    application/json:
      schema:
        $ref: "#/components/schemas/Error"

api.yaml

openapi: 3.0.0
info:
  title: My API
  description: This is an API
  version: 1.0.0
paths:
  '/my-endpoint':
    get:
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: string
        '401':
          $ref: '#/components/responses/401'

components:
  schemas:
    Error:
      type: object
      properties:
        code:
          type: string
        message:
          type: string
        requestId:
          type: string
  responses:
    $ref: './responses.yaml'

I also noticed this same behavior occurs when referring to other schemas inside a schema (when the schemas are in separate files).

JamesMessinger commented 4 years ago

@niklas-e - The $ref paths are relative to the file that they appear in, not to the root file. So #/components/schemas/Error is an invalid path in responses.yaml. You need to point to the path in api.yaml instead, like this:

401:
  description: Unauthorized
  content:
    application/json:
      schema:
        $ref: "api.yaml#/components/schemas/Error"
niklas-e commented 4 years ago

Yeah, I somehow missed that from the docs. Probably got misled because it actually seemed to work with different parser. Thanks for your response.