### Local Development Setup and Testing Commands Source: https://github.com/apidevtools/swagger-parser/blob/main/README.md These commands are used to initialize the development environment, install necessary dependencies, execute the test suite, and generate code coverage reports for the project. ```bash git clone https://github.com/APIDevTools/swagger-parser.git npm install npm test npm run coverage ``` -------------------------------- ### Install Swagger Parser Source: https://github.com/apidevtools/swagger-parser/blob/main/README.md The command to install the library via the npm package manager. ```bash npm install @apidevtools/swagger-parser ``` -------------------------------- ### Get Paths of Files and URLs from Swagger Parser `$Refs` Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/refs.md This example shows how to retrieve paths of files and URLs from the `$Refs` object. You can filter by type (e.g., 'fs' for local files, 'http' for URLs) or get all paths. ```javascript let $refs = await SwaggerParser.resolve("my-api.yaml"); // Get the paths of ALL files in the API $refs.paths(); // Get the paths of local files only $refs.paths("fs"); // Get all URLs $refs.paths("http", "https"); ``` -------------------------------- ### Customize SwaggerParser with Options (JavaScript) Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/options.md Demonstrates how to use the options parameter to customize SwaggerParser's behavior. This example shows settings for error handling, parsing (JSON, YAML, text), resolving (file, HTTP), dereferencing, and validation. ```javascript SwaggerParser.validate("my-api.yaml", { continueOnError: true, // Don't throw on the first error parse: { json: false, // Disable the JSON parser yaml: { allowEmpty: false, // Don't allow empty YAML files }, text: { canParse: [".txt", ".html"], // Parse .txt and .html files as plain text (strings) encoding: "utf16", // Use UTF-16 encoding }, }, resolve: { file: false, // Don't resolve local file references http: { timeout: 2000, // 2 second timeout withCredentials: true, // Include auth credentials when resolving HTTP references }, }, dereference: { circular: false, // Don't allow circular $refs }, validate: { spec: false, // Don't validate against the Swagger spec }, }); ``` -------------------------------- ### GET /pets Source: https://context7.com/apidevtools/swagger-parser/llms.txt Retrieves a list of all pets from the Pet Store API. ```APIDOC ## GET /pets ### Description Returns a list of all pets available in the store. ### Method GET ### Endpoint /pets ### Parameters None ### Request Example N/A ### Response #### Success Response (200) - **pets** (array) - A list of Pet objects. #### Response Example [ { "id": 1, "name": "Fido", "tag": "dog" } ] ``` -------------------------------- ### Get a Specific JSON Reference Value in Swagger Parser Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/refs.md This example demonstrates how to retrieve the value of a specific JSON Reference using its path with the `get()` method. It throws an error if the path is not found. ```javascript let $refs = await SwaggerParser.resolve("my-api.yaml"); let value = $refs.get("schemas/person.yaml#/properties/firstName"); ``` -------------------------------- ### Retrieve Values by Path from Swagger Parser `$Refs` Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/refs.md This code demonstrates how to get all values from the `$Refs` object, mapped by their paths/URLs. You can optionally filter values by their location type (e.g., 'file', 'http'). ```javascript let $refs = await SwaggerParser.resolve("my-api.yaml"); // Get ALL paths & values in the API // (this is the same as $refs.toJSON()) let values = $refs.values(); values["schemas/person.yaml"]; values["http://company.com/my-api.yaml"]; ``` -------------------------------- ### Validate OpenAPI 3.1 Document with Webhooks Source: https://context7.com/apidevtools/swagger-parser/llms.txt This example demonstrates validating an OpenAPI 3.1.0 document that includes webhooks. It utilizes Swagger Parser's `validate` function to process a specification with a defined webhook, showcasing support for advanced OpenAPI 3.1 features. ```javascript // OpenAPI 3.1 with webhooks (no paths required) const webhookApi = await SwaggerParser.validate({ openapi: "3.1.0", info: { title: "Webhook API", version: "1.0.0" }, webhooks: { newPet: { post: { summary: "New pet webhook", requestBody: { content: { "application/json": { schema: { $ref: "#/components/schemas/Pet" } } } }, responses: { "200": { description: "Webhook received" } } } } }, components: { schemas: { Pet: { type: "object", properties: { name: { type: "string" } } } } } }); ``` -------------------------------- ### Resolve References in OpenAPI/Swagger Definitions with SwaggerParser Source: https://context7.com/apidevtools/swagger-parser/llms.txt The SwaggerParser.resolve() method resolves all JSON references in the API definition without dereferencing them. It returns a `$Refs` object containing a map of all resolved file paths and their values, useful for inspecting or manipulating the raw referenced files. It allows filtering references by type (file, http) and provides methods to check existence, get, and set values. ```javascript const SwaggerParser = require("@apidevtools/swagger-parser"); // Resolve all references const $refs = await SwaggerParser.resolve("./api.yaml"); // Get all file paths in the API const allPaths = $refs.paths(); console.log(allPaths); // Output: ["api.yaml", "schemas/pet.yaml", "schemas/user.yaml", "https://example.com/common.yaml"] // Get only local file paths const localPaths = $refs.paths("file"); // Output: ["api.yaml", "schemas/pet.yaml", "schemas/user.yaml"] // Get only HTTP/HTTPS paths const remotePaths = $refs.paths("http", "https"); // Output: ["https://example.com/common.yaml"] // Get all values as a map const values = $refs.values(); console.log(Object.keys(values)); // Output: ["api.yaml", "schemas/pet.yaml", ...] // Check if a reference exists const exists = $refs.exists("schemas/pet.yaml#/properties/name"); console.log(exists); // true // Get a specific value using JSON pointer const petName = $refs.get("schemas/pet.yaml#/properties/name"); console.log(petName); // { type: "string", minLength: 1 } // Set a value at a JSON pointer path $refs.set("schemas/pet.yaml#/properties/name/default", "Fluffy"); // Check for circular references if ($refs.circular) { console.log("API contains circular references"); } ``` -------------------------------- ### Circular Reference Example in Swagger/OpenAPI Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/README.md A snippet showing a circular reference within a Swagger/OpenAPI schema definition. The 'spouse' property in the 'person' schema references '#/person', creating a loop. Swagger Parser can handle these, but JSON.stringify requires a custom replacer for serialization. ```json { "person": { "properties": { "name": { "type": "string" }, "spouse": { "type": { "$ref": "#/person" // circular reference } } } } } ``` -------------------------------- ### SwaggerParser Static vs Instance Methods (JavaScript) Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/README.md Demonstrates the equivalence between using static class methods and instance methods in the SwaggerParser. Static methods internally create an instance and call the corresponding instance method. Using instance methods allows direct access to parser properties like .api and .$refs. ```javascript SwaggerParser.validate("my-api.yaml"); ``` ```javascript let parser = new SwaggerParser(); parser.validate("my-api.yaml"); ``` -------------------------------- ### Using SwaggerParser Instance for API Parsing and Reference Management Source: https://context7.com/apidevtools/swagger-parser/llms.txt Demonstrates how to create a SwaggerParser instance to parse and validate API definitions. It shows how to access the parsed API object and its resolved references ($refs) after operations, allowing for inspection, querying, and modification of the API structure. This approach provides state persistence across multiple operations on the same instance. ```javascript const SwaggerParser = require("@apidevtools/swagger-parser"); // Create an instance to maintain state const parser = new SwaggerParser(); // Before parsing console.log(parser.api); // null console.log(parser.$refs); // $Refs object (empty) // Parse and access results via instance await parser.validate("./api.yaml"); // Access the parsed API via instance property console.log(parser.api.info.title); // "My API" console.log(parser.api.info.version); // "1.0.0" // Access all resolved references const paths = parser.$refs.paths(); console.log("Files in API:", paths); // Check for circular references if (parser.$refs.circular) { console.log("Circular references detected"); } // Query specific parts of the API const petSchema = parser.$refs.get("#/definitions/Pet"); console.log(petSchema); // Modify the API parser.$refs.set("#/info/description", "Updated description"); // Re-validate after modifications (create new instance) const validator = new SwaggerParser(); try { await validator.validate(parser.api); console.log("Modified API is still valid"); } catch (err) { console.error("Modifications broke the API:", err.message); } // Chain operations on same instance const parser2 = new SwaggerParser(); await parser2.dereference("api.yaml"); const api = parser2.api; // Same as returned value ``` -------------------------------- ### Import Swagger Parser Source: https://github.com/apidevtools/swagger-parser/blob/main/README.md Shows the syntax for importing the library in Node.js using CommonJS or in modern environments using ECMAScript modules. ```javascript const SwaggerParser = require("@apidevtools/swagger-parser"); ``` ```javascript import * as SwaggerParser from "@apidevtools/swagger-parser"; ``` -------------------------------- ### Configuring SwaggerParser for Custom Parsing, Resolution, and Validation Source: https://context7.com/apidevtools/swagger-parser/llms.txt Illustrates how to customize the SwaggerParser's behavior using a comprehensive options object. This includes settings for error handling, file parsing (JSON, YAML, text, binary), $ref resolution (external, file, HTTP with timeouts and headers), dereferencing (circular reference handling), and validation rules (schema, spec). ```javascript const SwaggerParser = require("@apidevtools/swagger-parser"); // Full options example const options = { // Continue parsing after first error (collect all errors) continueOnError: true, // Parser options - control how files are read parse: { json: { allowEmpty: false, // Don't allow empty JSON files order: 100 // Parser priority (lower runs first) }, yaml: { allowEmpty: false, order: 200 }, text: { canParse: [".txt", ".html"], // Parse these as plain text encoding: "utf8" }, binary: { canParse: [".png", ".pdf"] // Parse these as binary } }, // Resolver options - control how $refs are fetched resolve: { external: true, // Resolve external $refs (default: true) file: { order: 100, canRead: true // Allow reading local files }, http: { order: 200, timeout: 5000, // 5 second timeout redirects: 5, // Max redirects to follow withCredentials: false, // Include cookies in CORS requests headers: { "Accept": "application/json, application/yaml", "Authorization": "Bearer token123", "User-Agent": "MyApp/1.0" } } }, // Dereference options - control $ref resolution dereference: { circular: true, // true: resolve circular refs (default) // false: throw error on circular refs // "ignore": leave circular $refs as-is excludedPathMatcher: (path) => { // Don't dereference paths matching this function return path.includes("x-examples"); } }, // Validation options validate: { schema: true, // Validate against JSON schema (default: true) spec: true // Validate against Swagger spec (default: true) } }; const api = await SwaggerParser.validate("api.yaml", options); // Disable specific validators const api = await SwaggerParser.validate("api.yaml", { validate: { schema: false, // Skip schema validation spec: false // Skip spec validation } }); // Disable external reference resolution const api = await SwaggerParser.dereference("api.yaml", { resolve: { external: false // Only resolve internal $refs } }); ``` -------------------------------- ### Bundle OpenAPI/Swagger Definitions with SwaggerParser Source: https://context7.com/apidevtools/swagger-parser/llms.txt The SwaggerParser.bundle() method combines all referenced files into a single API definition using only internal `$ref` pointers. This is useful for packaging multi-file APIs for distribution, keeping file sizes small, and avoiding circular reference issues during JSON serialization. It supports bundling from local files or URLs and offers options for resolving external references and configuring HTTP requests. ```javascript const SwaggerParser = require("@apidevtools/swagger-parser"); const fs = require("fs"); // Bundle a multi-file API into a single document const api = await SwaggerParser.bundle("./api/openapi.yaml"); // External $refs are converted to internal $refs // Before: { "$ref": "./schemas/pet.yaml" } // After: { "$ref": "#/definitions/pet" } // Safe to serialize as JSON (no circular references) const bundledJson = JSON.stringify(api, null, 2); fs.writeFileSync("bundled-api.json", bundledJson); // Bundle from URL const api = await SwaggerParser.bundle("https://api.example.com/openapi.yaml"); // Bundle with options const api = await SwaggerParser.bundle("api.yaml", { resolve: { external: true, // Resolve external $refs (default) http: { timeout: 10000, // 10 second timeout for HTTP requests headers: { "Authorization": "Bearer token123" } } } }); // Example output structure: console.log(api.paths["/pets"].get.responses["200"].schema); // Output: { "$ref": "#/definitions/PetArray" } console.log(api.definitions.PetArray); // Output: { type: "array", items: { "$ref": "#/definitions/Pet" } } ``` -------------------------------- ### SwaggerParser Callbacks vs Promises (JavaScript) Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/README.md Illustrates how SwaggerParser methods can be used with either Node.js-style error-first callbacks or Promises. If a callback is provided, it's executed upon completion. If no callback is given, the method returns a Promise that resolves with the result or rejects with an error. ```javascript SwaggerParser.validate(mySchema, (err, api) => { if (err) { // Error handling } else { // Success handling } }); ``` ```javascript try { let api = await SwaggerParser.validate(mySchema); // Success handling } catch (err) { // Error handling } ``` -------------------------------- ### Handling Errors with Swagger Parser in JavaScript Source: https://context7.com/apidevtools/swagger-parser/llms.txt Demonstrates how to use try-catch blocks to handle various errors like validation failures, circular references, file resolution issues, HTTP request timeouts, and incorrect Swagger version formats. It also shows how to collect multiple errors using continueOnError. ```javascript const SwaggerParser = require("@apidevtools/swagger-parser"); // Handle validation errors try { await SwaggerParser.validate("invalid-api.yaml"); } catch (err) { console.error("Error type:", err.name); // Output: "SyntaxError" or "Error" console.error("Message:", err.message); // Output: "Swagger schema validation failed. // /paths/~1pets/get/responses/200 is missing required property 'description'" // Check for specific error types if (err.message.includes("schema validation failed")) { console.error("Schema validation error - check your API structure"); } } // Handle circular reference errors try { await SwaggerParser.dereference("api.yaml", { dereference: { circular: false } // Throw on circular refs }); } catch (err) { if (err instanceof ReferenceError) { console.error("Circular reference detected:", err.message); // Output: "Circular reference detected: The API contains circular references" } } // Handle file resolution errors try { await SwaggerParser.validate("./missing-file.yaml"); } catch (err) { console.error("File error:", err.message); // Output: "Error opening file './missing-file.yaml': ENOENT: no such file or directory" } // Handle HTTP resolution errors try { await SwaggerParser.validate("https://api.example.com/api.yaml", { resolve: { http: { timeout: 1000 } // 1 second timeout } }); } catch (err) { console.error("HTTP error:", err.message); // Output: "Error downloading https://api.example.com/api.yaml: request timeout" } // Handle Swagger version errors try { await SwaggerParser.parse({ swagger: 2.0, // Should be string "2.0" info: { title: "Test", version: "1.0" }, paths: {} }); } catch (err) { console.error(err.message); // Output: "Swagger version number must be a string (e.g. '2.0') not a number." } // Collect all errors with continueOnError try { await SwaggerParser.validate("api.yaml", { continueOnError: true }); } catch (err) { // err.errors contains array of all validation errors if (err.errors) { err.errors.forEach((e, i) => { console.error(`Error ${i + 1}: ${e.message}`); }); } } ``` -------------------------------- ### Managing external references with $refs Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/swagger-parser.md Shows how to use the $refs property to inspect referenced file paths within a Swagger API. ```javascript let parser = new SwaggerParser(); parser.$refs.paths(); // => [] empty array await parser.dereference("my-api.json"); parser.$refs.paths(); // => ["my-api.json"] ``` -------------------------------- ### Validate Swagger/OpenAPI Specifications Source: https://github.com/apidevtools/swagger-parser/blob/main/README.md Demonstrates how to validate an API specification using both callback-based and async/await patterns. These methods ensure the provided API object conforms to the Swagger/OpenAPI schema. ```javascript SwaggerParser.validate(myAPI, (err, api) => { if (err) { console.error(err); } else { console.log("API name: %s, Version: %s", api.info.title, api.info.version); } }); ``` ```javascript try { let api = await SwaggerParser.validate(myAPI); console.log("API name: %s, Version: %s", api.info.title, api.info.version); } catch (err) { console.error(err); } ``` -------------------------------- ### Accessing the API property Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/swagger-parser.md Demonstrates how to access the parsed API object from a SwaggerParser instance after dereferencing a file. ```javascript let parser = new SwaggerParser(); parser.api; // => null let api = await parser.dereference("my-api.yaml"); typeof parser.api; // => "object" api === parser.api; // => true ``` -------------------------------- ### Validating a Swagger API Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/swagger-parser.md Illustrates how to validate a Swagger API file using the static validate method, which performs schema validation and dereferencing. ```javascript try { let api = await SwaggerParser.validate("my-api.yaml"); console.log("Yay! The API is valid."); } catch (err) { console.error("Onoes! The API is invalid. " + err.message); } ``` -------------------------------- ### Bundle Swagger API Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/swagger-parser.md Combines multiple referenced files into a single Swagger object with internal $ref pointers. This method avoids circular references and is safe for JSON serialization. ```javascript let api = await SwaggerParser.bundle("my-api.yaml"); console.log(api.definitions.person); // => {$ref: "#/definitions/schemas~1person.yaml"} ``` -------------------------------- ### Dereferencing OpenAPI Document with Swagger Parser Source: https://github.com/apidevtools/swagger-parser/blob/main/SECURITY.md This code snippet demonstrates how to use the swagger-parser library to dereference an OpenAPI document. It processes a document that includes a `$ref` pointing to a local file, potentially leading to LFI if not handled securely. ```javascript import SwaggerParser from '@apidevtools/swagger-parser'; const documentSource = './document-shown-above.yml'; const doc = await SwaggerParser.dereference(documentSource); console.log(doc.paths['/pet'].put.requestBody.content['application/json'].schema); ``` -------------------------------- ### Dereference OpenAPI Schemas with Swagger Parser Source: https://context7.com/apidevtools/swagger-parser/llms.txt This code snippet illustrates how to dereference an OpenAPI specification file using Swagger Parser's `dereference` function. It then accesses a specific schema ('Pet') from the dereferenced components, demonstrating how to work with fully resolved schemas. ```javascript // Access dereferenced components const api = await SwaggerParser.dereference("openapi3.yaml"); const petSchema = api.components.schemas.Pet; console.log(petSchema.properties); ``` -------------------------------- ### Parse OpenAPI/Swagger Definitions with SwaggerParser Source: https://context7.com/apidevtools/swagger-parser/llms.txt The SwaggerParser.parse() method parses a single Swagger/OpenAPI file without resolving any `$ref` pointers. This is a low-level method primarily used internally but useful when you only need to read and validate the file format. It supports parsing YAML or JSON files, in-memory objects, and offers options for custom parsing behavior. ```javascript const SwaggerParser = require("@apidevtools/swagger-parser"); // Parse a YAML file const api = await SwaggerParser.parse("./openapi.yaml"); console.log("API name:", api.info.title); console.log("Version:", api.info.version); console.log("OpenAPI version:", api.openapi); // "3.0.0" or "3.1.0" // Parse a JSON file const api = await SwaggerParser.parse("./swagger.json"); console.log("Swagger version:", api.swagger); // "2.0" // $ref pointers are NOT resolved console.log(api.paths["/pets"].get.responses["200"].schema); // Output: { "$ref": "#/definitions/Pet" } - still a reference! // Parse with custom options const api = await SwaggerParser.parse("api.yaml", { parse: { yaml: { allowEmpty: false // Throw error on empty YAML files }, json: false // Disable JSON parser (only accept YAML) } }); // Parse an in-memory object (validates structure) const apiObject = { swagger: "2.0", info: { title: "My API", version: "1.0.0" }, paths: {} }; const parsed = await SwaggerParser.parse(apiObject); ``` -------------------------------- ### POST /webhooks/newPet Source: https://context7.com/apidevtools/swagger-parser/llms.txt Webhook endpoint to receive notifications when a new pet is added. ```APIDOC ## POST /webhooks/newPet ### Description Receives a payload whenever a new pet is registered in the system. ### Method POST ### Endpoint /webhooks/newPet ### Parameters #### Request Body - **name** (string) - Required - The name of the new pet. ### Request Example { "name": "Rex" } ### Response #### Success Response (200) - **message** (string) - Confirmation that the webhook was received. #### Response Example { "message": "Webhook received" } ``` -------------------------------- ### SwaggerParser.dereference() Source: https://context7.com/apidevtools/swagger-parser/llms.txt Resolves all $ref pointers in the API definition, replacing them with the actual referenced objects. ```APIDOC ## POST SwaggerParser.dereference() ### Description Recursively resolves all $ref pointers in an API definition, resulting in a plain JavaScript object without any external or internal references. ### Method POST (Internal Library Method) ### Parameters #### Path/Input Parameters - **api** (string|object) - Required - The file path, URL, or in-memory object to dereference. #### Options - **dereference.circular** (boolean|string) - Optional - Strategy for circular references: true (default), false, or "ignore". ### Request Example SwaggerParser.dereference("./api.yaml", { dereference: { circular: true } }); ### Response #### Success Response (200) - **api** (object) - The fully dereferenced API object with all $refs resolved. #### Response Example { "paths": { "/pets": { "get": { "responses": { "200": { "schema": { "type": "array", "items": { "type": "object" } } } } } } } ``` -------------------------------- ### Parse Swagger API File Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/swagger-parser.md Parses a Swagger API file (YAML or JSON) into a JavaScript object. This method does not resolve $ref pointers and is intended for basic file loading. ```javascript let api = await SwaggerParser.parse("my-api.yaml"); console.log("API name: %s, Version: %s", api.info.title, api.info.version); ``` -------------------------------- ### Set a JSON Reference Value in Swagger Parser Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/refs.md This code snippet illustrates how to set or update a value at a specific JSON Reference path using the `set()` method. It automatically creates parent properties if they don't exist. ```javascript let $refs = await SwaggerParser.resolve("my-api.yaml"); $refs.set("schemas/person.yaml#/properties/favoriteColor/default", "blue"); ``` -------------------------------- ### Validate OpenAPI 3.0 Document with Swagger Parser Source: https://context7.com/apidevtools/swagger-parser/llms.txt This snippet shows how to validate an OpenAPI 3.0.3 document using Swagger Parser. It imports the library and uses the `validate` function to process a JSON object representing the API definition. The output confirms the OpenAPI version. ```javascript const SwaggerParser = require("@apidevtools/swagger-parser"); // Validate OpenAPI 3.0 document const api = await SwaggerParser.validate({ openapi: "3.0.3", info: { title: "Pet Store API", version: "1.0.0" }, servers: [ { url: "https://api.example.com/v1" } ], paths: { "/pets": { get: { summary: "List all pets", operationId: "listPets", responses: { "200": { description: "A list of pets", content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/Pet" } } } } } } } } }, components: { schemas: { Pet: { type: "object", required: ["id", "name"], properties: { id: { type: "integer", format: "int64" }, name: { type: "string" }, tag: { type: "string" } } } } } }); console.log("OpenAPI version:", api.openapi); // "3.0.3" ``` -------------------------------- ### SwaggerParser.validate() Source: https://context7.com/apidevtools/swagger-parser/llms.txt Parses, dereferences, and validates a Swagger/OpenAPI definition against the official JSON schema and specification. ```APIDOC ## POST SwaggerParser.validate() ### Description Validates a Swagger or OpenAPI definition. It ensures the structure complies with the official JSON schema and specification rules. ### Method POST (Internal Library Method) ### Parameters #### Path/Input Parameters - **api** (string|object) - Required - The file path, URL, or in-memory object representing the API definition. #### Options - **validate.schema** (boolean) - Optional - Validate against JSON schema (default: true). - **validate.spec** (boolean) - Optional - Validate against Swagger 2.0 spec (default: true). ### Request Example SwaggerParser.validate("./petstore.yaml", { validate: { schema: true } }); ### Response #### Success Response (200) - **api** (object) - The fully validated and dereferenced API object. #### Response Example { "openapi": "3.0.0", "info": { "title": "My API", "version": "1.0.0" } } ``` -------------------------------- ### Resolve References with SwaggerParser.dereference() Source: https://context7.com/apidevtools/swagger-parser/llms.txt This method resolves all $ref pointers in an API definition, replacing them with the actual referenced values. It produces a plain JavaScript object, simplifies data traversal, and provides options to handle circular references. ```javascript const SwaggerParser = require("@apidevtools/swagger-parser"); const api = await SwaggerParser.dereference("./api.yaml"); console.log(api.paths["/pets"].get.responses["200"].schema); const apiCircular = await SwaggerParser.dereference("circular-api.yaml", { dereference: { circular: true } }); const parser = new SwaggerParser(); const apiResult = await parser.dereference("api.yaml"); if (parser.$refs.circular) { console.log("Warning: API contains circular references"); } ``` -------------------------------- ### Restricting File Resolver to YAML and JSON Source: https://github.com/apidevtools/swagger-parser/blob/main/SECURITY.md This code snippet shows how to configure the swagger-parser's file resolver to only allow reading of YAML (.yml) and JSON (.json) files. This is a security measure to mitigate Local File Inclusion (LFI) by preventing the resolution of arbitrary file types. ```javascript const doc = await SwaggerParser.dereference(documentSource, { resolve: { file: { canRead: ['.yml', '.json'] } } }); ``` -------------------------------- ### Validate API Definitions with SwaggerParser.validate() Source: https://context7.com/apidevtools/swagger-parser/llms.txt This method parses, dereferences, and validates an API definition against official JSON schemas. It supports input from file paths, URLs, or in-memory objects and allows for custom validation options. ```javascript const SwaggerParser = require("@apidevtools/swagger-parser"); try { const api = await SwaggerParser.validate("./petstore.yaml"); console.log("API name: %s, Version: %s", api.info.title, api.info.version); } catch (err) { console.error("Validation failed:", err.message); } const api = await SwaggerParser.validate("https://api.example.com/openapi.json"); const apiObject = { openapi: "3.0.0", info: { title: "My API", version: "1.0.0" } }; const validatedApi = await SwaggerParser.validate(apiObject); const apiCustom = await SwaggerParser.validate("api.yaml", { validate: { schema: true, spec: false }, dereference: { circular: "ignore" } }); ``` -------------------------------- ### Resolve Swagger API References Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/swagger-parser.md Resolves all $ref pointers within a Swagger API, including external files and URLs. It returns a $Refs object that allows for querying and modifying referenced parts of the API. ```javascript let $refs = await SwaggerParser.resolve("my-api.yaml"); // $refs.paths() returns the paths of all the files in your API let filePaths = $refs.paths(); // $refs.get() lets you query parts of your API let name = $refs.get("schemas/person.yaml#/properties/name"); // $refs.set() lets you change parts of your API $refs.set("schemas/person.yaml#/properties/favoriteColor/default", "blue"); ``` -------------------------------- ### Dereference Swagger API Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/swagger-parser.md Resolves all $ref pointers in a Swagger API into a standard JavaScript object. This method is ideal for programmatic access but may introduce circular references. ```javascript let api = await SwaggerParser.dereference("my-api.yaml"); // The `api` object is a normal JavaScript object, // so you can easily access any part of the API using simple dot notation console.log(api.definitions.person.properties.firstName); // => {type: "string"} ``` -------------------------------- ### Check if a JSON Reference Exists in Swagger Parser Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/refs.md This snippet shows how to use the `exists()` method to check if a specific JSON Reference path exists within the `$Refs` object. It returns a boolean value. ```javascript let $refs = await SwaggerParser.resolve("my-api.yaml"); $refs.exists("schemas/person.yaml#/properties/firstName"); // => true $refs.exists("schemas/person.yaml#/properties/foobar"); // => false ``` -------------------------------- ### Check for Circular References in Swagger Parser Source: https://github.com/apidevtools/swagger-parser/blob/main/docs/refs.md This snippet demonstrates how to check if an API schema contains circular references using the `circular` property of the `$Refs` object. It's useful before JSON stringification to avoid errors. ```javascript let parser = new SwaggerParser(); await parser.dereference("my-api.yaml"); if (parser.$refs.circular) { console.log("The API contains circular references"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.