{"id":15286058,"url":"https://github.com/swaggerexpert/openapi-path-templating","last_synced_at":"2025-04-13T03:09:43.481Z","repository":{"id":211898063,"uuid":"730126319","full_name":"swaggerexpert/openapi-path-templating","owner":"swaggerexpert","description":"OpenAPI Path Templating parser, validator and resolver.","archived":false,"fork":false,"pushed_at":"2025-03-24T20:09:24.000Z","size":674,"stargazers_count":2,"open_issues_count":5,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-13T03:09:31.514Z","etag":null,"topics":["matcher","openapi2","openapi3","openapi31","parser","path","resolver","swagger","template-expression","templating","validator"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/swaggerexpert.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":"GOVERNANCE.md","roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["char0n"],"tidelift":"npm/openapi-path-templating","patreon":"char0n","ko_fi":"char0n","liberapay":"char0n","issuehunt":"char0n"}},"created_at":"2023-12-11T09:07:36.000Z","updated_at":"2025-03-24T20:09:28.000Z","dependencies_parsed_at":"2024-02-12T20:25:28.827Z","dependency_job_id":"790f3e7f-8fc6-43bf-b9bb-de9cf7384111","html_url":"https://github.com/swaggerexpert/openapi-path-templating","commit_stats":{"total_commits":144,"total_committers":3,"mean_commits":48.0,"dds":"0.33333333333333337","last_synced_commit":"ffbcd2b30e640202f58918feb7a90f8174bf06a8"},"previous_names":["char0n/openapi-path-templating","swaggerexpert/openapi-path-templating"],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swaggerexpert%2Fopenapi-path-templating","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swaggerexpert%2Fopenapi-path-templating/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swaggerexpert%2Fopenapi-path-templating/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swaggerexpert%2Fopenapi-path-templating/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/swaggerexpert","download_url":"https://codeload.github.com/swaggerexpert/openapi-path-templating/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248657917,"owners_count":21140846,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["matcher","openapi2","openapi3","openapi31","parser","path","resolver","swagger","template-expression","templating","validator"],"created_at":"2024-09-30T15:10:19.453Z","updated_at":"2025-04-13T03:09:43.475Z","avatar_url":"https://github.com/swaggerexpert.png","language":"JavaScript","readme":"# openapi-path-templating\n\n[![npmversion](https://badge.fury.io/js/openapi-path-templating.svg)](https://www.npmjs.com/package/openapi-path-templating)\n[![npm](https://img.shields.io/npm/dm/openapi-path-templating.svg)](https://www.npmjs.com/package/openapi-path-templating)\n[![Test workflow](https://github.com/swaggerexpert/openapi-path-templating/actions/workflows/test.yml/badge.svg)](https://github.com/swaggerexpert/openapi-path-templating/actions)\n[![Dependabot enabled](https://img.shields.io/badge/Dependabot-enabled-blue.svg)](https://dependabot.com/)\n[![try on RunKit](https://img.shields.io/badge/try%20on-RunKit-brightgreen.svg?style=flat)](https://npm.runkit.com/openapi-path-templating)\n[![Tidelift](https://tidelift.com/badges/package/npm/openapi-path-templating)](https://tidelift.com/subscription/pkg/npm-openapi-path-templating?utm_source=npm-openapi-path-templating\u0026utm_medium=referral\u0026utm_campaign=readme)\n\n[OpenAPI Path Templating](https://spec.openapis.org/oas/v3.1.1.html#path-templating) refers to the usage of template expressions, delimited by curly braces (`{}`), to mark a section of a URL path as replaceable using path parameters.\nEach template expression in the path MUST correspond to a path parameter that is included in the [Path Item](https://spec.openapis.org/oas/v3.1.1.html#path-item-object) itself and/or in each of the Path Item's [Operations](https://spec.openapis.org/oas/v3.1.1.html#operation-object).\nAn exception is if the path item is empty, for example due to ACL constraints, matching path parameters are not required.\n\n`openapi-path-templating` is a **parser**, **validator**, **resolver** and **matcher** for OpenAPI Path Templating,\nwhich played a [foundational role](https://github.com/OAI/OpenAPI-Specification/pull/4244) in defining the official ANBF grammar for OpenAPI Path Templating.\n\nIt supports Path Templating defined in following OpenAPI specification versions:\n\n- [OpenAPI 2.0](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#pathTemplating)\n- [OpenAPI 3.0.0](https://spec.openapis.org/oas/v3.0.0.html#path-templating)\n- [OpenAPI 3.0.1](https://spec.openapis.org/oas/v3.0.1.html#path-templating)\n- [OpenAPI 3.0.2](https://spec.openapis.org/oas/v3.0.2.html#path-templating)\n- [OpenAPI 3.0.3](https://spec.openapis.org/oas/v3.0.3.html#path-templating)\n- [OpenAPI 3.0.4](https://spec.openapis.org/oas/v3.0.4.html#path-templating)\n- [OpenAPI 3.1.0](https://spec.openapis.org/oas/v3.1.0.html#path-templating)\n- [OpenAPI 3.1.1](https://spec.openapis.org/oas/v3.1.1.html#path-templating)\n\n\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003ctd align=\"right\" valign=\"middle\"\u003e\n        \u003cimg src=\"https://cdn2.hubspot.net/hubfs/4008838/website/logos/logos_for_download/Tidelift_primary-shorthand-logo.png\" alt=\"Tidelift\" width=\"60\" /\u003e\n      \u003c/td\u003e\n      \u003ctd valign=\"middle\"\u003e\n        \u003ca href=\"https://tidelift.com/subscription/pkg/npm-openapi-path-templating?utm_source=npm-openapi-path-templating\u0026utm_medium=referral\u0026utm_campaign=readme\"\u003e\n            Get professionally supported openapi-path-templating with Tidelift Subscription.\n        \u003c/a\u003e\n      \u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\n## Table of Contents\n\n- [Getting started](#getting-started)\n  - [Installation](#installation)\n  - [Usage](#usage)\n    - [Parsing](#parsing)\n    - [Validation](#validation)\n    - [Resolution](#resolution)\n    - [Normalization](#normalization)\n    - [Matching](#matching)\n    - [Grammar](#grammar)\n- [More about OpenAPI Path Templating](#more-about-openapi-path-templating)\n- [License](#license)\n\n\n## Getting started\n\n### Installation\n\nYou can install `openapi-path-templating` using `npm`:\n\n```sh\n $ npm install openapi-path-templating\n```\n\n### Usage\n\n`openapi-path-templating` currently supports **parsing**, **validation**, **resolution** and **matching**.\nBoth parser and validator are based on a superset of [ABNF](https://www.rfc-editor.org/rfc/rfc5234) ([SABNF](https://github.com/ldthomas/apg-js2/blob/master/SABNF.md))\nand use [apg-lite](https://github.com/ldthomas/apg-lite) parser generator.\n\n#### Parsing\n\nParsing a Path Templating is as simple as importing the **parse** function\nand calling it.\n\n```js\nimport { parse } from 'openapi-path-templating';\n\nconst parseResult = parse('/pets/{petId}');\nparseResult.result.success; // =\u003e true\n```\n\n**parseResult** variable has the following shape:\n\n```\n{\n  result: {\n    success: true,\n    state: 101,\n    stateName: 'MATCH',\n    length: 13,\n    matched: 13,\n    maxMatched: 13,\n    maxTreeDepth: 20,\n    nodeHits: 232\n  },\n  ast: fnast {\n    callbacks: [\n      'path-template': [Function: pathTemplate],\n      slash: [Function: slash],\n      'path-literal': [Function: pathLiteral],\n      'template-expression': [Function: templateExpression],\n      'template-expression-param-name': [Function: templateExpressionParamName]\n    ],\n    init: [Function (anonymous)],\n    ruleDefined: [Function (anonymous)],\n    udtDefined: [Function (anonymous)],\n    down: [Function (anonymous)],\n    up: [Function (anonymous)],\n    translate: [Function (anonymous)],\n    setLength: [Function (anonymous)],\n    getLength: [Function (anonymous)],\n    toXml: [Function (anonymous)]\n  }\n}\n```\n\n###### Interpreting AST as list of entries\n\n```js\nimport { parse } from 'openapi-path-templating';\n\nconst parseResult = parse('/pets/{petId}');\nconst parts = [];\n\nparseResult.ast.translate(parts);\n```\n\nAfter running the above code, **parts** variable has the following shape:\n\n```js\n[\n  [ 'path-template', '/pets/{petId}' ],\n  [ 'slash', '/' ],\n  [ 'path-literal', 'pets' ],\n  [ 'slash', '/' ],\n  [ 'template-expression', '{petId}' ],\n  [ 'template-expression-param-name', 'petId' ]\n]\n```\n\n###### Interpreting AST as XML\n\n```js\nimport { parse } from 'openapi-path-templating';\n\nconst parseResult = parse('/pets/{petId}');\nconst xml = parseResult.ast.toXml();\n```\n\nAfter running the above code, **xml** variable has the following content:\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003croot nodes=\"6\" characters=\"13\"\u003e\n  \u003c!-- input string --\u003e\n  /pets/{petId}\n  \u003cnode name=\"path-template\" index=\"0\" length=\"13\"\u003e\n    /pets/{petId}\n    \u003cnode name=\"slash\" index=\"0\" length=\"1\"\u003e\n      /\n    \u003c/node\u003e\u003c!-- name=\"slash\" --\u003e\n    \u003cnode name=\"path-literal\" index=\"1\" length=\"4\"\u003e\n      pets\n    \u003c/node\u003e\u003c!-- name=\"path-literal\" --\u003e\n    \u003cnode name=\"slash\" index=\"5\" length=\"1\"\u003e\n      /\n    \u003c/node\u003e\u003c!-- name=\"slash\" --\u003e\n    \u003cnode name=\"template-expression\" index=\"6\" length=\"7\"\u003e\n      {petId}\n      \u003cnode name=\"template-expression-param-name\" index=\"7\" length=\"5\"\u003e\n        petId\n      \u003c/node\u003e\u003c!-- name=\"template-expression-param-name\" --\u003e\n    \u003c/node\u003e\u003c!-- name=\"template-expression\" --\u003e\n  \u003c/node\u003e\u003c!-- name=\"path-template\" --\u003e\n\u003c/root\u003e\n```\n\n\u003e NOTE: AST can also be traversed in classical way using [depth first traversal](https://www.tutorialspoint.com/data_structures_algorithms/depth_first_traversal.htm). For more information about this option please refer to [apg-js](https://github.com/ldthomas/apg-js) and [apg-js-examples](https://github.com/ldthomas/apg-js-examples).\n\n#### Validation\n\nValidating a Path Templating is as simple as importing the **test** function and calling it.\n\n\n```js\nimport { test } from 'openapi-path-templating';\n\ntest('/pets/{petId}'); // =\u003e true\ntest('/a{petId}'); // =\u003e true\ntest('/pets'); // =\u003e true\ntest('/pets', { strict: true }); // =\u003e false (doesn't contain any template-expression)\n```\n\n#### Resolution\n\nResolving a Path Templating is as simple as importing the **resolve** function and calling it.\n\n```js\nimport { resolve } from 'openapi-path-templating';\n\nresolve('/pets/{petId}', { petId: 3 }); // =\u003e \"/pets/3\"\n```\n\nResolved Path Templating is automatically encoded using [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) function.\nIt is possible to provide a custom encoder.\n\n```js\nimport { resolve } from 'openapi-path-templating';\n\nresolve('/pets/{petId}', { petId: '/?#' }, {\n  encoder: (component) =\u003e component, // no encoding\n}); // =\u003e \"/pets//?#\"\n```\n\n#### Normalization\n\nNormalization of OpenAPI Path Template is a process of transforming the path template into its normalized form.\nNormalization is used to compare two path templates for equivalence and is based on **Syntax-Based Normalization** as defined in [RFC 3986, section 6.2.2](https://datatracker.ietf.org/doc/html/rfc3986#section-6.2.2).\n\n##### Syntax-Based normalization\n\nSyntax-Based normalization is a process of transforming the path template into its normalized form using\na fixed set of normalizers in following order:\n\n- [Case normalization](#case-normalization)\n- [Percent-Encoding normalization](#percent-encoding-normalization)\n- [Path segment normalization](#path-segment-normalization)\n\n```js\nimport { normalize } from '@swaggerexpert/openapi-path-templating';\n\nnormalize('/api/{userId}/profile/../account/%41ccount'); // =\u003e '/api/{userId}/account/Account'\n```\n\nSyntax-Based normalization is a default normalization strategy used by this library.\n\n\n###### No normalization\n\nNoop normalizer that acts as identity function. Performs no transformations on the path template\nand returns it as is.\n\n```js\nimport { identityNormalizer } from '@swaggerexpert/openapi-path-templating';\n\nidentityNormalizer('/API/%2faPi/%7bsection%7d/./../profile'); // =\u003e '/API/%2faPi/%7bsection%7d/./../profile'\n```\n\n###### Case normalization\n\nFor all path templates, the hexadecimal digits within a percent-encoding\ntriplet (e.g., `\"%3a\"` versus `\"%3A\"`) are case-insensitive and therefore\nshould be normalized to use uppercase letters for the digits A-F.\n\n```js\nimport { caseNormalizer } from '@swaggerexpert/openapi-path-templating';\n\ncaseNormalizer('/api/{userId}/profile/%7bsection%7d'); // =\u003e '/api/{userId}/profile/%7Bsection%7D'\n```\n\n###### Percent-Encoding normalization\n\nThe percent-encoding mechanism is a frequent source of\nvariance among otherwise identical path templates. In addition to the case\nnormalization issue noted above, some path template producers percent-encode\noctets that do not require percent-encoding, resulting in path templates that\nare equivalent to their non-encoded counterparts. These path templates should\nbe normalized by decoding any percent-encoded octet that corresponds\nto an unreserved character.\n\n```js\nimport { percentEndingNormalizer } from '@swaggerexpert/openapi-path-templating';\n\npercentEndingNormalizer('/api/%7BuserId%7D/profile/%41ccount/{account}'); // =\u003e '/api/%7BuserId%7D/profile/Account/{account}'\n```\n\n###### Path segment normalization\n\nThe complete path segments `\".\"` and `\"..\"` are intended for use\nwithin path templates and are removed as part of\nthe reference resolution process. Path template segment normalizer removes\ndot-segments by applying the [remove_dot_segments](https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4) algorithm to the path template.\n\n```js\nimport { pathSegmentNormalizer } from '@swaggerexpert/openapi-path-templating';\n\npathSegmentNormalizer('/api/{userId}/./profile/../account'); // =\u003e '/api/{userId}/account'\n```\n\n**NOTE**: note that all normalizers acts as identity functions when invalid path template is provided.\n\n#### Matching\n\nPath templating matching in OpenAPI prioritizes concrete paths over parameterized ones,\ntreats paths with identical structures but different parameter names as invalid,\nand considers paths with overlapping patterns that could match the same request as potentially ambiguous.\n\n##### Equivalence\n\n`isIdentical`\n\nDetermines whether two path templates are structurally identical, meaning they have the same sequence\nof literals and template expressions, regardless of template expression names. In the OpenAPI context,\nsuch identical paths are considered invalid due to potential conflicts in routing.\n\nTesting path templates for equality is normally based on pair comparison of the\ncharacters that make up the strings, starting from the first and\nproceeding until both strings are exhausted and all characters are\nfound to be equal, until a pair of characters compares unequal, or\nuntil one of the strings is exhausted before the other. More in [RFC 3986, section 6.2.1](https://datatracker.ietf.org/doc/html/rfc3986#section-6.2.1).\n\n```js\nimport { isIdentical } from 'openapi-path-templating';\n\nisIdentical('/pets/{petId}', '/pets/{name}'); // =\u003e true\nisIdentical('/pets/{petId}', '/animals/{name}'); // =\u003e false\n```\n\nBy default, extensive [normalization](#normalization) prior to comparison is applied to produce a normalized form of the path template.\n\n```js\nimport { isIdentical, normalize, identityNormalizer } from 'openapi-path-templating';\n\n// default behavior\nisIdentical('/API/%2faPi/%7bsection%7d/./../profile', '/API/%2FaPi/profile'); // =\u003e true\nisIdentical('/api/{userId}/account/Account', '/api/{userId}/profile/../account/%41ccount'); // =\u003e true\n// equivalent to above\nisIdentical('/API/%2faPi/%7bsection%7d/./../profile', '/API/%2FaPi/profile', { normalizer: normalize }); // =\u003e true\nisIdentical('/api/{userId}/account/Account', '/api/{userId}/profile/../account/%41ccount', { normalizer: normalize }); // =\u003e true\n// no normalization\nisIdentical('/API/%2faPi/%7bsection%7d/./../profile', '/API/%2FaPi/profile', { normalizer: identityNormalizer }); // =\u003e false\nisIdentical('/api/{userId}/account/Account', '/api/{userId}/profile/../account/%41ccount', { normalizer: identityNormalizer }); // =\u003e false\n```\n\n#### Grammar\n\nNew grammar instance can be created in following way:\n\n```js\nimport { Grammar } from 'openapi-path-templating';\n\nconst grammar = new Grammar();\n```\n\nTo obtain original ABNF (SABNF) grammar as a string:\n\n```js\nimport { Grammar } from 'openapi-path-templating';\n\nconst grammar = new Grammar();\n\ngrammar.toString();\n// or\nString(grammar);\n```\n\n## More about OpenAPI Path Templating\n\nThe Path Templating is defined by the following [ABNF](https://tools.ietf.org/html/rfc5234) syntax\n\n```abnf\n; OpenAPI Path Templating ABNF syntax\n; variant of https://datatracker.ietf.org/doc/html/rfc3986#section-3.3\npath-template                  = slash *( path-segment slash ) [ path-segment ]\npath-segment                   = 1*( path-literal / template-expression )\nslash                          = \"/\"\npath-literal                   = 1*pchar\ntemplate-expression            = \"{\" template-expression-param-name \"}\"\ntemplate-expression-param-name = 1*( %x00-7A / %x7C / %x7E-10FFFF ) ; every UTF8 character except { and } (from OpenAPI)\n\n; https://datatracker.ietf.org/doc/html/rfc3986#section-3.3\npchar               = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\nunreserved          = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n                    ; https://datatracker.ietf.org/doc/html/rfc3986#section-2.3\npct-encoded         = \"%\" HEXDIG HEXDIG\n                    ; https://datatracker.ietf.org/doc/html/rfc3986#section-2.1\nsub-delims          = \"!\" / \"$\" / \"\u0026\" / \"'\" / \"(\" / \")\"\n                    / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n                    ; https://datatracker.ietf.org/doc/html/rfc3986#section-2.2\n\n; https://datatracker.ietf.org/doc/html/rfc5234#appendix-B.1\nALPHA               = %x41-5A / %x61-7A   ; A-Z / a-z\nDIGIT               = %x30-39            ; 0-9\nHEXDIG              = DIGIT / \"A\" / \"B\" / \"C\" / \"D\" / \"E\" / \"F\"\n```\n\n## License\n\n`openapi-path-templating` is licensed under [Apache 2.0 license](https://github.com/swaggerexpert/openapi-path-templating/blob/main/LICENSE).\n`openapi-path-templating` comes with an explicit [NOTICE](https://github.com/swaggerexpert/openapi-path-templating/blob/main/NOTICE) file\ncontaining additional legal notices and information.\n","funding_links":["https://github.com/sponsors/char0n","https://tidelift.com/funding/github/npm/openapi-path-templating","https://patreon.com/char0n","https://ko-fi.com/char0n","https://liberapay.com/char0n","https://issuehunt.io/r/char0n","https://tidelift.com/badges/package/npm/openapi-path-templating","https://tidelift.com/subscription/pkg/npm-openapi-path-templating?utm_source=npm-openapi-path-templating\u0026utm_medium=referral\u0026utm_campaign=readme"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fswaggerexpert%2Fopenapi-path-templating","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fswaggerexpert%2Fopenapi-path-templating","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fswaggerexpert%2Fopenapi-path-templating/lists"}