Skip to content
Back to search

openapi-format

Format an OpenAPI document by ordering, formatting and filtering fields.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/thim81--openapi-format/badge.svg)](/listings/thim81--openapi-format)

HTML

<a href="/listings/thim81--openapi-format"><img src="/api/listings/thim81--openapi-format/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

NPX usage (recommended)

To execute the CLI without installing it via npm, use the npx method

$ npx openapi-format your-openapi-file.yaml

Local Installation

While possible to install globally, we recommend that you add the openapi-format CLI to the `node_modules` by using:

$ npm install --save openapi-format

Global Installation

$ npm install -g openapi-format

AI (OpenAI Codex/Claude Code/...) skill usage

To install the `openapi-format` skill from this repository:

$ npx skills add https://github.com/thim81/openapi-format --skill openapi-format

Then use it in Claude, Codex by explicitly referencing the skill in your prompt, for example:

Using $openapi-format, create a minimal filter config to remove internal endpoints and give me the CLI command.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

readme.md · README · 1,760 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ![openapi-format icon](./assets/openapi-format-logo.svg)
  2. <a href="https://www.npmjs.com/package/openapi-format" alt="Latest Stable Version">![npm](https://img.shields.io/npm/v/openapi-format.svg)</a>
  3. <a href="https://www.npmjs.com/package/openapi-format" alt="Total Downloads">![npm](https://img.shields.io/npm/dw/openapi-format.svg)</a>
  4. <a href="https://www.npmjs.com/package/openapi-format" alt="Total Downloads">![npm](https://img.shields.io/npm/dt/openapi-format.svg)</a>
  5. # openapi-format
  6. Format an OpenAPI document by ordering, formatting, filtering, and applying overlays to OpenAPI documents.
  7. The openapi-format CLI can sort the OpenAPI fields by ordering them in a hierarchical order, format the casing of the fields and
  8. output cleanly indented JSON or YAML.
  9. Additional features include powerful filtering options based on flags, tags, methods, operationIDs, and even unused components.
  10. To quickly standardize OpenAPI documents there is support for generating the operationIds and apply casing rules for consistency.
  11. The CLI can split large OpenAPI documents into modular, multi-file structures for easier management.
  12. For upgrades, the openapi-format CLI offers the option to convert an OpenAPI 3.0 or 3.1 document to OpenAPI 3.1 or 3.2.
  13. With the OpenAPI Overlay support, users can overlay changes onto existing OpenAPI documents, to extend and customize the OpenAPI document.
  14. ## Table of content
  15. * [Use-cases](#use-cases)
  16. * [Features](#features)
  17. * [Online playground](#online-playground)
  18. * [Installation](#installation)
  19. + [Local Installation (recommended)](#local-installation-recommended)
  20. + [Global Installation](#global-installation)
  21. + [NPX usage](#npx-usage)
  22. + [Codex skill usage](#codex-skill-usage)
  23. * [Command Line Interface](#command-line-interface)
  24. * [OpenAPI format CLI options](#openapi-format-cli-options)
  25. * [OpenAPI sort configuration options](#openapi-sort-configuration-options)
  26. * [OpenAPI formatting configuration options](#openapi-formatting-configuration-options)
  27. * [OpenAPI filter options](#openapi-filter-options)
  28. * [OpenAPI generate elements](#openapi-generate-options)
  29. * [CLI sort usage](#cli-sort-usage)
  30. * [CLI filter usage](#cli-filter-usage)
  31. * [CLI OpenAPI overlay usage](#cli-openapi-overlay-usage)
  32. * [CLI generate usage](#cli-generate-usage)
  33. * [CLI casing usage](#cli-casing-usage)
  34. * [CLI split & bundle usage](#cli-bundle--split-usage)
  35. * [CLI rename usage](#cli-rename-usage)
  36. * [CLI convertTo usage](#cli-convertto-usage)
  37. * [CLI configuration usage](#cli-configuration-usage)
  38. * [Programmatic usage](#programmatic-usage)
  39. * [Credits](#credits)
  40. ## Use-cases
  41. **Public documentation:**
  42. An OpenAPI document is a specification that evolves and changes. To facilitate working with the specification and publishing the
  43. document as public documentation, you want to deliver a clean and structured specification. OpenAPI-format helps you to
  44. organize the fields by sorting, formatting and filtering specific elements from the OpenAPI like internal endpoints, beta tags, ...
  45. and even unused schemas, examples, responses, ... with a clean and optimized OpenAPI document as a result.
  46. **Maintenance:**
  47. When working on large OpenAPI documents or with multiple team members, the file can be become messy and difficult to
  48. compare changes. By sorting & formatting from time to time, the fields are all ordered in a structured manner & properly cased, which will help you
  49. to maintain the file with greater ease.
  50. **CI/CD pipelines:**
  51. OpenAPI-format can be useful in CI/CD pipelines, where the OpenAPI is used as the source for other documents like Web documentation,
  52. Postman collections, test suites, ...
  53. ## Features
  54. - [x] Order OpenAPI fields in a default order
  55. - [x] Order OpenAPI fields in a custom order
  56. - [x] Order Components elements by alphabet
  57. - [x] Filter OpenAPI files based on methods
  58. - [x] Filter OpenAPI files based on flags
  59. - [x] Filter OpenAPI files based on flags values
  60. - [x] Filter OpenAPI files based on tags
  61. - [x] Filter OpenAPI files based on operationID's
  62. - [x] Filter OpenAPI files based on operations definition
  63. - [x] Filter OpenAPI files based on response content-types
  64. - [x] Format the casing (camelCase,PascalCase, ...) of component elements
  65. - [x] Apply OpenAPI Overlay actions
  66. - [x] Strip flags from OpenAPI files
  67. - [x] Strip unused components from OpenAPI files
  68. - [x] Generate OpenAPI elements for consistency
  69. - [x] Bundle local and remote references in the OpenAPI document
  70. - [x] Split the OpenAPI document into a multi-file structure
  71. - [x] Convert OpenAPI 3.0 documents to OpenAPI 3.1 or 3.2
  72. - [x] Convert OpenAPI 3.1 documents to OpenAPI 3.2
  73. - [x] Rename the OpenAPI title
  74. - [x] Support OpenAPI documents in JSON format
  75. - [x] Support OpenAPI documents in YAML format
  76. - [x] Format via CLI
  77. - [x] Format via local or remote config files
  78. - [x] Use as a Module
  79. - [x] Support for OpenAPI 3.0
  80. - [x] Support for OpenAPI 3.1
  81. - [x] Support for OpenAPI 3.2
  82. - [x] Online playground ([playground.openapi-format.com](https://playground.openapi-format.com/))
  83. ## Online playground
  84. The [OpenAPI-Format Playground](https://playground.openapi-format.com/) is a web-based tool for formatting, sorting, filtering, previewing, and comparing OpenAPI documents, powered by the `openapi-format` CLI.
  85. You can also explore the website at [openapi-format.com](https://openapi-format.com/).
  86. <a href="https://playground.openapi-format.com/" target="_blank" title="OpenAPI-format Playground" rel="nofollow">
  87. <img src="https://openapi-format.com/screenshots/openapi-format-playground-code-view.png" alt="OpenAPI-format Playground code view" width="76%"><br>
  88. <img src="https://openapi-format.com/screenshots/openapi-format-playground-preview-view.png" alt="OpenAPI-format Playground preview view" width="25%">
  89. <img src="https://openapi-format.com/screenshots/openapi-format-playground-diff-view.png" alt="OpenAPI-format Playground diff view" width="25%">
  90. <img src="https://openapi-format.com/screenshots/openapi-format-playground-overlay-actions.png" alt="OpenAPI-format Playground overlay actions" width="25%">
  91. </a>
  92. More info about the playground features and usage can be found on the [website](https://openapi-format.com/).
  93. ## Installation
  94. ### NPX usage (recommended)
  95. To execute the CLI without installing it via npm, use the npx method
  96. ```shell
  97. $ npx openapi-format your-openapi-file.yaml
  98. ```
  99. ### Local Installation
  100. While possible to install globally, we recommend that you add the openapi-format CLI to the `node_modules` by using:
  101. ```shell
  102. $ npm install --save openapi-format
  103. ```
  104. ### Global Installation
  105. ```shell
  106. $ npm install -g openapi-format
  107. ```
  108. ### AI (OpenAI Codex/Claude Code/...) skill usage
  109. To install the `openapi-format` skill from this repository:
  110. ```shell
  111. $ npx skills add https://github.com/thim81/openapi-format --skill openapi-format
  112. ```
  113. Then use it in Claude, Codex by explicitly referencing the skill in your prompt, for example:
  114. ```text
  115. Using $openapi-format, create a minimal filter config to remove internal endpoints and give me the CLI command.
  116. ```
  117. ## Command Line Interface
  118. ```
  119. openapi-format.js <input-file> -o [output-file] [options]
  120. Arguments:
  121. input-file the OpenAPI document can be a local or remote file in JSON or YAML format
  122. output-file the output file is optional and can be either a .json or .yaml file.
  123. Options:
  124. --output, -o Save the formatted OpenAPI file as JSON/YAML [path]
  125. --sortFile The file to specify custom OpenAPI fields ordering [path]
  126. --casingFile The file to specify casing rules [path]
  127. --generateFile The file to specify generate rules [path]
  128. --filterFile The file to specify filter rules [path]
  129. --overlayFile The file to specify OpenAPI overlay actions [path]
  130. --no-sort Don't sort the OpenAPI file [boolean]
  131. --keepComments Don't remove the comments from the OpenAPI YAML file [boolean]
  132. --yamlBlockStyle YAML block style: preserve, auto, literal, folded [string]
  133. --yamlQuoteStyle Preferred YAML quote style: single, double, detect [string]
  134. --yamlCompat YAML compatibility schema for older OpenAPI tools [string]
  135. --sortComponentsFile The file with components to sort alphabetically [path]
  136. --sortComponentsProps Sort properties within schema components alphabetically [boolean]
  137. --no-bundle Don't bundle the local and remote $ref [boolean]
  138. --split Split OpenAPI document into a multi-file structure [boolean]
  139. --rename Rename the OpenAPI title [string]
  140. --convertTo convert the OpenAPI document to OpenAPI version 3.1 or 3.2 [string]
  141. --configFile The file with the OpenAPI-format CLI options [path]
  142. --lineWidth Max line width of YAML output [number]
  143. --json Prints the file to stdout as JSON [boolean]
  144. --yaml Prints the file to stdout as YAML [boolean]
  145. --playground, -p Open config in online playground
  146. --help Show help [boolean]
  147. --version Output the version number
  148. --verbose Output more details of the filter process [count]
  149. ```
  150. ## OpenAPI format CLI options
  151. | Parameter | Alias | Description | Input type | Default | Info |
  152. |-----------------------|---------------|-----------------------------------------------------------------------------|--------------|----------------------------|----------|
  153. | file | | the OpenAPI document can be a local or remote file in JSON or YAML format | path to file | | required |
  154. | --output | -o | save the formatted OpenAPI file as JSON/YAML | path to file | | optional |
  155. | --sortFile | -s | the file to specify custom OpenAPI fields ordering | path to file | defaultSort.json | optional |
  156. | --filterFile | -f | the file to specify filter setting | path to file | defaultFilter.json | optional |
  157. | --casingFile | -k | the file to specify casing setting | path to file | | optional |
  158. | --generateFile | -g | the file to specify generate rules | path to file | | optional |
  159. | --overlayFile | -l | the file to specify OpenAPI overlay actions | path to file | | optional |
  160. | --no-sort | | don't sort the OpenAPI file | boolean | FALSE | optional |
  161. | --keepComments | | don't remove the comments from the OpenAPI YAML file | boolean | FALSE | optional |
  162. | --yamlBlockStyle | | YAML block style (`preserve`, `auto`, `literal`, `folded`) | string | preserve | optional |
  163. | --yamlQuoteStyle | | preferred YAML quote style for YAML output (`single`, `double`, `detect`) | string | detect | optional |
  164. | --yamlCompat | | YAML compatibility schema for older OpenAPI tools (`yaml-1.1`) | string | | optional |
  165. | --sortComponentsFile | | sort the items of the components (schemas, parameters, ...) by alphabet | path to file | defaultSortComponents.json | optional |
  166. | --sortComponentsProps | | sort properties within schema components alphabetically | boolean | FALSE | optional |
  167. | --no-bundle | | don't bundle the local and remote $ref in the OpenAPI document | boolean | FALSE | optional |
  168. | --split | | split the OpenAPI document into a multi-file structure | boolean | FALSE | optional |
  169. | --rename | | rename the OpenAPI title | string | | optional |
  170. | --convertTo | | convert the OpenAPI document to OpenAPI version 3.1 or 3.2 | string | | optional |
  171. | --configFile | -c | the file with all the format config options | path to file | | optional |
  172. | --lineWidth | | max line width of YAML output | number | -1 (Infinity) | optional |
  173. | --json | | prints the file to stdout as JSON | | FALSE | optional |
  174. | --yaml | | prints the file to stdout as YAML | | FALSE | optional |
  175. | --playground | -p | open config in online playground | | | optional |
  176. | --version | | output the version number | | | optional |
  177. | --verbose | -v, -vv, -vvv | verbosity that can be increased, which will show more output of the process | | | optional |
  178. | --help | h | display help for command | | | optional |
  179. ## OpenAPI sort configuration options
  180. The CLI will sort the OpenAPI document in the defined order liked defined per OpenAPI key/field/property/element. The fields that are
  181. not specified will keep their order like it is in the original OpenAPI document, so only defined fields will be
  182. re-ordered.
  183. The default sorting of the different fields based on the defined order (listed in the table below), which is stored in
  184. the [defaultSort.json](https://github.com/thim81/openapi-format/blob/main/defaultSort.json) file.
  185. ### OpenAPI sort fields
  186. You can easily modify this by specifying your own ordering per key, which can be passed on to the CLI (see below for an
  187. example on how to do this).
  188. | Key | Ordered by | OpenAPI reference |
  189. |-------------|-----------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
  190. | root | - openapi<br>\- info<br>\- servers<br>\- paths<br>\- components<br>\- tags<br>\- x-tagGroups<br>\- externalDocs | [openapi-object](https://spec.openapis.org/oas/v3.0.3.html#openapi-object) |
  191. | get | - operationId<br>\- summary<br>\- description<br>\- parameters<br>\- requestBody<br>\- responses | [operationObject](https://spec.openapis.org/oas/v3.0.3.html#operationObject) |
  192. | post | - operationId<br>\- summary<br>\- description<br>\- parameters<br>\- requestBody<br>\- responses | [operationObject](https://spec.openapis.org/oas/v3.0.3.html#operationObject) |
  193. | put | - operationId<br>\- summary<br>\- description<br>\- parameters<br>\- requestBody<br>\- responses | [operationObject](https://spec.openapis.org/oas/v3.0.3.html#operationObject) |
  194. | patch | - operationId<br>\- summary<br>\- description<br>\- parameters<br>\- requestBody<br>\- responses | [operationObject](https://spec.openapis.org/oas/v3.0.3.html#operationObject) |
  195. | delete | - operationId<br>\- summary<br>\- description<br>\- parameters<br>\- requestBody<br>\- responses | [operationObject](https://spec.openapis.org/oas/v3.0.3.html#operationObject) |
  196. | parameters | - name<br>\- in<br>\- description<br>\- required<br>\- schema | [parameterObject](https://spec.openapis.org/oas/v3.0.3.html#parameterObject) |
  197. | requestBody | - description<br>\- headers<br>\- content<br>\- links | [request-body-object](https://spec.openapis.org/oas/v3.0.3.html#request-body-object) |
  198. | responses | - description<br>\- headers<br>\- content<br>\- links | [responses-object](https://spec.openapis.org/oas/v3.0.3.html#responses-object) |
  199. | content | (By alphabet) | [responses-object](https://spec.openapis.org/oas/v3.0.3.html#responses-object) |
  200. | components | - parameters<br>\- schemas | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  201. | schema | - description<br>\- type<br>\- items<br>\- properties<br>\- format<br>\- example<br>\- default | [schemaObject](https://spec.openapis.org/oas/v3.0.3.html#schemaObject) |
  202. | schemas | - description<br>\- type<br>\- items<br>\- properties<br>\- format<br>\- example<br>\- default | |
  203. | properties | - description<br>\- type<br>\- items<br>\- format<br>\- example<br>\- default<br>\- enum | |
  204. Have a look at the folder [yaml-default](test/yaml-default) and compare the "output.yaml" (sorted document) with the "input.yaml" (original document), to see how openapi-format have sorted the OpenAPI document.
  205. ### OpenAPI sort Paths
  206. You can change the order of the paths defined in the OpenAPI specification and sort them alphabetically (`path`) or by the first tag of the first method (`tags`).
  207. Options to sort by:
  208. - `original` (default): keep the order as defined in the OpenAPI specification
  209. - `path`: order the paths alphabetically by the path parts
  210. - `tags`: order by the first tag of the first method
  211. | Key | Options | OpenAPI reference |
  212. |-------------|------------------------------|------------------------------------------------------------------------|
  213. | sortPathsBy | 'original' / 'path' / 'tags' | [paths-object](https://spec.openapis.org/oas/v3.0.3.html#paths-object) |
  214. ## OpenAPI filter options
  215. By specifying the desired filter values for the available filter types, the openapi-format CLI will strip out any
  216. matching item from the OpenAPI document. You can combine multiple types to filter out a range of OpenAPI items.
  217. | Type | Description | Type | Examples |
  218. |------------------------|---------------------------------------------|---------|-------------------------------------------|
  219. | methods | OpenAPI methods. | array | ['get','post','put'] |
  220. | inverseMethods | OpenAPI methods that will be kept | array | ['get','post','put'] |
  221. | tags | OpenAPI tags | array | ['pet','user'] |
  222. | inverseTags | OpenAPI tags that will be kept | array | ['pet','user'] |
  223. | operationIds | OpenAPI operation ID's | array | ['findPetsByStatus','updatePet'] |
  224. | inverseOperationIds | OpenAPI operation ID's that will be kept | array | ['findPetsByStatus','updatePet'] |
  225. | operations | OpenAPI operations | array | ['GET::/pets','PUT::/pets'] |
  226. | flags | Custom flags | array | ['x-exclude','x-internal'] |
  227. | inverseFlags | Custom flags that will kept | array | ['x-exclude','x-internal'] |
  228. | flagValues | Custom flags with a specific value | array | ['x-version: 1.0','x-version: 3.0'] |
  229. | inverseFlagValues | Custom flags with a value that will be kept | array | ['x-version: 1.0','x-version: 3.0'] |
  230. | responseContent | Response Content types | array | ['application/json','application/html'] |
  231. | inverseResponseContent | Response Content types that will kept | array | ['application/ld+json'] |
  232. | requestContent | Request Body Content types | array | ['application/json','application/html'] |
  233. | inverseRequestContent | Request Body Content types that will kept | array | ['application/ld+json'] |
  234. | unusedComponents | Unused components | array | ['examples','schemas'] |
  235. | stripFlags | Custom flags that will be stripped | array | ['x-exclude','x-internal'] |
  236. | preserveEmptyObjects | Preserve empty object | boolean | true OR ['schema'] |
  237. | textReplace | Search & replace values to replace | array | [{'searchFor':'Pet','replaceWith':'Dog'}] |
  238. Some more details on the available filter types:
  239. ### Filter - methods/inverseMethods
  240. => **methods**: Refers to the [Path Item Object](http://spec.openapis.org/oas/v3.0.3.html#operationObject)
  241. This will remove all fields and attached fields that match the verbs. In the example below, this would mean that
  242. all `get`, `put`, `post` items would be removed from the OpenAPI document.
  243. ```yaml
  244. openapi: 3.0.0
  245. info:
  246. title: API
  247. version: 1.0.0
  248. paths:
  249. /pets:
  250. get:
  251. summary: Finds Pets by status
  252. put:
  253. summary: Update an existing pet
  254. ```
  255. => **inverseMethods**: This option does the inverse filtering, by keeping only the verbs defined and remove all other verbs.
  256. ### Filter - tags
  257. => **tags**: Refers to the "tags" field from the "Operation
  258. Object" https://spec.openapis.org/oas/v3.0.3.html#operationObject
  259. This will remove all fields and attached fields that match the tags. In the example below, this would mean that all
  260. items with the tags `pet` or `user` would be removed from the OpenAPI document.
  261. For example:
  262. ```yaml
  263. openapi: 3.0.0
  264. info:
  265. title: API
  266. version: 1.0.0
  267. paths:
  268. /pets:
  269. put:
  270. tags:
  271. - pet
  272. summary: Update an existing pet
  273. ```
  274. => **inverseTags**: This option does the inverse filtering, by keeping only the tags defined and remove all other tags, including the operations without a tags.
  275. ### Filter - operationIds
  276. => **operationIds**: Refers to the "operationId" field from the [Operation Object](https://spec.openapis.org/oas/v3.0.3.html#operationObject)
  277. This will remove specific fields and attached fields that match the operation ID's. In the example below, this would
  278. mean that the item with operationID `findPetsByStatus` would be removed from the OpenAPI document.
  279. For example:
  280. ```yaml
  281. openapi: 3.0.0
  282. info:
  283. title: API
  284. version: 1.0.0
  285. paths:
  286. /pets:
  287. get:
  288. operationId: findPetsByStatus
  289. ```
  290. => **inverseTags**: This option does the inverse filtering, by keeping only the operationIds defined and remove all other operationIds, including the operations without an operationId.
  291. ### Filter - operations
  292. => **operations**: Refers to a combination of a OpenAPI method & path from the [Path Object](https://spec.openapis.org/oas/v3.0.3.html#paths-object)
  293. & [Path item](https://spec.openapis.org/oas/v3.0.3.html#path-item-object)
  294. This will remove specific path items that match the operation definition `PUT::/pets`. In the example below, this would
  295. mean that the item with the path '/pets' and method 'PUT' would be removed from the OpenAPI document.
  296. For example:
  297. ```yaml
  298. openapi: 3.0.0
  299. info:
  300. title: API
  301. version: 1.0.0
  302. paths:
  303. /pets:
  304. get:
  305. summary: Finds Pets by status
  306. put:
  307. summary: Update an existing pet
  308. ```
  309. An `operationId` is an optional property. To offer support for OpenAPI documents that don't have operationIds, we have
  310. added the `operation` definition which is the unique combination of the OpenAPI method & path, with a `::` separator
  311. symbol.
  312. This will allow filtering for very specific OpenAPI items, without the need of adding operationIds to the OpenAPI
  313. document.
  314. To facilitate managing the filtering, we have included wildcard options for the `operations` option, supporting the
  315. methods & path definitions.
  316. REMARK: Be sure to put quotes around the target definition.
  317. Strict matching example: `"GET::/pets"`
  318. This will target only the "GET" method and the specific path "/pets"
  319. Method wildcard matching example: `"*::/pets"`
  320. This will target all methods ('get', 'query', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace') and the specific
  321. path "/pets"
  322. Path wildcard matching example: `"GET::/pets/*"`
  323. This will target only the "GET" method and any path matching any folder behind the "/pets", like "/pets/123" and
  324. "/pets/123/buy".
  325. Method & Path wildcard matching example: `"*::/pets/*"`
  326. A combination of wildcards for the method and path parts is even possible.
  327. ### Filter - flags/inverseFlags
  328. => **flags**: Refers to a custom property that can be set on any field in the OpenAPI document.
  329. This will remove all fields and attached fields that match the flags. In the example below, this would mean that all
  330. items with the flag `x-exclude` would be removed from the OpenAPI document.
  331. For example:
  332. ```yaml
  333. openapi: 3.0.0
  334. info:
  335. title: API
  336. version: 1.0.0
  337. paths:
  338. /pets:
  339. get:
  340. x-exclude: true
  341. ```
  342. => **inverseFlags**: This option does the inverse filtering, by keeping only the path operations, tags, x-tagGroups that match the flag(s). This is a very aggressive option to keep only the items that are needed but it will keep the components. The components can best be filtered out, by using the "[unusedComponents](https://github.com/thim81/openapi-format#filter---unusedcomponents)" filter option.
  343. ### Filter - flagValues/inverseFlagValues
  344. => **flagValues**: Refers to a flag, custom property which can be set on any field in the OpenAPI document, and the combination with the value for that flag.
  345. This will remove all fields and attached fields that match the flag with the specific value.
  346. A `flagValues` example:
  347. ```yaml
  348. flagValues:
  349. - x-version: 1.0
  350. - x-version: 3.0
  351. ```
  352. In the example below, this would mean that all items with the flag `x-version` that matches `x-version: 1.0` OR `x-version: 3.0` would be removed from the OpenAPI document.
  353. ```yaml
  354. openapi: 3.0.0
  355. info:
  356. title: API
  357. version: 1.0.0
  358. paths:
  359. /pets:
  360. get:
  361. x-version: 1.0
  362. ```
  363. The filter option `flagValues` also will remove flags that contain an array of values in the OpenAPI document.
  364. A `flagValues` example:
  365. ```yaml
  366. flagValues:
  367. - x-versions: 1.0
  368. - x-versions: 2.0
  369. ```
  370. In the example below, this would mean that all items with the flag `x-versions`, which is an array, that match `x-version: 1.0` OR `x-version: 3.0` would be removed from the OpenAPI document.
  371. ```yaml
  372. openapi: 3.0.0
  373. info:
  374. title: API
  375. version: 1.0.0
  376. paths:
  377. /pets:
  378. get:
  379. x-versions:
  380. - 1.0
  381. - 3.0
  382. - 5.0
  383. ```
  384. Have a look at [flagValues](test/yaml-filter-custom-flagsvalue-value) and [flagValues for array values](test/yaml-filter-custom-flagsvalue-array) for a practical example.
  385. => **inverseFlagValues**: This option does the inverse filtering, by keeping only the path operations, tags, x-tagGroups that match the flag with the specific value. This is a very aggressive option to keep only the items that are needed but it will keep the components. The components can best be filtered out, by using the "[unusedComponents](https://github.com/thim81/openapi-format#filter---unusedcomponents)" filter option.
  386. ### Filter - responseContent/inverseResponseContent
  387. => **ResponseContent**: Refers to the [Response Object's content](https://spec.openapis.org/oas/v3.0.3.html#response-object)
  388. A responses `content` filter example:
  389. ```yaml
  390. responseContent:
  391. - application/json
  392. ```
  393. This will remove all the content that match the media types from the responses. In the example below, this would mean that all `application/json`
  394. content items would be removed from the OpenAPI document
  395. Example before:
  396. ```yaml
  397. openapi: 3.0.0
  398. info:
  399. title: API
  400. version: 1.0.0
  401. paths:
  402. /pet:
  403. post:
  404. tags:
  405. - pet
  406. summary: Add a new pet to the store
  407. description: Add a new pet to the store
  408. operationId: addPet
  409. x-visibility: true
  410. responses:
  411. '200':
  412. description: Successful operation
  413. content:
  414. application/xml:
  415. schema:
  416. $ref: '#/components/schemas/Pet'
  417. application/json:
  418. schema:
  419. $ref: '#/components/schemas/Pet'
  420. '405':
  421. description: Invalid input
  422. ```
  423. Example after:
  424. ```yaml
  425. openapi: 3.0.0
  426. info:
  427. title: API
  428. version: 1.0.0
  429. paths:
  430. /pet:
  431. post:
  432. tags:
  433. - pet
  434. summary: Add a new pet to the store
  435. description: Add a new pet to the store
  436. operationId: addPet
  437. x-visibility: true
  438. responses:
  439. '200':
  440. description: Successful operation
  441. content:
  442. application/xml:
  443. schema:
  444. $ref: '#/components/schemas/Pet'
  445. '405':
  446. description: Invalid input
  447. ```
  448. => **inverseResponseContent**: This option does the inverse filtering, by keeping only the content with media types defined and remove all other content.
  449. ### Filter - requestContent/inverseRequestContent
  450. => **requestContent**: Refers to the [Request Body Object's content](https://spec.openapis.org/oas/v3.0.3.html#request-body-object)
  451. A request body `content` filter example:
  452. ```yaml
  453. requestContent:
  454. - application/json
  455. ```
  456. This will remove all the content that match the media types from the request body. In the example below, this would mean that all `application/json`
  457. content items would be removed from the OpenAPI document.
  458. Example before:
  459. ```yaml
  460. openapi: 3.0.0
  461. info:
  462. title: API
  463. version: 1.0.0
  464. paths:
  465. /pet:
  466. post:
  467. tags:
  468. - pet
  469. summary: Add a new pet to the store
  470. description: Add a new pet to the store
  471. operationId: addPet
  472. x-visibility: true
  473. requestBody:
  474. content:
  475. application/xml:
  476. schema:
  477. $ref: '#/components/schemas/Pet'
  478. application/json:
  479. schema:
  480. $ref: '#/components/schemas/Pet'
  481. ```
  482. Example after:
  483. ```yaml
  484. openapi: 3.0.0
  485. info:
  486. title: API
  487. version: 1.0.0
  488. paths:
  489. /pet:
  490. post:
  491. tags:
  492. - pet
  493. summary: Add a new pet to the store
  494. description: Add a new pet to the store
  495. operationId: addPet
  496. x-visibility: true
  497. requestBody:
  498. content:
  499. application/xml:
  500. schema:
  501. $ref: '#/components/schemas/Pet'
  502. ```
  503. => **inverseRequestContent**: This option does the inverse filtering, by keeping only the content with media types defined and remove all other content types from the request body.
  504. ### Filter - unusedComponents
  505. => **unusedComponents**: Refers to a list of [reusable component types]( https://spec.openapis.org/oas/v3.0.3.html#components-object), from which unused items will be removed.
  506. This option allows you to strip the OpenAPI document from any unused items of the targeted `components` types.
  507. Any item in the list of OpenAPI `components` that is not referenced as `$ref`, will get marked and removed from the OpenAPI document.
  508. REMARK: We will recursively strip all unused components, with a maximum depth of 10 times. This means that "nested" components, that become unused, will also get removed
  509. Supported component types that can be marked as "unused":
  510. - schemas
  511. - parameters
  512. - examples
  513. - headers
  514. - requestBodies
  515. - responses
  516. - mediaTypes
  517. ### Filter - textReplace
  518. => **textReplace**: "search & replace" option to replace text in the OpenAPI specification
  519. The `textReplace` provides a "search & replace" method, that will search for a text/word/characters in the OpenAPI description, summary, URL fields and replace it with another text/word/characters.
  520. This is very useful to replace data in the OpenAPI specification.
  521. A `textReplace` example:
  522. ```yaml
  523. textReplace:
  524. - searchFor: 'Pets'
  525. replaceWith: 'Dogs'
  526. - searchFor: 'swagger.io'
  527. replaceWith: 'openapis.org'
  528. ```
  529. This will replace all "Pets" with "Dogs" & "swagger.io" with "openapi.org" in the OpenAPI document.
  530. ### Filter - stripFlags
  531. => **stripFlags**: Refers to a list of custom properties that can be set on any field in the OpenAPI document.
  532. The `stripFlags` will remove only the flags, the linked parent and properties will remain. In the example below, this would mean that all
  533. flags `x-exclude` itself would be stripped from the OpenAPI document.
  534. Example before:
  535. ```yaml
  536. openapi: 3.0.0
  537. info:
  538. title: API
  539. version: 1.0.0
  540. paths:
  541. /pets:
  542. get:
  543. x-exclude: true
  544. summary: Finds Pets by status
  545. ```
  546. Example after:
  547. ```yaml
  548. openapi: 3.0.0
  549. info:
  550. title: API
  551. version: 1.0.0
  552. paths:
  553. /pets:
  554. get:
  555. summary: Finds Pets by status
  556. ```
  557. ### Filter - preserveEmptyObjects
  558. => **preserveEmptyObjects**: Refers to any properties of your OpenAPI document, from which empty object values would be kept.
  559. The `preserveEmptyObjects` will preserve all empty objects if set to `true`.
  560. You can also pass a list of keys from which preserve empty objects. For instance a `['schema']` value would only prevent removal of empty objects having for key `schema`.
  561. REMARK: Please note that openapi-format default behavior is to remove all empty objects from your document, except for items of examples, security, schemas, default, oneOf, allOf.
  562. ```yaml
  563. openapi: 3.0.0
  564. info:
  565. title: API
  566. version: 1.0.0
  567. paths:
  568. /pets:
  569. post:
  570. requestBody:
  571. description: Create a new pet in the store
  572. required: true
  573. content:
  574. application/json:
  575. schema: {}
  576. ```
  577. Example after (with `preserveEmptyObjects: false`):
  578. ```yaml
  579. openapi: 3.0.0
  580. info:
  581. title: API
  582. version: 1.0.0
  583. paths:
  584. /pets:
  585. post:
  586. requestBody:
  587. description: Create a new pet in the store
  588. required: true
  589. content:
  590. application/json: {}
  591. ```
  592. ## OpenAPI formatting configuration options
  593. Tools like [spectral](https://github.com/stoplightio/spectral) or [speccy](https://speccy.io/), or any of the [linting tools](https://nordicapis.com/8-openapi-linters/), provide a manner to validate & lint OpenAPI specifications to be uniform. The linting tool informs about the incorrect usage of OpenAPI properties & inconsistent field names.
  594. This is very useful and helps to guard the quality of the OpenAPI specification. They inform which fields to correct so that the specification will comply with all the defined linting rules.
  595. The openapi-format CLI formatting option can assist with keeping the field names consistent by automatically changing the casing of the properties/keys/names for the different elements in the OpenAPI document.
  596. The desired casing can be defined per OpenAPI key/element (see list below).
  597. The keys that are not specified will keep their casing like it is in the original OpenAPI document, so only for defined fields, the casing will be changed.
  598. | Key | Description | OpenAPI reference |
  599. |----------------------------|------------------------------------------------------------------------------------------------------| ------------------------------------------------------------------------- |
  600. | operationId | Changes operation ID's that are part of the Operations Object | [operation-object](https://spec.openapis.org/oas/v3.0.3.html#operation-object)|
  601. | properties | Changes property keys of the schemas of the inline response/requestBody & components | [schemaObject](https://spec.openapis.org/oas/v3.0.3.html#schemaObject) |
  602. | parametersCookie | Changes the cookie name of the parameters inline & models in the components | [parameter-object](https://spec.openapis.org/oas/v3.0.3.html#parameter-object) |
  603. | parametersPath | Changes the path name of the parameters inline & models in the components | [parameter-object](https://spec.openapis.org/oas/v3.0.3.html#parameter-object) |
  604. | parametersHeader | Changes the header name of the parameters inline & models in the components | [parameter-object](https://spec.openapis.org/oas/v3.0.3.html#parameter-object) |
  605. | parametersQuery | Changes the query name of the parameters inline & models in the components | [parameter-object](https://spec.openapis.org/oas/v3.0.3.html#parameter-object) |
  606. | componentsParametersCookie | Changes the key of the cookie models in the components parameters sections & "$ref" links | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  607. | componentsParametersPath | Changes the key of the path models in the components parameters sections & "$ref" links | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  608. | componentsParametersQuery | Changes the key of the query models in the components parameters sections & "$ref" links | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  609. | componentsParametersHeader | Changes the key of the header models in the components parameters sections & "$ref" links | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  610. | componentsSchemas | Changes the key of the schema models in the components sections & "$ref" links | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  611. | componentsExamples | Changes the key of the example models in the components sections & "$ref" links | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  612. | componentsHeaders | Changes the key of the header models in the components sections & "$ref" links | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  613. | componentsResponses | Changes the key of the response models in the components sections & "$ref" links | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  614. | componentsRequestBodies | Changes the key of the request body models in the components sections & "$ref" links | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  615. | componentsSecuritySchemes | Changes the key of the security schemes in the components sections & "$ref" links | [components-object](https://spec.openapis.org/oas/v3.0.3.html#components-object) |
  616. ### Casing options
  617. | Casing type | Casing alias | Description | Example |
  618. | -----------------| ------------ | ------------------------------------------------- | --------------- |
  619. | 🐪 camelCase | camelCase | converts a strings to `camelCase` | `openapiFormat` |
  620. | 👨‍🏫 PascalCase | PascalCase | converts a strings to `PascalCase` | `OpenapiFormat` |
  621. | 🥙 kebab-case | kebabCase | converts a strings to `kebab-case` | `openapi-format` |
  622. | 🚂 Train-Case | TrainCase | converts a strings to `Train-Case` | `Openapi-Format` |
  623. | 🐍 snake_case | snakeCase | converts a strings to `snake_case` | `openapi_format` |
  624. | 🕊 Ada_Case | AdaCase | converts a strings to `Ada_Case` | `Openapi_Format` |
  625. | 📣 CONSTANT_CASE | constantCase | converts a strings to `CONSTANT_CASE` | `OPENAPI_FORMAT` |
  626. | 👔 COBOL-CASE | cobolCase | converts a strings to `COBOL-CASE` | `OPENAPI-FORMAT` |
  627. | 📍 Dot.notation | dotNotation | converts a strings to `Dot.notation` | `openapi.format` |
  628. | 🛰 Space case | spaceCase | converts a strings to `Space case` (with spaces) | `openapi format` |
  629. | 🏛 Capital Case | capitalCase | converts a strings to `Capital Case` (with spaces)| `Openapi Format` |
  630. | 🔡 lower case | lowerCase | converts a strings to `lower case` (with spaces) | `openapi format` |
  631. | 🔠 UPPER CASE | upperCase | converts a strings to `UPPER CASE` (with spaces) | `OPENAPI FORMAT` |
  632. > REMARK: All special characters are stripped during conversion, except for the `@` and `$`, since they can be part of the query strings.
  633. The casing options are provided by the nano NPM [case-anything](https://github.com/mesqueeb/case-anything) package.
  634. ### Format casing - operationId
  635. => **operationId**: Refers to the `operationId` properties in the OpenAPI document.
  636. Formatting casing example:
  637. ```yaml
  638. operationId: kebab-case
  639. ```
  640. Example before:
  641. ```yaml
  642. openapi: 3.0.3
  643. paths:
  644. /pets:
  645. get:
  646. operationId: getPets
  647. ```
  648. openapi-format will format the "getPets" from the original camelcase to kebab-case.
  649. Example after:
  650. ```yaml
  651. openapi: 3.0.3
  652. paths:
  653. /pets:
  654. get:
  655. operationId: get-pets
  656. ```
  657. ### Format casing - model & schema properties
  658. => **properties**: Refers to all the schema properties, that are defined inline in the paths request bodies & responses and the models in the components section of the OpenAPI document.
  659. Formatting casing example:
  660. ```yaml
  661. properties: snake_case
  662. ```
  663. Example before:
  664. ```yaml
  665. openapi: 3.0.3
  666. components:
  667. schemas:
  668. UserModel:
  669. type: object
  670. properties:
  671. id:
  672. type: integer
  673. example: 10
  674. emailAddress:
  675. type: string
  676. example: john@doe.com
  677. firstName:
  678. type: string
  679. example: John
  680. ```
  681. The CLI will format all the properties like: "id", "username", "firstName" from the original camelcase to snake_case.
  682. Example after:
  683. ```yaml
  684. openapi: 3.0.3
  685. components:
  686. schemas:
  687. UserModel:
  688. type: object
  689. properties:
  690. id:
  691. type: integer
  692. example: 10
  693. email_address:
  694. type: string
  695. example: john@doe.com
  696. first_name:
  697. type: string
  698. example: John
  699. ```
  700. ### Format casing - component keys
  701. => **componentsSchemas / componentsExamples / componentsParametersCookie / componentsParametersHeader / componentsParametersQuery / componentsParametersQuery / componentsParametersPath / componentsHeaders / componentsResponses / componentsRequestBodies / componentsSecuritySchemes**: Refers to all the model objects that are defined in the components section of the OpenAPI document.
  702. Formatting casing example:
  703. ```yaml
  704. componentsSchemas: PascalCase
  705. ```
  706. Example before:
  707. ```yaml
  708. openapi: 3.0.3
  709. paths:
  710. /orders:
  711. get:
  712. responses:
  713. content:
  714. application/json:
  715. schema:
  716. $ref: '#/components/schemas/order-model'
  717. components:
  718. schemas:
  719. userModel:
  720. type: object
  721. order-model:
  722. type: object
  723. pet_model:
  724. type: object
  725. ```
  726. openapi-format will format all the component keys like: "userModel", "order-model", "pet_model" to PascalCase, including formatting all the "$ref" used in the OpenAPI document.
  727. Example after:
  728. ```yaml
  729. openapi: 3.0.3
  730. paths:
  731. /orders:
  732. get:
  733. responses:
  734. content:
  735. application/json:
  736. schema:
  737. $ref: '#/components/schemas/OrderModel'
  738. components:
  739. schemas:
  740. UserModel:
  741. type: object
  742. OrderModel:
  743. type: object
  744. PetModel:
  745. type: object
  746. ```
  747. ### Format casing - parameter names
  748. => **componentsParametersCookie / componentsParametersPath / componentsParametersQuery / componentsParametersHeader**: Refers to "name" in the Parameters types: Path, Query or Header, which can be defined inline in the Path or as a reference in the components of the OpenAPI document.
  749. Formatting casing example:
  750. ```yaml
  751. componentsParametersPath: kebab-case
  752. ```
  753. Example before:
  754. ```yaml
  755. openapi: 3.0.3
  756. paths:
  757. '/pet/{petId}':
  758. get:
  759. parameters:
  760. - name: petId
  761. in: path
  762. description: ID of pet to return
  763. - $ref: '#/components/parameters/LimitParam'
  764. components:
  765. parameters:
  766. LimitParam:
  767. name: limitParam
  768. in: query
  769. description: max records to return
  770. ```
  771. The CLI will format the "name" of the parameters: Path, Query or Header like: "petId", "limitParam" to kebab-case in the OpenAPI document.
  772. Example after:
  773. ```yaml
  774. openapi: 3.0.3
  775. paths:
  776. '/pet/{petId}':
  777. get:
  778. parameters:
  779. - name: pet-id
  780. in: path
  781. description: ID of pet to return
  782. - $ref: '#/components/parameters/LimitParam'
  783. components:
  784. parameters:
  785. LimitParam:
  786. name: limit-param
  787. in: query
  788. description: max records to return
  789. ```
  790. ### OpenAPI Generate Options
  791. The OpenAPI formatting tool allows you to generate various elements such as `operationId`, and more using customizable templates. These templates enable dynamic generation of missing or incomplete values in your OpenAPI specification, ensuring consistency and adherence to your conventions.
  792. Options for generating elements:
  793. - `operationIdTemplate`: Generate the `operationId` using placeholders like `<method>`, `<pathPart2>`, etc.
  794. - `overwriteExisting`: Set to `true` or `false` to control whether existing values should be overwritten (default: `false`).
  795. | Key | Options | OpenAPI Reference |
  796. |---------------------|--------------------------------|--------------------------------------------------------------------------------|
  797. | operationIdTemplate | Customizable with placeholders | [operation-object](https://spec.openapis.org/oas/v3.0.3.html#operation-object) |
  798. | overwriteExisting | `true` / `false` | N/A |
  799. See [CLI generate usage](#cli-generate-usage) for an example and the available template options.
  800. ## CLI sort usage
  801. - Format a spec with the default sorting and saves it as a new JSON file
  802. ```shell
  803. $ openapi-format openapi.json -o openapi-formatted.json
  804. ```
  805. - Format a remote spec with the default sorting and saves it as a new JSON file
  806. ```shell
  807. $ openapi-format https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/examples/v3.0/api-with-examples.json -o openapi-formatted.json
  808. ```
  809. - Format an OpenAPI JSON document with the default sorting and saves it as a new YAML file
  810. ```shell
  811. $ openapi-format openapi.json -o openapi.yaml
  812. ```
  813. - Format an OpenAPI document using a configuration file containing all the options that would otherwise be passed via the CLI.
  814. ```shell
  815. $ openapi-format openapi.yaml --configFile openapi-format-options.json
  816. ```
  817. The formatting will happen based on all the options set in the `openapi-format-options.json` file. All the
  818. available [OpenAPI format options](https://github.com/thim81/openapi-format#openapi-format-options) can be used in the config file.
  819. - Format an OpenAPI document with the default sorting and output it as JSON to STDOUT
  820. ```shell
  821. $ openapi-format openapi.json --json
  822. ```
  823. - Format an OpenAPI document with the default sorting and output it as YAML to STDOUT
  824. ```shell
  825. $ openapi-format openapi.json --yaml
  826. ```
  827. - Format an OpenAPI JSON document with the default sorting and save it as YAML
  828. ```shell
  829. $ openapi-format openapi.json -o openapi.yaml
  830. ```
  831. - Format an OpenAPI document but skip the sorting and save it as a new JSON file
  832. ```shell
  833. $ openapi-format openapi.json -o openapi-formatted.json --no-sort
  834. ```
  835. This should keep the OpenAPI fields in the same order. This can be needed, when you only want to do a filtering or
  836. rename action.
  837. - Convert the OpenAPI 3.0 document to OpenAPI 3.1 but skip the sorting and save it as a new YAML file
  838. ```shell
  839. $ openapi-format openapi.yaml -o openapi-3.1.yaml --no-sort --convertTo "3.1"
  840. ```
  841. This will convert the OpenAPI 3.0 document into version 3.1 of OpenAPI, without any ordering or filtering.
  842. During the conversion, openapi-format will transform all OpenAPI 3.0 properties into the OpenAPI 3.1 properties, as described in the [migration guide from
  843. Phil Sturgeon](https://www.openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0).
  844. - Format an OpenAPI document, including sorting all elements in the components section
  845. ```shell
  846. $ openapi-format openapi.json -o openapi-formatted.json --sortComponentsFile ./test/json-sort-components/customSortComponents.json
  847. ```
  848. This will sort all elements in the components (components/schemas, components/parameters, components/headers,
  849. components/requestBodies, components/responses, ...) section alphabetically. The file specified by `--sortComponentsFile` should contain an array of component types to sort.
  850. Example of a customSortComponents.json file:
  851. ```json
  852. ["schemas", "parameters", "headers", "requestBodies", "responses", "securitySchemes"]
  853. ```
  854. **before**
  855. ```yaml
  856. components:
  857. schemas:
  858. Order:
  859. type: object
  860. # properties...
  861. Customer:
  862. type: object
  863. # properties...
  864. Address:
  865. type: object
  866. # properties...
  867. securitySchemes:
  868. petstore_auth:
  869. type: oauth2
  870. # configuration...
  871. api_key:
  872. type: apiKey
  873. # configuration...
  874. ```
  875. **after**
  876. ```yaml
  877. components:
  878. schemas:
  879. Address:
  880. type: object
  881. # properties...
  882. Customer:
  883. type: object
  884. # properties...
  885. Order:
  886. type: object
  887. # properties...
  888. securitySchemes:
  889. api_key:
  890. type: apiKey
  891. # configuration...
  892. petstore_auth:
  893. type: oauth2
  894. # configuration...
  895. ```
  896. - Format an OpenAPI document, including sorting properties within schema components alphabetically
  897. ```shell
  898. $ openapi-format openapi.json -o openapi-formatted.json --sortComponentsProps
  899. ```
  900. This will sort all properties within schema components alphabetically. For example:
  901. **before**
  902. ```yaml
  903. components:
  904. schemas:
  905. UserDto:
  906. type: object
  907. properties:
  908. lastName:
  909. type: string
  910. firstName:
  911. type: string
  912. ```
  913. **after**
  914. ```yaml
  915. components:
  916. schemas:
  917. UserDto:
  918. type: object
  919. properties:
  920. firstName:
  921. type: string
  922. lastName:
  923. type: string
  924. ```
  925. ## CLI filter usage
  926. - Format an OpenAPI document by filtering fields, default sorting and saves it as a new file
  927. When you want to strip certain methods ,tags, operationIds, operations, flags you can pass a `filterFile` which contains the
  928. specific values for the methods ,tags, operationIds, operations, flags.
  929. This can be useful to combine with the sorting, to end up with an order and filtered OpenAPI document.
  930. example:
  931. ```shell
  932. $ openapi-format openapi.json -o openapi-formatted.json --filterFile customFilter.yaml
  933. ```
  934. where the `customFilter.yaml` would contain a combination of all the elements you want to filter out.
  935. ```yaml
  936. flags:
  937. - x-visibility
  938. flagValues: [ ]
  939. tags: [ ]
  940. operationIds:
  941. - addPet
  942. - findPetsByStatus
  943. ```
  944. ## CLI OpenAPI Overlay Usage
  945. The OpenAPI Overlay functionality allows users to apply actions such as updates and removals to an OpenAPI Specification (OAS). This feature is useful for dynamically modifying OAS documents during development, testing, or publishing workflows.
  946. ### What is an OpenAPI Overlay?
  947. An [OpenAPI Overlay](https://spec.openapis.org/overlay/v1.1.0.html) is a specification that defines a structured set of actions to be applied to an existing OpenAPI document. It enables:
  948. - Updating existing fields, such as descriptions, parameters, or endpoints.
  949. - Adding new fields or objects to the OpenAPI document.
  950. - Removing fields or objects that are no longer relevant.
  951. - Copying values from one location in the source document to another location.
  952. An overlay document follows the structure below:
  953. ```yaml
  954. overlay: 1.1.0
  955. info:
  956. title: Example Overlay
  957. description: Overlay to add docs metadata and copy values
  958. version: 1.0.0
  959. x-overlay-owner: docs-team
  960. actions:
  961. - target: "$" # JSONPath definition of the targeted element of the document
  962. update: # The action to be applied: update, remove, or copy
  963. info:
  964. description: "Updated description for the OpenAPI specification."
  965. - target: "$.paths['/example']"
  966. update:
  967. get:
  968. description: "Updated GET description for /example endpoint."
  969. - target: "$.paths['/example'].get.parameters"
  970. remove: true # Example of removing an element
  971. - target: "$.info.title"
  972. copy: "$.info.version"
  973. ```
  974. For more information about the OpenAPI Overlay options, see [OpenAPI Overlay Specification 1.1.0](https://spec.openapis.org/overlay/v1.1.0.html).
  975. Use the `--overlayFile` option to specify the overlay file and apply it to your OpenAPI document.
  976. example:
  977. ```shell
  978. $ openapi-format openapi.yaml --overlayFile overlay.yaml -o openapi-updated.yaml
  979. ```
  980. You can also let the overlay declare the base OpenAPI document using the top-level `extends` property. When `extends` is present, the input file argument becomes optional:
  981. ```yaml
  982. overlay: 1.1.0
  983. info:
  984. title: Overlay for Tic Tac Toe
  985. version: 1.0.0
  986. description: Overlay for docs-only adjustments
  987. extends: 'https://raw.githubusercontent.com/OAI/learn.openapis.org/refs/heads/main/examples/v3.1/tictactoe.yaml'
  988. # actions: [...] # optional
  989. ```
  990. CLI usage with `extends` (no input file argument):
  991. ```shell
  992. $ openapi-format --overlayFile overlay.yaml -o openapi-updated.yaml
  993. ```
  994. Notes:
  995. - `extends` supports both local paths and remote `http(s)` URLs.
  996. - Local relative paths are resolved relative to the overlay file’s location.
  997. - `.overlay.yaml` is the recommended file naming convention for overlays.
  998. - Overlay actions are processed in strict mode and validated before applying:
  999. - `target` must be valid JSONPath.
  1000. - At least one of `update`, `remove`, or `copy` must be present.
  1001. - `copy` must be a JSONPath string and resolve to exactly one source node.
  1002. - Legacy overlays using `copy: true` with `from` remain supported for compatibility, but new overlays should use `copy: "$.source.path"`.
  1003. ## CLI generate usage
  1004. - Generate OpenAPI elements and saves it as a new file
  1005. The OpenAPI formatting tool allows you to generate OpenAPI elements, such as `operationId`, `summary`, and more, based on configurable templates. The generated elements will be saved to the output OpenAPI file.
  1006. You can also combine generation with filtering and sorting to customize the output.
  1007. example:
  1008. ```shell
  1009. $ openapi-format openapi.json -o openapi-formatted.json --generateFile customGenerate.yaml
  1010. ```
  1011. where the `customGenerate.yaml` would contain a combination of all the elements you to generate.
  1012. ```yaml
  1013. operationIdTemplate: "<method>_<pathPart2>"
  1014. overwriteExisting: false
  1015. ```
  1016. **Template Options:**
  1017. In the customGenerate.yaml, you can define templates for various OpenAPI properties using dynamic placeholders. These placeholders will be replaced by actual values from the OpenAPI operations. Below is a list of available placeholders and what they represent:
  1018. - `<operationId>` : The operationId of the OpenAPI operation. Example: leadsAll
  1019. - `<method>` : The HTTP method of the OpenAPI operation. Example: GET
  1020. - `<path>` : The path of the OpenAPI operation. Example: /crm/leads
  1021. - `<pathRef>` : The path reference of the OpenAPI operation. Example: GET::/crm/leads
  1022. - `<tag>` : The first tag name of the OpenAPI operation. Example: Leads
  1023. - `<tag1>` : The first tag name of the OpenAPI operation. Example: Leads
  1024. - `<tag2>` : The second tag name of the OpenAPI operation, if more than one tag is defined. Example: CRM
  1025. - `<tagn>` : The nth tag name of the OpenAPI operation if more than one tag is defined.
  1026. - `<pathPart1>` : The first part of the path of the OpenAPI operation. Example: crm
  1027. - `<pathPart2>` : The second part of the path of the OpenAPI operation. Example: leads
  1028. - `<pathPartn>` : The nth part of the path of the OpenAPI operation.
  1029. You can also include static text in the templates, which will be merged with the dynamic placeholders. For example:
  1030. ```yaml
  1031. operationIdTemplate: "Prefix_<method>_<pathPart2>_Handler"
  1032. ```
  1033. **Configuration Options:**
  1034. - `operationIdTemplate`: Template for generating `operationId`. Use dynamic placeholders like <method> and <pathPart2>.
  1035. - `overwriteExisting`: Set to `true` or `false` to control whether existing values should be overwritten. Default: `false`.
  1036. ## CLI casing usage
  1037. - Generate OpenAPI elements and saves it as a new file
  1038. The OpenAPI formatting tool allows you to enforce consistent casing styles across various OpenAPI elements, such as `operationId`, `summary`, `parameters`, and more. The specified casing preferences will be applied to the relevant elements and saved to the output OpenAPI file.
  1039. example:
  1040. ```shell
  1041. $ openapi-format openapi.json -o openapi-formatted.json --casingFile customCasing.yaml
  1042. ```
  1043. where the `customCasing.yaml` would contain a casing preferences for the specified of the elements.
  1044. In this example, the customCasing.yaml file would contain the desired casing preferences for specific OpenAPI elements.
  1045. ```yaml
  1046. operationId: snake_case
  1047. operationIdKeepChars:
  1048. - .
  1049. properties: camelCase
  1050. propertiesKeepChars:
  1051. - .
  1052. parametersQuery: kebab-case
  1053. parametersHeader: kebab-case
  1054. parametersPath: snake_case
  1055. parametersQueryKeepChars:
  1056. - .
  1057. componentsExamples: PascalCase
  1058. componentsSchemas: camelCase
  1059. componentsHeaders: kebab-case
  1060. componentsResponses: snake_case
  1061. componentsRequestBodies: snake_case
  1062. componentsSecuritySchemes: PascalCase
  1063. componentsParametersQuery: snake_case
  1064. componentsParametersHeader: kebab-case
  1065. componentsParametersPath: camelCase
  1066. componentsParametersQueryKeepChars:
  1067. - .
  1068. ```
  1069. **Casing Options:**
  1070. In the customCasing.yaml, you can define the casing style for various OpenAPI properties, allowing you to customize the appearance of your document consistently.
  1071. For every casing option, you can optionally define a matching `*KeepChars` option. This follows the same per-element configuration model as the casing rules themselves: different OpenAPI elements can have different casing conventions, and they may also need to preserve different separator characters. For example, query parameters may preserve dots for nested parameter names, while component schemas may preserve dots for versioned names.
  1072. - `operationId`: Defines the casing for operation IDs. Example: `snake_case`, `PascalCase`, or `camelCase`.
  1073. - `operationIdKeepChars`: Keeps selected characters while casing `operationId`. Example: `.` for dotted identifiers.
  1074. - `properties`: Sets the casing for properties within schemas. Example: `camelCase`.
  1075. - `propertiesKeepChars`: Keeps selected characters while casing schema properties. Example: `.` for dotted property names.
  1076. - `parametersQuery`, `parametersHeader`, `parametersPath`, `parametersCookie`: Define different casing styles for parameters based on their location. Example: `camelCase` for query parameters, `kebab-case` for headers, or `snake_case` for path parameters.
  1077. - `parametersQueryKeepChars`, `parametersHeaderKeepChars`, `parametersPathKeepChars`, `parametersCookieKeepChars`: Keep selected characters while casing inline parameter names.
  1078. - `componentsSchemas`, `componentsExamples`, `componentsHeaders`, `componentsResponses`, `componentsRequestBodies`, `componentsSecuritySchemes`: Define casing styles for component keys.
  1079. - `componentsSchemasKeepChars`, `componentsExamplesKeepChars`, `componentsHeadersKeepChars`, `componentsResponsesKeepChars`, `componentsRequestBodiesKeepChars`, `componentsSecuritySchemesKeepChars`: Keep selected characters while casing component keys.
  1080. - `componentsParametersQuery`, `componentsParametersHeader`, `componentsParametersPath`, `componentsParametersCookie`: Define casing styles for reusable parameters in `components.parameters`, based on their `in` value.
  1081. - `componentsParametersQueryKeepChars`, `componentsParametersHeaderKeepChars`, `componentsParametersPathKeepChars`, `componentsParametersCookieKeepChars`: Keep selected characters while casing reusable parameter keys in `components.parameters`.
  1082. See [OpenAPI formatting configuration options](#openapi-formatting-configuration-options) for the full list of casing options
  1083. Note: When custom keep characters are configured, they are merged with the default characters that `openapi-format` already preserves: `$` and `@`. To disable the default preserved characters for direct `changeCase` usage, pass an empty array as the custom keep characters.
  1084. ## CLI Bundle & Split usage
  1085. - **Bundling**: Create a self-contained OpenAPI file that can be used for documentation generation or API validation tools that don't support external references.
  1086. - **Splitting**: Generate a modular OpenAPI structure during development or testing, making it easier to manage changes to individual paths or components without altering the entire document.
  1087. ### Splitting the OpenAPI Document
  1088. The `--split` option splits the OpenAPI document into a modular multi-file structure. This structure makes it easier to manage larger specifications by separating paths, components (schemas, paramaters, ...) into individual files.
  1089. Example: Splitting the Document
  1090. ```shell
  1091. $ openapi-format openapi.json -o ./openapi-split/openapi.yaml --split
  1092. ```
  1093. This command will take the openapi.json and split it into multiple files, stored under the ./openapi-split/ directory.
  1094. The resulting structure might look like this:
  1095. ```bash
  1096. ./openapi-split/
  1097. ├── openapi.yaml
  1098. ├── paths/
  1099. │ ├── /pets.yaml
  1100. │ └── /pets/{petId}.yaml
  1101. ├── components/
  1102. ├── schemas/
  1103. │ ├── Pet.yaml
  1104. │ └── Error.yaml
  1105. ├── parameters/
  1106. │ └── petId.yaml
  1107. ```
  1108. The main openapi.yaml file will contain references to these newly created files using $ref, making the structure modular and easier to navigate.
  1109. ### Bundling the OpenAPI Document
  1110. The `--no-bundle` option allows you to control whether local and remote $ref references are bundled into the final document.
  1111. By default, all $ref references are dereferenced, resulting in a single, self-contained OpenAPI file. However, in some cases, you might prefer to keep the $ref references intact, especially if you're working with external references or want to maintain a modular structure.
  1112. Example: Default Bundling
  1113. ```shell
  1114. $ openapi-format input.json -o bundled-openapi.json
  1115. ```
  1116. This example produces a fully dereferenced dereferenced-openapi.json, where all local and remote $ref references are resolved into the file.
  1117. This is the default behaviour.
  1118. Example: No Bundling
  1119. ```shell
  1120. $ openapi-format openapi.json -o openapi.json --no-bundle
  1121. ```
  1122. In this case, the resulting bundled-openapi.json will preserve all $ref references as they are in the original document.
  1123. ## CLI rename usage
  1124. - Format an OpenAPI document by changing the title and saves it as a new JSON file
  1125. During CI/CD pipelines, you might want to create different results of the OpenAPI document. Having the option to rename
  1126. them might make it easier to work with the results, so that is why we provide this command option.
  1127. ```shell
  1128. $ openapi-format openapi.json -o openapi.json --rename "OpenAPI Petstore - OpenAPI 3.0"
  1129. ```
  1130. which results in
  1131. **before**
  1132. ```json
  1133. {
  1134. "openapi": "3.0.2",
  1135. "info": {
  1136. "title": "Petstore - OpenAPI 3.0",
  1137. ```
  1138. **after**
  1139. ```json
  1140. {
  1141. "openapi": "3.0.2",
  1142. "info": {
  1143. "title": "OpenAPI Petstore - OpenAPI 3.0",
  1144. ```
  1145. ## CLI convertTo usage
  1146. - Format & convert the OpenAPI document to OpenAPI version 3.1 or 3.2
  1147. openapi-format can help you to upgrade your current OpenAPI 3.0.x document to OpenAPI 3.1 or 3.2.
  1148. ```shell
  1149. $ openapi-format openapi.json -o openapi-3.1.json --convertTo "3.1"
  1150. $ openapi-format openapi.json -o openapi-3.2.json --convertTo "3.2"
  1151. ```
  1152. Using `3.1` results in all the changes described in the [migration guide from Phil Sturgeon](https://www.openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0), while the `3.2` target aligns with the new capabilities highlighted in [OpenAPI 3.2 is here](https://quobix.com/articles/openapi-3.2/).
  1153. **before**
  1154. ```json
  1155. {
  1156. "openapi": "3.0.2",
  1157. "info": {
  1158. "title": "Petstore - OpenAPI",
  1159. ```
  1160. **after**
  1161. ```json
  1162. {
  1163. "openapi": "3.1.0",
  1164. "info": {
  1165. "title": "OpenAPI Petstore - OpenAPI",
  1166. ```
  1167. When converting to 3.2 the `openapi` field will be set to `3.2.0`, preparing the document for features like hierarchical tags, the `QUERY` HTTP method, and reusable media types introduced in the 3.2 release.
  1168. ## CLI configuration usage
  1169. The openapi-format CLI supports bundling all options in a single configuration file. This can simplify management, especially for CI/CD pipelines where configurations are stored in version control systems.
  1170. ### Using the --configFile option
  1171. You can pass a configuration file containing all the options that would otherwise be passed via the CLI. This helps in centralizing the configuration for your OpenAPI formatting operations.
  1172. Example:
  1173. ```shell
  1174. $ openapi-format openapi.json --configFile openapi-format-options.json
  1175. ```
  1176. The formatting will happen based on all the options set in the `openapi-format-options.json` file. All the
  1177. available [OpenAPI format options](https://github.com/thim81/openapi-format#openapi-format-options) can be used in the config file.
  1178. The openapi-format-options.json file might look like this:
  1179. ```json
  1180. {
  1181. "sort": true,
  1182. "casingSet": {
  1183. "operationId": "camelCase",
  1184. "properties": "snake_case"
  1185. },
  1186. "filterSet": {
  1187. "tags": ["internal", "beta"]
  1188. },
  1189. "generateSet": {
  1190. "operationIdTemplate": "<method>_<pathPart2>_Handler"
  1191. }
  1192. }
  1193. ```
  1194. Alternatively, you can reference external files for each setting using the corresponding File properties.
  1195. ```json
  1196. {
  1197. "sortFile": "customSort.json",
  1198. "casingFile": "casing-rules.json",
  1199. "filterFile": "filter-rules.json",
  1200. "generateFile": "generate-rules.json"
  1201. }
  1202. ```
  1203. In this case, the settings will be loaded from the external files, and they override any inline configurations.
  1204. **Define sort, filter, casing, generate options**
  1205. You can either pass the settings inline or reference an external file using the appropriate File property:
  1206. - **sortSet** / **sortFile**: Sort the fields in the OpenAPI document based on the order defined in the sort settings.
  1207. - Inline: Pass the sort order directly using sortSet in the config file.
  1208. - File: Use sortFile to specify the path to a local or remote JSON/YAML file containing custom sorting rules.
  1209. - **casingSet** / **casingFile**: Define the casing convention for operationId, parameters, properties, etc.
  1210. - Inline:
  1211. ```json
  1212. "casingSet": {
  1213. "operationId": "camelCase",
  1214. "properties": "PascalCase"
  1215. }
  1216. ```
  1217. - File: Use casingFile to specify the path to a local or remote JSON/YAML file containing casing rules.
  1218. - **filterSet** / **filterFile**: Filter out specific tags, paths, or components from the OpenAPI document.
  1219. - Inline:
  1220. ```json
  1221. "filterSet": {
  1222. "tags": ["internal", "beta"]
  1223. }
  1224. ```
  1225. - File: Use filterFile to specify the path to a local or remote JSON/YAML file containing filter rules.
  1226. - **generateSet** / **generateFile**: Automatically generate operationId, summary, and other elements based on predefined templates.
  1227. - Inline:
  1228. ```json
  1229. "generateSet": {
  1230. "operationIdTemplate": "<method>_<pathPart2>_Handler"
  1231. }
  1232. ```
  1233. - File: Use generateFile to specify the path to a local or remote JSON/YAML file containing generate rules.
  1234. ### Using .openapiformatrc
  1235. In addition to specifying a configuration file using `--configFile`, openapi-format also supports automatically loading a configuration file named `.openapiformatrc` from the current directory. If this file is present, it will be used as the configuration source, and individual options passed via the CLI will override the settings from this file.
  1236. Example of a .openapiformatrc file:
  1237. ```json
  1238. {
  1239. "output": "openapi-final.yaml",
  1240. "sort": true,
  1241. "filterSet": {
  1242. "tags": ["internal", "beta"]
  1243. }
  1244. }
  1245. ```
  1246. ### JSON Schema for the configuration file
  1247. An official JSON Schema is shipped with openapi-format so editors can validate the configuration and offer autocompletion. The schema is available in the repository at [`schemas/openapi-format.schema.json`](https://github.com/thim81/openapi-format/blob/main/schemas/openapi-format.schema.json) and is also published with the npm package at `node_modules/openapi-format/schemas/openapi-format.schema.json`.
  1248. Reference it from your config via the `$schema` key:
  1249. ```json
  1250. {
  1251. "$schema": "https://openapi-format.com/schema/v1.json",
  1252. "sort": true,
  1253. "casingSet": {
  1254. "operationId": "PascalCase",
  1255. "properties": "camelCase"
  1256. }
  1257. }
  1258. ```
  1259. Extra keys are allowed at every level so user-defined extensions (e.g. `sortSet.paths.order`) keep working.
  1260. ## Programmatic usage
  1261. The CLI is the primary interface, but all formatting utilities are exposed as module functions as well:
  1262. ```js
  1263. const {
  1264. openapiSort,
  1265. getDefaultSortSet,
  1266. getDefaultSortComponentsSet
  1267. } = require('openapi-format');
  1268. const document = /* your OpenAPI document */;
  1269. const sorted = await openapiSort(document, {
  1270. sortSet: await getDefaultSortSet(),
  1271. sortComponentsSet: await getDefaultSortComponentsSet()
  1272. });
  1273. ```
  1274. Both `sortSet` and `sortComponentsSet` are optional when you call `openapiSort`. When omitted, openapi-format automatically applies the built-in defaults (the same ones the CLI uses). The helper functions `getDefaultSortSet` and `getDefaultSortComponentsSet` are provided in case you want to start from the defaults and tweak them before invoking `openapiSort` in your own scripts.
  1275. ### Sorting with minimal setup
  1276. ```js
  1277. const {
  1278. parseFile,
  1279. stringify,
  1280. writeFile,
  1281. openapiSort
  1282. } = require('openapi-format');
  1283. const input = await parseFile('spec.json'); // local path or remote URL
  1284. const {data} = await openapiSort(input, {sort: true});
  1285. const output = await stringify(data, {format: 'json'});
  1286. await writeFile('spec.sorted.json', output, {format: 'json'});
  1287. ```
  1288. ### Sorting with custom tweaks
  1289. ```js
  1290. const {
  1291. parseFile,
  1292. stringify,
  1293. writeFile,
  1294. openapiSort,
  1295. getDefaultSortSet
  1296. } = require('openapi-format');
  1297. const document = await parseFile('spec.json');
  1298. const sortSet = await getDefaultSortSet();
  1299. sortSet.get = ['summary', 'description', 'responses']; // override GET priority
  1300. const {data} = await openapiSort(document, {
  1301. sort: true,
  1302. sortSet,
  1303. sortComponentsSet: ['schemas', 'responses']
  1304. });
  1305. const output = await stringify(data, {format: 'json'});
  1306. await writeFile('spec.sorted.json', output, {format: 'json'});
  1307. ```
  1308. ### Mixing in other utilities
  1309. ```js
  1310. const {openapiFilter, openapiGenerate} = require('openapi-format');
  1311. let draft = await parseFile('spec.json');
  1312. draft = (await openapiFilter(draft, {
  1313. filterSet: {tags: ['public']}
  1314. })).data;
  1315. draft = (await openapiGenerate(draft, {
  1316. generateSet: {
  1317. operationIdTemplate: '<method>_<pathPart1>_<pathPart2>'
  1318. }
  1319. })).data;
  1320. ```
  1321. ### Using the file helpers for YAML/JSON OpenAPI documents
  1322. The module also exports the same helpers the CLI relies on for smart parsing/writing (large-number handling, YAML comments, remote loading, etc.) of OpenAPI documents:
  1323. ```js
  1324. const {
  1325. parseFile,
  1326. stringify,
  1327. writeFile,
  1328. openapiSort
  1329. } = require('openapi-format');
  1330. const input = await parseFile('openapi.yaml'); // local path or remote URL
  1331. const {data} = await openapiSort(input, {sort: true});
  1332. const output = await stringify(data, {format: 'yaml', lineWidth: -1});
  1333. await writeFile('openapi.sorted.yaml', output, {format: 'yaml'});
  1334. ```
  1335. ## AsyncAPI documents
  1336. For handling AsyncAPI documents, we have created a separate
  1337. package [asyncapi-format](https://github.com/thim81/asyncapi-format) to allow customisation specific for AsyncAPI
  1338. use-cases.
  1339. ## YAML handling
  1340. As of `v1.31.0`, `openapi-format` uses `yaml` by [eemeli](https://github.com/eemeli/yaml) instead of `@stoplight/yaml`, thanks to the contribution of [@guilhas07](https://github.com/guilhas07).
  1341. This improves YAML comment preservation and fixes previous formatting issues where:
  1342. - valid YAML strings were unnecessarily quoted
  1343. - double-quoted strings were converted to single quotes
  1344. ## Credits
  1345. This package is inspired by
  1346. the [@microsoft.azure/format-spec](https://www.npmjs.com/package/@microsoft.azure/format-spec) from [@fearthecowboy](https://github.com/fearthecowboy). The
  1347. original code was not available on GitHub, with the last update since 2018, so to improve support and extend it; we
  1348. tried to reproduce the original functionality.
  1349. The filter capabilities from `openapi-format` are inspired by the work from [@MikeRalphson](https://github.com/mikeralphson) on
  1350. the [openapi-filter](https://github.com/Mermade/openapi-filter) package.
  1351. The casing options available in `openapi-format` are powered by the excellent [case-anything](https://github.com/mesqueeb/case-anything) nano package from Luca Ban ([@mesqueeb](https://github.com/mesqueeb)).
  1352. <a href="https://www.jetbrains.com/" target="_blank">
  1353. <img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jetbrains.png" alt="JetBrains logo." width="200px">
  1354. </a>
  1355. Special thanks to [JetBrains](https://www.jetbrains.com/) for their continuous sponsorship of this project over the last 3 years, and for their support to open-source software (OSS) initiatives.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.