Skip to content

Latest commit

 

History

History
107 lines (83 loc) · 4.29 KB

README.md

File metadata and controls

107 lines (83 loc) · 4.29 KB

Swagger Parser API

Things to Know

Classes & Methods

Class methods vs. Instance methods

All of Swagger Parser's methods are available as static (class) methods, and as instance methods. The static methods simply create a new SwaggerParser instance and then call the corresponding instance method. Thus, the following line...

SwaggerParser.validate("my-api.yaml");

... is the same as this:

var parser = new SwaggerParser();
parser.validate("my-api.yaml");

The difference is that in the second example you now have a reference to parser, which means you can access the results (parser.api and parser.$refs) anytime you want, rather than just in the callback function. Also, having a SwaggerParser instance allows you to benefit from caching, so the next time you call parser.resolve(), it won't need to re-download those files again (as long as the cache hasn't expired).

Callbacks vs. Promises

Many people prefer ES6 Promise syntax instead of callbacks. Swagger Parser allows you to use whichever one you prefer.

If you pass a callback function to any method, then the method will call the callback using the Node.js error-first convention. If you do not pass a callback function, then the method will return an ES6 Promise.

The following two examples are equivalent:

// Callback syntax
SwaggerParser.validate(mySchema, function(err, api) {
    if (err) {
        // Error
    }
    else {
        // Success
    }
});
// ES6 Promise syntax
SwaggerParser.validate(mySchema)
    .then(function(api) {
        // Success
    })
    .catch(function(err) {
        // Error
    });

Circular $Refs

Swagger APIs can contain circular $ref pointers, and Swagger Parser fully supports them. Circular references can be resolved and dereferenced just like any other reference. However, if you intend to serialize the dereferenced api as JSON, then you should be aware that JSON.stringify does not support circular references by default, so you will need to use a custom replacer function.

You can disable circular references by setting the $refs.circular option to false. Then, if a circular reference is found, a ReferenceError will be thrown.

Another option is to use the bundle method rather than the dereference method. Bundling does not result in circular references, because it simply converts external $ref pointers to internal ones.

"person": {
    "properties": {
        "name": {
          "type": "string"
        },
        "spouse": {
          "type": {
            "$ref": "#/person"        // circular reference
          }
        }
    }
}