Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
swagger-parser
Advanced tools
swagger-parser is a powerful npm package that allows you to parse, validate, and dereference Swagger (OpenAPI) definitions. It helps in ensuring that your API definitions are correct and can be used to resolve $ref pointers to simplify the API documentation.
Parse
This feature allows you to parse a Swagger (OpenAPI) definition file. The code sample demonstrates how to parse a Swagger file and log the API name and version.
const SwaggerParser = require('swagger-parser');
SwaggerParser.parse('path/to/your/swagger.yaml')
.then(api => {
console.log('API name: %s, Version: %s', api.info.title, api.info.version);
})
.catch(err => {
console.error(err);
});
Validate
This feature allows you to validate a Swagger (OpenAPI) definition file. The code sample demonstrates how to validate a Swagger file and log whether the API is valid or not.
const SwaggerParser = require('swagger-parser');
SwaggerParser.validate('path/to/your/swagger.yaml')
.then(api => {
console.log('API is valid:', api);
})
.catch(err => {
console.error('API is invalid:', err);
});
Dereference
This feature allows you to dereference $ref pointers in a Swagger (OpenAPI) definition file. The code sample demonstrates how to dereference a Swagger file and log the dereferenced API.
const SwaggerParser = require('swagger-parser');
SwaggerParser.dereference('path/to/your/swagger.yaml')
.then(api => {
console.log('Dereferenced API:', api);
})
.catch(err => {
console.error(err);
});
Bundle
This feature allows you to bundle all external $ref pointers into a single file. The code sample demonstrates how to bundle a Swagger file and log the bundled API.
const SwaggerParser = require('swagger-parser');
SwaggerParser.bundle('path/to/your/swagger.yaml')
.then(api => {
console.log('Bundled API:', api);
})
.catch(err => {
console.error(err);
});
openapi-schema-validator is a package that validates OpenAPI 3.0 schemas. It focuses on schema validation and does not provide parsing or dereferencing functionalities like swagger-parser.
swagger-jsdoc is a package that generates Swagger (OpenAPI) definitions from JSDoc comments in your code. It is more focused on generating documentation from code comments rather than parsing and validating existing Swagger files.
swagger-client is a package that provides a JavaScript client for interacting with Swagger (OpenAPI) APIs. It includes functionalities for making API requests and handling responses, but it does not focus on parsing or validating Swagger definitions.
Live Demo! |
---|
$ref
pointers, including pointers to external files and URLs$ref
pointers, even in external files and URLs$ref
pointers (see notes below)$ref
pointers to the same object are resolved to the same object instanceThe syntax varies slightly depending on whether you're running it in Node.js or in a web browser. In all cases, you'll call the parse
method, passing it the path/url of your Swagger spec and a callback function. The api
parameter that's passed to the callback function is the parsed, validated, and dereferenced Swagger object.
npm install swagger-parser
Then add this to your Node script:
var parser = require("swagger-parser");
parser.parse('swagger.yaml', function(err, api, metadata) {
if (!err) {
console.log("API name: %s, Version: %s", api.info.title, api.info.version);
}
});
bower install swagger-parser
Then add this to your HTML page:
<script src="bower_components/swagger-parser/dist/swagger-parser.js"></script>
<script>
swagger.parser.parse('http://mysite.com/swagger.yaml', function(err, api, metadata) {
if (!err) {
console.log("API name: " + api.info.title + ", Version: " + api.info.version);
}
});
</script>
Just add swagger-parser
to your AMD module's dependencies, or require("swagger-parser")
explicitly.
define("myModule", ["swagger-parser"], function(parser) {
parser.parse('http://mysite.com/swagger.yaml', function(err, api, metadata) {
if (!err) {
console.log("API name: " + api.info.title + ", Version: " + api.info.version);
}
});
});
Parser.parse(swaggerPath, [options], callback)
swagger (required) - string
or object
The file path or URL of your Swagger file. Relative paths are allowed. In Node, the path is relative to process.cwd()
. In the browser, it's relative to the URL of the page.
If you pass an object instead of a string, then the parsing step will be skipped, but the object will still be validated, resolved, and dereferenced just like normal.
options (optional) - object
An object containing one or more parsing options. See options below.
callback (required) - function(err, api, metadata)
Called after the parsing is finished, or when an error occurs. See callback below for details.
Property | Type | Default | Description |
---|---|---|---|
parseYaml | bool | true | Enables/disables support for Swagger specs in YAML format. If set to false , then only JSON will be allowed. |
dereference$Refs | bool | true | Replaces $ref pointers in the Swagger object with their resolved values, resulting in a POJO (Plain-Old JavaScript Object) that is much easier to work with. Different $ref pointers that resolve to the same object will be replaced with the same object instance. Setting this option to |
dereferenceInternal$Refs | bool | true | If disabled, then only external $ref pointers will be dereferenced. This can be used to easily bundle a multi-file Swagger API into a single file, without affecting internal $ref pointers. |
resolve$Refs | bool | true | If disabled, then $ref pointers will not be resolved or dereferenced. This effectively disables dereference$Refs as well. The difference is that the metadata object won't be populated either. |
resolveExternal$Refs | bool | true | If disabled, then only internal $ref pointers will be resolved. Any $ref pointers to external files or URLs will be ignored. |
validateSchema | bool | true | Validates the API against the official Swagger schema. If set to false , then the resulting Swagger object may be missing properties, have properties of the wrong data type, etc. |
strictValidation | bool | true | Performs additional validation to ensure that the API is valid according to the Swagger Spec. This will detect things like duplicate parameters, invalid parameter types, etc. that aren't covered by the validateSchema option. |
Parameter | Type | Description |
---|---|---|
err | Error | null unless an error occurred. |
api | Swagger object | The complete Swagger API object. Or null if an error occurred |
metadata | object | This parameter provides extra information about the parsing operation. It is always provided, even if there's an error. |
The metadata
parameter is an object with the following properties:
Property | Type | Description |
---|---|---|
baseDir | string | The base directory used to resolve any external $ref pointers. If you passed a file path/URL to the parse method, then the baseDir is the directory of that file. If you passed an object, then baseDir is set to process.cwd() in Node, or the URL of the current page in browsers. |
files | array of strings | The full paths of all files that were parsed. This only includes local files, not URLs. If Parser.parse() was called with a local file path, then it will be the first item in this array. |
urls | array of URL objects | The URLs that were parsed. If Parser.parse() was called with a URL, then it will be the first item in this array. |
$refs | object | A map of all the $ref pointers that were resolved, and the objects they resolved to. If an error occurs while resolving a reference, then this object will still contain the $refs that were successfully parsed up to that point. |
Swagger files can contain circular $ref pointers, and Swagger-Parser will correctly parse them, resolve their values, and validate them against the Swagger schema. However, Swagger-Parser does not dereference circular references because this can easily cause stack overflows when the Swagger object is serialized, as well as other, more subtle bugs.
If your Swagger API includes circular references, then the callback will receive a ReferenceError
to alert you that the Swagger object was not fully dereferenced. However, you can choose to ignore this error and use the api
parameter anyway. All non-circular $ref
pointers in the Swagger object will still be resolved and dereferenced like always. Circular $ref
pointers will not be dereferenced, but they will be resolved, so you can access their resolved values in metadata.$refs
.
person:
properties:
name:
type: string
spouse:
type:
$ref: person # circular reference
I welcome any contributions, enhancements, and bug-fixes. File an issue on GitHub and submit a pull request. Just make sure you build the code and run the unit tests first.
To build the project locally on your computer:
Clone this repo
git clone https://github.com/BigstickCarpet/swagger-parser.git
Install dev dependencies
npm install
Run the build script
npm run build
Run unit tests
npm test
Swagger-Parser is 100% free and open-source, under the MIT license. Use it however you want.
FAQs
Swagger 2.0 and OpenAPI 3.0 parser and validator for Node and browsers
The npm package swagger-parser receives a total of 830,458 weekly downloads. As such, swagger-parser popularity was classified as popular.
We found that swagger-parser demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.