### Auto-Loaded Configuration File Example Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/INDEX.md Example of a .openapiformatrc file, demonstrating auto-loaded configuration settings. ```json { "$schema": "https://openapi-format.com/schema/v1.json", "sort": true, "sortComponentsProps": true, "filterSet": { "tags": ["internal"] } } ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/INDEX.md Example of a YAML configuration object for OpenAPI formatting options. ```yaml sort: true casingSet: operationId: camelCase ``` -------------------------------- ### Install openapi-format Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/INDEX.md Install the openapi-format package using npm. This is the first step before using the tool. ```bash npm install openapi-format ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/INDEX.md Example of a JSON configuration object for OpenAPI formatting options. ```json { "sort": true, "casingSet": {"operationId": "camelCase"} } ``` -------------------------------- ### Complete .openapiformatrc Configuration Example Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/configuration.md This JSON object shows a comprehensive example of an .openapiformatrc configuration file, demonstrating various available options for sorting, bundling, comment handling, line width, quoting, and file-specific configurations. ```json { "$schema": "https://openapi-format.com/schema/v1.json", "sort": true, "bundle": true, "keepComments": false, "lineWidth": 100, "yamlQuoteStyle": "single", "sortComponentsProps": true, "sortFile": "./config/sort.json", "casingFile": "./config/casing.yaml", "filterFile": "./config/filter.yaml", "generateFile": "./config/generate.yaml", "output": "./dist/openapi.yaml", "sortComponentsSet": ["schemas", "parameters", "responses"], "casingSet": { "operationId": "camelCase", "properties": "snake_case", "componentsSchemas": "PascalCase" }, "filterSet": { "tags": ["internal"] }, "generateSet": { "operationIdTemplate": "_", "overwriteExisting": false } } ``` -------------------------------- ### Format Casing for Component Keys Source: https://github.com/thim81/openapi-format/blob/main/readme.md This example shows how to format casing for component keys like schemas, examples, and parameters to PascalCase. It also demonstrates how references to these components are updated. ```yaml componentsSchemas: PascalCase ``` ```yaml openapi: 3.0.3 paths: /orders: get: responses: content: application/json: schema: $ref: '#/components/schemas/order-model' components: schemas: userModel: type: object order-model: type: object pet_model: type: object ``` ```yaml openapi: 3.0.3 paths: /orders: get: responses: content: application/json: schema: $ref: '#/components/schemas/OrderModel' components: schemas: UserModel: type: object OrderModel: type: object PetModel: type: object ``` -------------------------------- ### Install OpenAPI-Format CLI Globally Source: https://github.com/thim81/openapi-format/blob/main/readme.md Install the openapi-format CLI globally on your system using npm. This makes the command available system-wide. ```shell $ npm install -g openapi-format ``` -------------------------------- ### Configuration Merging Example Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/configuration.md Illustrates the configuration merging rules, showing how a 'sortFile' option takes precedence over an inline 'sortSet' configuration. ```json { "sort": true, // From defaults/config "sortSet": { // Overridden by sortFile "get": ["operationId", "summary"] }, "sortFile": "./custom-sort.json" // This takes precedence } ``` -------------------------------- ### Inline Generation Configuration Example Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/configuration.md An example of inline configuration for OpenAPI file generation, specifying the operation ID template and overwrite policy. ```yaml operationIdTemplate: 'Prefix___Handler' overwriteExisting: false ``` -------------------------------- ### Example AI Prompt for OpenAPI-Format Skill Source: https://github.com/thim81/openapi-format/blob/main/readme.md An example prompt demonstrating how to use the $openapi-format skill within AI environments like Claude or Codex to generate CLI commands for specific tasks. ```text Using $openapi-format, create a minimal filter config to remove internal endpoints and give me the CLI command. ``` -------------------------------- ### Apply Documentation Overlays Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/INDEX.md Updates descriptions, examples, and metadata in an OpenAPI specification using an overlay configuration. ```javascript const baseDoc = await openapifmt.parseFile('./openapi.yaml'); const overlaid = await openapifmt.openapiOverlay(baseDoc, { overlaySet: { overlay: '1.1.0', info: {title: 'Overlay', version: '1.0.0'}, actions: [ { target: '$.info.description', update: 'Enhanced API documentation with additional details' }, { target: "$.paths['/api/users'].get.summary", update: 'Retrieve all users with pagination' }, { target: '$.components.schemas.Error', remove: true } ] } }); await openapifmt.writeFile('./openapi-enhanced.yaml', overlaid.data); ``` -------------------------------- ### Minimal Setup for Sorting OpenAPI Documents Source: https://github.com/thim81/openapi-format/blob/main/readme.md Sorts an OpenAPI document with minimal setup, reading from a file and writing the sorted output. Uses parseFile, stringify, and writeFile helpers. ```javascript const { parseFile, stringify, writeFile, openapiSort } = require('openapi-format'); const input = await parseFile('spec.json'); // local path or remote URL const {data} = await openapiSort(input, {sort: true}); const output = await stringify(data, {format: 'json'}); await writeFile('spec.sorted.json', output, {format: 'json'}); ``` -------------------------------- ### Install OpenAPI-Format CLI Locally Source: https://github.com/thim81/openapi-format/blob/main/readme.md Add the openapi-format CLI to your project's node_modules by running this command. This is the recommended method for local development. ```shell $ npm install --save openapi-format ``` -------------------------------- ### Example Usage of changeParametersCasingEnabled Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/casing-utilities.md Demonstrates how to use the `changeParametersCasingEnabled` function with a sample casing set. ```javascript const casingSet = {operationId: 'camelCase', parametersQuery: 'kebab-case'}; if (changeParametersCasingEnabled(casingSet)) { // Parameter casing is configured } ``` -------------------------------- ### Keep Only Specific Methods Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/configuration.md Use 'inverseMethods' to specify methods that should be kept. All other methods will be removed. This example keeps only 'get' and 'post' methods. ```json { "inverseMethods": ["get", "post"] } ``` -------------------------------- ### Get API Version and Summary using JSONPath Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/json-path-utilities.md Demonstrates retrieving specific values like API version and endpoint summary using `resolveJsonPathValue` with different JSONPath syntaxes. Includes an example with a default fallback value. ```javascript const version = openapifmt.resolveJsonPathValue( document, '$.info.version', '1.0.0' ); console.log('API version:', version); const title = openapifmt.resolveJsonPathValue( document, "$.paths['/pets'].post.summary" ); console.log('Create pet summary:', title); // With default fallback const deprecated = openapifmt.resolveJsonPathValue( document, "$.info.x-deprecated", false ); console.log('Is deprecated:', deprecated); ``` -------------------------------- ### Composite example: generate, filter, overlay, casing, convert, rename Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/command-recipes.md Demonstrates a composite workflow applying multiple formatting options including generation, filtering, overlay, casing, conversion, and renaming, saving the final output. ```bash openapi-format openapi.yaml \ --generateFile config/generate.yaml \ --filterFile config/filter.yaml \ --overlayFile config/overlay.yaml \ --casingFile config/casing.yaml \ --convertTo 3.2 \ --rename "Public API" \ --output dist/openapi.public.3.2.yaml ``` -------------------------------- ### JavaScript Examples for changeCase Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/casing-utilities.md Demonstrates how to use the changeCase function to convert strings to different casing styles and preserve characters. ```javascript const {changeCase} = require('openapi-format'); changeCase('openapiFormat', 'snake_case'); // 'openapi_format' changeCase('openapi-format', 'PascalCase'); // 'OpenapiFormat' changeCase('user.name', 'camelCase', ['.']); // 'user.name' (dot preserved) changeCase('api$key', 'snake_case'); // 'api$key' ($ always preserved) ``` -------------------------------- ### Quick Start: Process OpenAPI Document Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/README.md Demonstrates a typical workflow for loading, sorting, filtering, changing case, and saving an OpenAPI document using the openapi-format library. ```javascript const openapifmt = require('openapi-format'); // Load OpenAPI document const doc = await openapifmt.parseFile('./openapi.json'); // Sort fields const sorted = await openapifmt.openapiSort(doc, {sort: true}); // Filter out internal endpoints const filtered = await openapifmt.openapiFilter(sorted.data, { filterSet: {tags: ['internal']} }); // Standardize casing const cased = await openapifmt.openapiChangeCase(filtered.data, { casingSet: {operationId: 'camelCase', properties: 'snake_case'} }); // Save result await openapifmt.writeFile('./openapi-formatted.json', cased.data); ``` -------------------------------- ### Example Usage of changeComponentParametersCasingEnabled Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/casing-utilities.md Demonstrates how to use the `changeComponentParametersCasingEnabled` function with a sample casing set. ```javascript const casingSet = {componentsSchemas: 'PascalCase', componentsParametersQuery: 'kebab-case'}; if (changeComponentParametersCasingEnabled(casingSet)) { // Component parameter casing is configured } ``` -------------------------------- ### Format Casing for Parameter Names Source: https://github.com/thim81/openapi-format/blob/main/readme.md This example demonstrates formatting the 'name' field of parameters (Path, Query, Header) to kebab-case. It shows the transformation of parameter names before and after formatting. ```yaml componentsParametersPath: kebab-case ``` ```yaml openapi: 3.0.3 paths: '/pet/{petId}': get: parameters: - name: petId in: path description: ID of pet to return - $ref: '#/components/parameters/LimitParam' components: parameters: LimitParam: name: limitParam in: query description: max records to return ``` ```yaml openapi: 3.0.3 paths: '/pet/{petId}': get: parameters: - name: pet-id in: path description: ID of pet to return - $ref: '#/components/parameters/LimitParam' components: parameters: LimitParam: name: limit-param in: query description: max records to return ``` -------------------------------- ### Model and Schema Properties Casing Example Source: https://github.com/thim81/openapi-format/blob/main/readme.md Illustrates formatting schema properties within OpenAPI components from camelCase to snake_case. ```yaml properties: snake_case ``` ```yaml openapi: 3.0.3 components: schemas: UserModel: type: object properties: id: type: integer example: 10 emailAddress: type: string example: john@doe.com firstName: type: string example: John ``` ```yaml openapi: 3.0.3 components: schemas: UserModel: type: object properties: id: type: integer example: 10 email_address: type: string example: john@doe.com first_name: type: string example: John ``` -------------------------------- ### Add OpenAPI-Format AI Skill Source: https://github.com/thim81/openapi-format/blob/main/readme.md Install the openapi-format skill from the GitHub repository using npx. This allows AI models to utilize the CLI's functionality. ```shell $ npx skills add https://github.com/thim81/openapi-format --skill openapi-format ``` -------------------------------- ### OpenAPI Document Before Version Conversion Source: https://github.com/thim81/openapi-format/blob/main/readme.md Example of an OpenAPI document's 'info' section before converting to a newer version. ```json { "openapi": "3.0.2", "info": { "title": "Petstore - OpenAPI", ``` -------------------------------- ### Example Usage of openapiChangeCase Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/main-functions.md Demonstrates how to use the openapiChangeCase function with specific casing rules for operation IDs, properties, schema components, and query parameters. ```javascript const cased = await openapifmt.openapiChangeCase(document, { casingSet: { operationId: 'snake_case', properties: 'camelCase', componentsSchemas: 'PascalCase', parametersQuery: 'kebab-case' } }); ``` -------------------------------- ### Example Usage of parseFile Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/file-utilities.md Demonstrates how to use the `parseFile` function to load OpenAPI documents from local files and remote URLs, with and without specific parsing options. ```javascript const localDoc = await openapifmt.parseFile('./openapi.json'); const remoteDoc = await openapifmt.parseFile('https://api.example.com/openapi.yaml'); const withComments = await openapifmt.parseFile('./openapi.yaml', {keepComments: true}); ``` -------------------------------- ### OpenAPI Document Before Rename Source: https://github.com/thim81/openapi-format/blob/main/readme.md Example of an OpenAPI document's 'info' section before applying the rename operation. ```json { "openapi": "3.0.2", "info": { "title": "Petstore - OpenAPI 3.0", ``` -------------------------------- ### Example Usage of resolveJsonPath Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/json-path-utilities.md Demonstrates how to use the resolveJsonPath function to find operation details, all response definitions, and component schemas within an OpenAPI document. ```javascript const nodes = openapifmt.resolveJsonPath(document, "$.paths['/pets'].get"); if (nodes.length > 0) { console.log('Found operation:', nodes[0].value); } const allResponses = openapifmt.resolveJsonPath(document, "$.paths[*][*].responses"); console.log('Response definitions found:', allResponses.length); const allSchemas = openapifmt.resolveJsonPath(document, "$.components.schemas[*]"); console.log('Component schemas:', allSchemas.map(n => n.value)); ``` -------------------------------- ### OperationId Casing Example Source: https://github.com/thim81/openapi-format/blob/main/readme.md Demonstrates how to format the 'operationId' property from camelCase to kebab-case in an OpenAPI document. ```yaml operationId: kebab-case ``` ```yaml openapi: 3.0.3 paths: /pets: get: operationId: getPets ``` ```yaml openapi: 3.0.3 paths: /pets: get: operationId: get-pets ``` -------------------------------- ### OpenAPI Document After Version Conversion to 3.1 Source: https://github.com/thim81/openapi-format/blob/main/readme.md Example of an OpenAPI document's 'info' section after converting to version 3.1. ```json { "openapi": "3.1.0", "info": { "title": "OpenAPI Petstore - OpenAPI", ``` -------------------------------- ### OpenAPI Document After Rename Source: https://github.com/thim81/openapi-format/blob/main/readme.md Example of an OpenAPI document's 'info' section after applying the rename operation. ```json { "openapi": "3.0.2", "info": { "title": "OpenAPI Petstore - OpenAPI 3.0", ``` -------------------------------- ### Execute OpenAPI-Format CLI with NPX Source: https://github.com/thim81/openapi-format/blob/main/readme.md Use this command to execute the openapi-format CLI directly without a local installation. Replace 'your-openapi-file.yaml' with the path to your OpenAPI document. ```shell $ npx openapi-format your-openapi-file.yaml ``` -------------------------------- ### Main Functions Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/00-START-HERE.txt Reference for the core functions exported by the openapi-format library, including their signatures and usage examples. ```APIDOC ## Main Functions API Reference This section details the primary functions available in the openapi-format library. ### `openapiSort()` Sorts an OpenAPI document. ### `openapiFilter()` Filters an OpenAPI document based on specified criteria. ### `openapiChangeCase()` Changes the casing of keys within an OpenAPI document. ### `openapiGenerate()` Generates an OpenAPI document from a given source. ### `openapiOverlay()` Applies an overlay to an OpenAPI document. ### `openapiRename()` Renames elements within an OpenAPI document. ### `openapiConvertVersion()` Converts the version of an OpenAPI document. ### `openapiSplit()` Splits an OpenAPI document into multiple parts. ``` -------------------------------- ### Example OpenAPI Format Options Configuration Source: https://github.com/thim81/openapi-format/blob/main/readme.md Define sorting, casing, filtering, and generation rules within a JSON configuration file. These settings dictate how the OpenAPI document will be formatted. ```json { "sort": true, "casingSet": { "operationId": "camelCase", "properties": "snake_case" }, "filterSet": { "tags": ["internal", "beta"] }, "generateSet": { "operationIdTemplate": "__Handler" } } ``` -------------------------------- ### Applying Overlay Actions to OpenAPI Document Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/main-functions.md Example demonstrating how to use the openapiOverlay function to apply updates and removals to an OpenAPI document. It shows how to define overlay actions for specific targets like descriptions, summaries, and schema removals. ```javascript const overlaid = await openapifmt.openapiOverlay(document, { overlaySet: { overlay: '1.1.0', info: { title: 'Overlay for docs', version: '1.0.0' }, actions: [ { target: '$.info.description', update: 'Updated API description' }, { target: "$.paths['/pets'].get.summary", update: 'Retrieve all pets' }, { target: '$.components.schemas.OldSchema', remove: true } ] } }); console.log('Used:', overlaid.resultData.totalUsedActions); ``` -------------------------------- ### Complex Overlay Example with JSONPath Actions Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/json-path-utilities.md Demonstrates how to use JSONPath to define overlay actions for modifying an OpenAPI document. This includes adding descriptions, deprecation notices, security schemes, copying version information, and removing endpoints. ```javascript const overlay = await openapiFormat.openapiOverlay(document, { overlaySet: { overlay: '1.1.0', info: { title: 'Overlay Example', version: '1.0.0' }, actions: [ // Add description to root {target: '$.info.description', update: 'API documentation'}, // Add deprecation notice to specific endpoint {target: "$.paths['/v1/users'].get.deprecated", update: true}, // Add required security to all operations {target: "$.paths[*][*].security", update: [{api_key: []}]}, // Copy version info {target: '$.info.version', copy: '$.info.x-version'}, // Remove old endpoint {target: "$.paths['/deprecated/endpoint']", remove: true} ] } }); console.log('Applied', overlay.resultData.totalUsedActions, 'actions'); ``` -------------------------------- ### Example OpenAPI Document Structure Source: https://github.com/thim81/openapi-format/blob/main/readme.md This YAML snippet shows a basic structure of an OpenAPI document, including version, info, and paths. It serves as a reference for the context of the filtering and sorting options. ```yaml openapi: 3.0.0 info: title: API version: 1.0.0 paths: /pets: get: summary: Finds Pets by status put: summary: Update an existing pet ``` -------------------------------- ### Example Usage of OpenAPIResult Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/types.md Demonstrates typical usage of the OpenAPIResult type with default and specific type parameters. The resultData field can contain operation-specific metadata. ```typescript // Typical usage const result: OpenAPIResult = await openapiSort(doc, options); // result.data is the sorted document // result.resultData is an empty object {} // With specific result type const filterResult: OpenAPIResult = await openapiFilter(doc, {filterSet: {...}}); // filterResult.resultData contains {unusedComp, totalComp} ``` -------------------------------- ### Custom Casing Configuration Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/configuration.md A YAML configuration file for defining casing conventions for various OpenAPI elements. This example sets casing for operation IDs, properties, and different types of parameters and components. ```yaml operationId: snake_case operationIdKeepChars: - . properties: camelCase propertiesKeepChars: - . parametersQuery: kebab-case parametersPath: snake_case parametersHeader: kebab-case componentsSchemas: PascalCase componentsExamples: PascalCase componentsResponses: snake_case componentsRequestBodies: snake_case componentsHeaders: kebab-case componentsSecuritySchemes: PascalCase componentsParametersQuery: snake_case componentsParametersPath: camelCase componentsParametersHeader: kebab-case ``` -------------------------------- ### Using Environment-Specific Configuration Files Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/configuration.md Demonstrates how to use different configuration files for different environments (e.g., production and development) by specifying the --configFile option in the CLI. ```bash openapi-format openapi.json --configFile config/prod.json openapi-format openapi.json --configFile config/dev.json ``` -------------------------------- ### Correct CLI Usage: Input and Output Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/errors.md Demonstrates the correct invocation of the `openapi-format` CLI, including specifying both the input file and the output file. ```bash openapi-format openapi.json -o output.yaml # Correct usage ``` -------------------------------- ### CLI Usage: Display Help Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/errors.md Shows how to display the help message for the `openapi-format` CLI to view all valid options. ```bash openapi-format --help # See all valid options ``` -------------------------------- ### CLI Sort and Format with Configuration File Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/INDEX.md Applies sorting and formatting using a configuration file specified via the CLI. ```bash # With configuration file openapi-format openapi.json --configFile openapi-format-config.json -o output.yaml ``` -------------------------------- ### Apply overlay to input Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/command-recipes.md Formats an OpenAPI file, applying an overlay defined in a specified file, and saves the output. ```bash openapi-format openapi.yaml --overlayFile config/overlay.yaml --output dist/openapi.overlay.yaml ``` -------------------------------- ### Basic Formatting Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/command-recipes.md Formats an OpenAPI file and saves the output to a new file. ```bash openapi-format openapi.yaml --output openapi.formatted.yaml ``` -------------------------------- ### Remove Internal and Beta Endpoints Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/configuration.md Use the 'tags' field to specify tags for endpoints that should be removed. This example targets endpoints tagged as 'internal' or 'beta'. ```json { "tags": ["internal", "beta"] } ``` -------------------------------- ### Filter Unused OpenAPI Components Source: https://github.com/thim81/openapi-format/blob/main/readme.md Use the 'unusedComponents' filter to remove unused components like schemas or examples from the OpenAPI document. This helps in cleaning up the specification. ```yaml unusedComponents: - examples - schemas ``` -------------------------------- ### Use Configuration File with CLI Source: https://github.com/thim81/openapi-format/blob/main/readme.md Pass a configuration file to the CLI to apply all formatting options defined within it. This centralizes settings for automated workflows. ```shell $ openapi-format openapi.json --configFile openapi-format-options.json ``` -------------------------------- ### Import and List Module Exports Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/INDEX.md This snippet demonstrates how to import the openapi-format library and lists all available functions for processing, defaults, file I/O, and utilities. ```javascript const openapifmt = require('openapi-format'); // Processing functions openapifmt.openapiSort() openapifmt.openapiFilter() openapifmt.openapiChangeCase() openapifmt.openapiGenerate() openapifmt.openapiOverlay() openapifmt.openapiSplit() openapifmt.openapiConvertVersion() openapifmt.openapiRename() // Defaults openapifmt.getDefaultSortSet() openapifmt.getDefaultSortComponentsSet() // File I/O openapifmt.parseFile() openapifmt.parseString() openapifmt.stringify() openapifmt.writeFile() openapifmt.readFile() openapifmt.detectFormat() // Utilities openapifmt.analyzeOpenApi() openapifmt.changeCase() openapifmt.resolveJsonPath() openapifmt.resolveJsonPathValue() ``` -------------------------------- ### Use Defaults with Single Output File Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/config-patterns.md Use this pattern when the default settings of openapi-format are sufficient and only input and output files need to be specified. ```bash openapi-format input.yaml --output output.yaml ``` -------------------------------- ### Get Default OpenAPI Sort Configuration Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/main-functions.md Retrieves a deep copy of the default sorting configuration for OpenAPI documents. This configuration can be modified and used with the `openapiSort` function. ```typescript async function getDefaultSortSet(): Promise ``` ```javascript const defaultSort = await openapifmt.getDefaultSortSet(); defaultSort.get = ['summary', 'description', 'responses']; const sorted = await openapifmt.openapiSort(document, {sortSet: defaultSort}); ``` -------------------------------- ### Use a specific config file Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/command-recipes.md Formats an OpenAPI file using a specified configuration file and saves the output. ```bash openapi-format openapi.yaml --configFile config/format.yaml --output dist/openapi.yaml ``` -------------------------------- ### Apply casing rules Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/command-recipes.md Formats an OpenAPI file, applying casing rules defined in a specified file, and saves the cased output. ```bash openapi-format openapi.yaml --casingFile config/casing.yaml --output dist/openapi.cased.yaml ``` -------------------------------- ### Remove Elements by JSONPath in OpenAPI Overlay Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/json-path-utilities.md Removes specified elements from an OpenAPI document using JSONPath targets. This includes removing entire endpoints, schemas, or collections like examples. ```javascript const overlaid = await openapifmt.openapiOverlay(document, { overlaySet: { actions: [ // Remove deprecated endpoint { target: "$.paths['/old-endpoint']", remove: true }, // Remove internal schema { target: '$.components.schemas.InternalModel', remove: true }, // Remove all examples { target: '$.components.examples', remove: true } ] } }); ``` -------------------------------- ### Get Default OpenAPI Components Sort Configuration Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/main-functions.md Retrieves a deep copy of the default sorting configuration specifically for OpenAPI components. This is a string array representing the order of component types. ```typescript async function getDefaultSortComponentsSet(): Promise ``` -------------------------------- ### Create Output Directory with mkdir Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/errors.md Ensures the output directory exists before splitting the OpenAPI document. Use `recursive: true` to create parent directories if they don't exist. ```javascript import {mkdir} from 'fs/promises'; const outputDir = './openapi-split'; await mkdir(outputDir, {recursive: true}); await openapiFormat.openapiSplit(document, { output: `${outputDir}/openapi.yaml` }); ``` -------------------------------- ### Custom OperationId Template with Static Text Source: https://github.com/thim81/openapi-format/blob/main/readme.md An example of an operationId template that includes static text along with dynamic placeholders for the HTTP method and path parts. This allows for more structured and descriptive operationIds. ```yaml operationIdTemplate: "Prefix___Handler" ``` -------------------------------- ### Apply overlay with `extends` as implicit input Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/command-recipes.md Applies an overlay to an OpenAPI file where the input file is implicitly determined by the `extends` keyword within the overlay configuration. ```bash openapi-format --overlayFile config/overlay.yaml --output dist/openapi.overlay.yaml ``` -------------------------------- ### Find All Operations in OpenAPI Document Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/json-path-utilities.md Extract all defined operations (GET, POST, PUT, etc.) from an OpenAPI document using a wildcard JSONPath expression. This snippet iterates through the found operations and logs their summaries. ```javascript // Get all operations (get, post, put, patch, delete, etc.) const operations = openapifmt.resolveJsonPath( document, "$.paths[*][*]" ); operations.forEach(op => { console.log('Operation:', op.value?.summary || '(no summary)'); }); ``` -------------------------------- ### Project Defaults in `.openapiformatrc` Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/config-patterns.md Define project-wide default settings in a `.openapiformatrc` file. These settings are automatically applied when `openapi-format` is run in the project directory. ```yaml # .openapiformatrc lineWidth: 120 keepComments: true sort: true bundle: true sortSet: sortPathsBy: original ``` ```bash openapi-format input.yaml --output output.yaml ``` -------------------------------- ### Convert OpenAPI Document to Version 3.1 Source: https://github.com/thim81/openapi-format/blob/main/readme.md Use the `--convertTo "3.1"` option to upgrade an OpenAPI 3.0.x document to version 3.1. This aligns with the changes described in the migration guide. ```shell $ openapi-format openapi.json -o openapi-3.1.json --convertTo "3.1" ``` -------------------------------- ### Reference External Configuration Files Source: https://github.com/thim81/openapi-format/blob/main/readme.md Configure formatting by referencing external JSON/YAML files for specific settings like sorting, casing, filtering, and generation. These external files override inline configurations. ```json { "sortFile": "customSort.json", "casingFile": "casing-rules.json", "filterFile": "filter-rules.json", "generateFile": "generate-rules.json" } ``` -------------------------------- ### Configure Version Upgrade and Casing Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/configuration.md Use this pattern to upgrade the OpenAPI version and apply specific casing rules for operations and properties. It also enables bundling of the output. ```json { "sort": true, "convertTo": "3.1", "bundle": true, "casingSet": { "operationId": "camelCase", "properties": "snake_case" } } ``` -------------------------------- ### Copy Values Between JSONPath Targets in OpenAPI Overlay Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/json-path-utilities.md Copies values from a source JSONPath to a target JSONPath within an OpenAPI document. Examples include copying API version information and endpoint descriptions to summaries. ```javascript const overlaid = await openapifmt.openapiOverlay(document, { overlaySet: { actions: [ // Copy version from custom field to info { target: '$.info.version', copy: '$.info.x-api-version' }, // Copy description to summary { target: "$.paths['/pets'].get.summary", copy: "$.paths['/pets'].get.description" } ] } }); ``` -------------------------------- ### Filter OpenAPI Methods Source: https://github.com/thim81/openapi-format/blob/main/readme.md Use the 'methods' filter to remove specific HTTP methods (like GET, POST, PUT) and their associated fields from the OpenAPI document. This is useful for simplifying the specification or focusing on certain operations. ```yaml methods: - get - put - post ``` -------------------------------- ### Sorting OpenAPI Documents with Custom Tweaks Source: https://github.com/thim81/openapi-format/blob/main/readme.md Sorts an OpenAPI document with custom sorting rules, overriding default priorities for specific sections like GET requests. Allows modification of default sort sets before applying them. ```javascript const { parseFile, stringify, writeFile, openapiSort, getDefaultSortSet } = require('openapi-format'); const document = await parseFile('spec.json'); const sortSet = await getDefaultSortSet(); sortSet.get = ['summary', 'description', 'responses']; // override GET priority const {data} = await openapiSort(document, { sort: true, sortSet, sortComponentsSet: ['schemas', 'responses'] }); const output = await stringify(data, {format: 'json'}); await writeFile('spec.sorted.json', output, {format: 'json'}); ``` -------------------------------- ### OpenAPI Format CLI Usage Source: https://github.com/thim81/openapi-format/blob/main/readme.md Basic command structure for using the openapi-format CLI. Specify input and output files, along with various formatting and manipulation options. ```bash openapi-format.js -o [output-file] [options] ``` -------------------------------- ### Overlay Using `extends` Fallback Input Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/config-patterns.md Apply overlay actions to an OpenAPI document that extends from a base file. This pattern allows for modular configuration, where specific overrides are applied to a common base. ```yaml # config/overlay-extends.yaml extends: ./base.yaml actions: - target: "$.info" update: title: "Public API" ``` ```bash openapi-format --overlayFile config/overlay-extends.yaml --output output.yaml ``` -------------------------------- ### Default OpenAPI Sort File Structure Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/configuration.md This JSON defines the default order for root-level elements and common OpenAPI object properties. It specifies the sequence for keys within various sections like 'get', 'post', and 'parameters'. ```json { "root": ["openapi", "info", "servers", "paths", "components", "tags", "x-tagGroups", "externalDocs"], "get": ["operationId", "summary", "description", "parameters", "requestBody", "responses"], "post": ["operationId", "summary", "description", "parameters", "requestBody", "responses"], "put": ["operationId", "summary", "description", "parameters", "requestBody", "responses"], "patch": ["operationId", "summary", "description", "parameters", "requestBody", "responses"], "delete": ["operationId", "summary", "description", "parameters", "requestBody", "responses"], "parameters": ["name", "in", "description", "required", "schema"], "requestBody": ["description", "required", "content"], "responses": ["description", "headers", "content", "links"], "content": [], "components": ["parameters", "schemas"], "schema": ["description", "type", "items", "properties", "format", "example", "default"], "schemas": ["description", "type", "items", "properties", "format", "example", "default"], "properties": ["description", "type", "items", "format", "example", "default", "enum"], "sortPathsBy": "original" } ``` -------------------------------- ### Prevent Type Errors with Utility Checks Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/errors.md This example shows how to use utility functions like `isObject`, `isArray`, and `isString` from `openapi-format` to validate input types before performing operations. This prevents unexpected behavior or failures due to incorrect data types. ```javascript const {isObject, isArray, isString} = require('openapi-format'); if (!isObject(document)) throw new TypeError('Document must be an object'); if (!isString(options.rename)) throw new TypeError('rename must be a string'); if (!isArray(options.filterSet.tags)) throw new TypeError('tags must be an array'); ``` -------------------------------- ### Configure Public API Documentation Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/configuration.md Use this configuration to sort, filter, and apply casing rules for public API documentation. It includes settings for tags, flags, and unused components. ```json { "sort": true, "filterSet": { "tags": ["internal", "beta"], "flags": ["x-exclude"], "unusedComponents": ["schemas", "parameters", "responses"] }, "casingSet": { "operationId": "camelCase", "properties": "camelCase", "componentsSchemas": "PascalCase" } } ``` -------------------------------- ### Write Pre-formatted OpenAPI String to File Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/api-reference/file-utilities.md Shows how to write a pre-formatted OpenAPI document string to a file. This involves first stringifying the document with desired options and then writing the resulting string. ```javascript // Write pre-formatted string const formatted = await openapifmt.stringify(document, {format: 'json'}); await openapifmt.writeFile('./output/openapi.json', formatted); ``` -------------------------------- ### CLI Error: Missing Input Argument Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/errors.md Illustrates a scenario where the `openapi-format` CLI might error due to a missing input file argument. Always provide the input file. ```bash openapi-format -o output.yaml # Error: missing input-file argument (in some versions) ``` -------------------------------- ### Basic CLI Sort and Format Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/INDEX.md Formats and sorts an OpenAPI JSON file using the CLI. Output is written to a specified file. ```bash # Basic sort and format openapi-format openapi.json -o openapi-formatted.json ``` -------------------------------- ### Print to stdout as YAML Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/command-recipes.md Formats an OpenAPI file and prints the output to standard output as YAML. ```bash openapi-format openapi.json --yaml ``` -------------------------------- ### Import and Access OpenAPI Format Functions Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/README.md Import the openapi-format library and access its various processing, file I/O, and utility functions. ```javascript const openapifmt = require('openapi-format'); // Processing openapifmt.openapiSort(doc, options) openapifmt.openapiFilter(doc, options) openapifmt.openapiChangeCase(doc, options) openapifmt.openapiGenerate(doc, options) openapifmt.openapiOverlay(doc, options) openapifmt.openapiSplit(doc, options) openapifmt.openapiConvertVersion(doc, options) openapifmt.openapiRename(doc, options) // File I/O openapifmt.parseFile(path, options) openapifmt.parseString(content, options) openapifmt.stringify(doc, options) openapifmt.writeFile(path, doc, options) openapifmt.readFile(path) openapifmt.detectFormat(path, content) openapifmt.analyzeOpenApi(doc) // Utilities openapifmt.changeCase(text, style, keepChars) openapifmt.changeObjKeysCase(obj, style) openapifmt.changeArrayObjKeysCase(array, style) openapifmt.resolveJsonPath(doc, path) openapifmt.resolveJsonPathValue(doc, path, default) openapifmt.getDefaultSortSet() openapifmt.getDefaultSortComponentsSet() ``` -------------------------------- ### Convert to OpenAPI 3.1 Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/command-recipes.md Converts an OpenAPI file to version 3.1 and saves the output. ```bash openapi-format openapi.yaml --convertTo 3.1 --output dist/openapi.3.1.yaml ``` -------------------------------- ### Apply OpenAPI Overlay with Overlay File Source: https://github.com/thim81/openapi-format/blob/main/readme.md Use this command to apply modifications defined in an overlay file to an OpenAPI document. The result is saved to a new file. ```shell $ openapi-format openapi.yaml --overlayFile overlay.yaml -o openapi-updated.yaml ``` -------------------------------- ### Prepare Public API Documentation Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/INDEX.md Filters internal endpoints and unused schemas, standardizes naming, and sorts fields for public API documentation. ```javascript const doc = await openapifmt.parseFile('./openapi.json'); // Remove internal/beta endpoints and unused schemas const filtered = await openapifmt.openapiFilter(doc, { filterSet: { tags: ['internal', 'beta'], flags: ['x-exclude'], unusedComponents: ['schemas', 'parameters', 'responses'] } }); // Standardize naming const cased = await openapifmt.openapiChangeCase(filtered.data, { casingSet: { operationId: 'camelCase', properties: 'camelCase', componentsSchemas: 'PascalCase' } }); // Sort for readability const sorted = await openapifmt.openapiSort(cased.data, { sortComponentsSet: ['schemas', 'parameters'] }); await openapifmt.writeFile('./public-api.json', sorted.data); ``` -------------------------------- ### Organize Large Specs with Splitting Source: https://github.com/thim81/openapi-format/blob/main/_autodocs/INDEX.md Sorts a large OpenAPI specification and then splits it into a modular multi-file structure for collaboration. ```javascript const doc = await openapifmt.parseFile('./large-api.json'); // Sort first const sorted = await openapifmt.openapiSort(doc, { sortComponentsSet: ['schemas', 'parameters', 'responses'], sortComponentsProps: true }); // Split into modules await openapifmt.openapiSplit(sorted.data, { output: './openapi-split/openapi.yaml' }); // Result structure: // openapi-split/ // openapi.yaml (main file with $refs) // paths/ // /pets.yaml // /pets/{id}.yaml // components/ // schemas/ // Pet.yaml // Error.yaml ``` -------------------------------- ### Bundle OpenAPI Document (Default Behavior) Source: https://github.com/thim81/openapi-format/blob/main/readme.md The default behavior of openapi-format is to bundle all local and remote $ref references, creating a single, self-contained OpenAPI file. This is useful for documentation generation or validation tools that do not support external references. ```shell $ openapi-format input.json -o bundled-openapi.json ``` -------------------------------- ### Convert to OpenAPI 3.2 Source: https://github.com/thim81/openapi-format/blob/main/skills/openapi-format/references/command-recipes.md Converts an OpenAPI file to version 3.2 and saves the output. ```bash openapi-format openapi.yaml --convertTo 3.2 --output dist/openapi.3.2.yaml ``` -------------------------------- ### Format Spec Using Configuration File Source: https://github.com/thim81/openapi-format/blob/main/readme.md Formats an OpenAPI document using options defined in a configuration file. All available format options can be used in the config file. ```shell $ openapi-format openapi.yaml --configFile openapi-format-options.json ```