Swagger Parser

repository·main·Indexed 22 days ago

https://github.com/apidevtools/swagger-parser

A parser and validator for Swagger 2.0 and OpenAPI 3.0 specifications for Node.js and browsers. It supports JSON and YAML formats, resolves $ref pointers (including circular references), and provides capabilities to bundle or dereference API definitions. The library supports both static and instance methods, and works with Promises or error-first callbacks.

Tokens
6K
Snippets
20
Records
34
Agent score
77%

What's inside @apidevtools/swagger-parser

  1. Core features of Swagger Parser

    main

    Swagger Parser provides several key capabilities for working with API definitions:

    • Parsing: Supports both JSON and YAML formats.
    • Validation: Validates against Swagger 2.0 or OpenAPI 3.0 schemas.
    • Resolution: Resolves all $ref pointers, including external files and URLs.
    • Bundling: Can bundle all Swagger files into a single file containing only internal $ref pointers.
    • Dereferencing: Can dereference all $ref pointers to provide a standard JavaScript object.
    • Reference Handling: Supports circular references, nested references, back-references, and cross-references while maintaining object reference equality (pointers to the same value resolve to the same object instance).
  2. Handle circular $ref pointers

    main

    Swagger Parser supports circular $ref pointers. When using dereference(), circular references are resolved, but be aware that JSON.stringify() will throw an error when encountering them.

    You have three ways to manage circular references:

    1. Default Behavior: Resolve them normally. If you need to serialize the result to JSON, use a custom replacer function to handle the circularity.
    2. Disable/Error: Set the dereference.circular option to false. This will cause a ReferenceError if a circular reference is detected.
    3. Ignore: Set the dereference.circular option to "ignore". Non-circular references will be dereferenced, but circular ones will remain as $ref pointers in the schema.
    4. Use bundle(): Instead of dereference(), use the bundle() method. Bundling converts external $ref pointers to internal ones without creating circular references in the resulting object.
    "person": {
        "properties": {
            "name": {
              "type": "string"
            },
            "spouse": {
              "type": {
                "$ref": "#/person"        // circular reference
              }
            }
        }
    }
  3. Understand the $Refs class

    main
    The $Refs class is a map of JSON References and their resolved values. It is provided to the callback function (or Promise) when calling the resolve method, and is also accessible via the parser.$refs property on a SwaggerParser instance. It provides helper methods to navigate and manipulate JSON References within your API.
  4. Use Callbacks or Promises with SwaggerParser

    main

    Swagger Parser supports both Node.js error-first callbacks and Promises (including async/await).

    • Callbacks: Pass a callback function as the last argument to any method. The callback follows the (err, result) pattern.
    • Promises: Omit the callback argument to receive a Promise. This is the recommended approach for modern async/await workflows.
    // Callback syntax
    SwaggerParser.validate(mySchema, (err, api) => {
      if (err) {
        // Error
      } else {
        // Success
      }
    });
    
    // async/await syntax
    try {
      let api = await SwaggerParser.validate(mySchema);
      // Success
    } catch (err) {
      // Error
    }
  5. Use static vs instance methods in SwaggerParser

    main

    Swagger Parser provides methods as both static (class) methods and instance methods.

    • Static methods: Use these for quick, one-off operations. They internally create a new SwaggerParser instance, execute the method, and return the result.
    • Instance methods: Use these if you need to access the parsed API object or the $refs property after the operation is complete. By creating an instance, you maintain a reference to the parser state.

    Example of static usage:

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

    Example of instance usage:

    let parser = new SwaggerParser();
    await parser.validate("my-api.yaml");
    // You can now access parser.api or parser.$refs
    let parser = new SwaggerParser();
    parser.validate("my-api.yaml");
  6. Configure options for SwaggerParser methods

    main

    All SwaggerParser methods accept an optional options object to customize parsing, resolving, dereferencing, and validation behavior. You do not need to specify every option; any omitted keys will use their default values.

    SwaggerParser.validate("my-api.yaml", {
      continueOnError: true,
      parse: {
        json: false,
        yaml: {
          allowEmpty: false,
        },
        text: {
          canParse: [".txt", ".html"],
          encoding: "utf16",
        },
      },
      resolve: {
        file: false,
        http: {
          timeout: 2000,
          withCredentials: true,
        },
      },
      dereference: {
        circular: false,
      },
      validate: {
        spec: false,
      },
    });
  7. Use Swagger Parser in the browser

    main

    To use Swagger Parser in a web browser, you must use a bundling tool such as Webpack, Rollup, Parcel, or Browserify.

    Note: Some bundlers may require specific configuration, such as setting browser: true in rollup-plugin-resolve when using Rollup.

  8. Import SwaggerParser in your project

    main

    Depending on your environment, use either CommonJS or ECMAScript modules (ESM) syntax to import the library.

    For Node.js (CommonJS):

    const SwaggerParser = require("@apidevtools/swagger-parser");

    For TypeScript, Babel, Webpack, or Rollup (ESM):

    import * as SwaggerParser from "@apidevtools/swagger-parser";
  9. Security warning: Local File Inclusion (LFI)

    main
    By default, the library attempts to resolve any files referenced using $ref without considering file extensions or locations. This can lead to Local File Inclusion (LFI) and sensitive information disclosure if you process documents from untrusted sources. Developers must implement mitigation strategies when handling untrusted input.
  10. Use the SwaggerParser class

    main

    The SwaggerParser class is the default export of the library. You can use it by creating an instance with new SwaggerParser() to access instance properties like api and $refs, or by calling its static methods directly.

    When using an instance, the api property stores the parsed, bundled, or dereferenced Swagger API object resulting from the last operation performed by that instance.

    let parser = new SwaggerParser();
    
    // The api property is initially null
    parser.api; // => null
    
    // After an operation, it holds the resulting object
    let api = await parser.dereference("my-api.yaml");
    
    typeof parser.api; // => "object"
    api === parser.api; // => true
  11. Set a value at a specific path with $Refs.set()

    main

    The set($ref, value, [options]) method assigns a value to the specified JSON Reference path (optionally including a JSON Pointer in the hash). If the target property or any of its parent properties do not exist, they will be created automatically.

    let $refs = await SwaggerParser.resolve("my-api.yaml");
    $refs.set("schemas/person.yaml#/properties/favoriteColor/default", "blue");