OpenAPI Server URL Templating
The `openapi-server-url-templating` library provides a robust, specification-compliant mechanism for parsing, validating, and performing substitutions on server URLs as defined within the OpenAPI Specification. It comprehensively supports server URL templating features, including Server Variables, across various OpenAPI versions from 3.0.0 through 3.1.1. The current stable version is 1.3.0, released in December 2024, indicating an active development and maintenance cadence. A key differentiator is its foundational role in establishing the official ABNF grammar for Server URL Templating within the OpenAPI Specification itself, which ensures a high degree of fidelity and accuracy to the standard. The library leverages `apg-lite` for its underlying parsing and validation capabilities, offering a reliable tool for developers working with OpenAPI definitions.
Common errors
-
TypeError: (0 , openapi_server_url_templating__WEBPACK_IMPORTED_MODULE_0__.parse) is not a function
cause This typically indicates a mismatch between CommonJS `require` and ES module `import` syntax, often encountered in Webpack or similar bundler environments that misinterpret the module type.fixEnsure your project is configured to correctly handle ES modules. If using TypeScript, check `tsconfig.json` `module` and `moduleResolution` settings. For JavaScript, verify your bundler's configuration or explicitly use ESM imports in a module-aware context. -
GrammarError: no parse tree
cause The input URL template string does not conform to the expected OpenAPI server URL templating grammar, preventing successful parsing.fixReview the URL template for syntax errors, missing braces (`{`, `}`), or invalid characters according to the OpenAPI Specification's Server Object URL rules. Refer to the `parseResult` object for detailed error messages. -
Error: Variable 'someVar' is not defined in server variables.
cause The `validate` or `substitute` function was called with a URL template containing a variable that was not present in the provided `serverVariables` object.fixAdd a definition for `someVar` to your `serverVariables` object, even if it's just `someVar: { default: 'defaultValue' }`. All templated variables must have a corresponding entry.
Warnings
- breaking The grammar used for parsing and validating URL templates was aligned with the official OpenAPI Specification. While this improves correctness, it might lead to different parsing outcomes for malformed or non-standard templates that might have been accepted by earlier versions.
- gotcha Prior to v1.1.0, some environments might have experienced issues with module resolution due to the package's `imports` field configuration. This was fixed to improve compatibility.
- gotcha When using `validate` or `substitute`, ensure that all variables present in the URL template `{likeThis}` are defined in the `serverVariables` object. Undefined variables will cause validation to fail or substitution to result in unexpected output.
Install
-
npm install openapi-server-url-templating -
yarn add openapi-server-url-templating -
pnpm add openapi-server-url-templating
Imports
- parse
const { parse } = require('openapi-server-url-templating');import { parse } from 'openapi-server-url-templating'; - validate
import validate from 'openapi-server-url-templating';
import { validate } from 'openapi-server-url-templating'; - substitute
const substitute = require('openapi-server-url-templating').substitute;import { substitute } from 'openapi-server-url-templating'; - Grammar
import { Grammar } from 'openapi-server-url-templating';import type { Grammar } from 'openapi-server-url-templating';
Quickstart
import { parse, validate, substitute } from 'openapi-server-url-templating';
const urlTemplate = 'https://{username}.gigantic-server.com:{port}/{basePath}';
// 1. Parse the URL template
const parseResult = parse(urlTemplate);
console.log('Parse Success:', parseResult.result.success);
// 2. Define server variables for validation and substitution
const serverVariables = {
username: { default: 'demo', enum: ['demo', 'admin'] },
port: { default: '8443', enum: ['8443', '443'] },
basePath: { default: 'v2', enum: ['v1', 'v2'] }
};
// 3. Validate the URL template with variables
const validationResult = validate(urlTemplate, serverVariables);
console.log('Validation Success:', validationResult.result.success);
// 4. Substitute variables to get the final URL
const values = { username: 'admin', port: '443', basePath: 'v1' };
const substitutedUrl = substitute(urlTemplate, serverVariables, values);
console.log('Substituted URL:', substitutedUrl); // Expected: https://admin.gigantic-server.com:443/v1
// Example with default values
const substitutedUrlWithDefaults = substitute(urlTemplate, serverVariables, {});
console.log('Substituted URL (defaults):', substitutedUrlWithDefaults); // Expected: https://demo.gigantic-server.com:8443/v2