Skip to content

Instantly share code, notes, and snippets.

@vinitshahdeo
Last active April 22, 2023 16:05
Show Gist options
  • Save vinitshahdeo/ae76fae2350dfbd543cca66af42f1022 to your computer and use it in GitHub Desktop.
Save vinitshahdeo/ae76fae2350dfbd543cca66af42f1022 to your computer and use it in GitHub Desktop.
Resolve server URL template with variables for an OpenAPI 3.x definition
/**
* Resolve server URL template with variables for an OpenAPI 3.x definition
*
* GitHub Repo: https://github.com/vinitshahdeo/openapi-url-resolver
* NPM Package: https://www.npmjs.com/package/openapi-url-resolver
*/
const openapiUrlResolver = require('openapi-url-resolver');
const spec = {
openapi: '3.0.0',
servers: [
{
url: 'https://{username}.gigantic-server.com:{port}/{basePath}',
description: 'The production API server',
variables: {
username: {
default: 'demo',
description: 'this value is assigned by the service provider, in this example `gigantic-server.com`'
},
port: {
enum: ['8443', '443'],
default: '8443'
},
basePath: {
default: 'v2'
}
}
}
]
};
const hosts = openapiUrlResolver.resolve(spec);
/*
[
'demo.gigantic-server.com:8443/v2',
'demo.gigantic-server.com:443/v2'
]
*/
console.log(hosts);
// Pass false as second parameter to get the server URLs with protocols.
const serverUrls = openapiUrlResolver.resolve(spec, false)
/*
[
'https://demo.gigantic-server.com:8443/v2',
'https://demo.gigantic-server.com:443/v2'
]
*/
console.log(serverUrls);
@vinitshahdeo
Copy link
Author

openapi-url-resolver is a lightweight NPM package that provides a simple and efficient way to resolve server URLs from OpenAPI specifications.

NPM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment