docs
0
# Server and URL Management
1
2
Server URL handling with variable substitution, templating, and multi-server support for OpenAPI definitions.
3
4
## Capabilities
5
6
### Get Server URL
7
8
Get a fully resolved server URL with variable substitution.
9
10
```typescript { .api }
11
/**
12
* Get server URL with variables replaced
13
* @param selected - Index of server to use (default: 0)
14
* @param variables - Server variables to substitute
15
* @returns Fully resolved server URL
16
*/
17
url(selected?: number, variables?: ServerVariable): string;
18
```
19
20
**Usage Examples:**
21
22
```typescript
23
// Basic usage with first server
24
const serverUrl = oas.url(); // "https://api.example.com"
25
26
// Use second server
27
const secondUrl = oas.url(1); // "https://staging.example.com"
28
29
// With variable substitution
30
const customUrl = oas.url(0, { region: "us-west", version: "v2" });
31
// Result: "https://us-west.api.example.com/v2"
32
```
33
34
### Get Server Variables
35
36
Get server variables and their configuration for a specific server.
37
38
```typescript { .api }
39
/**
40
* Get server variables configuration
41
* @param selected - Index of server to get variables for (default: 0)
42
* @returns Server variables object with enum options and defaults
43
*/
44
variables(selected?: number): ServerVariablesObject;
45
```
46
47
**Usage Examples:**
48
49
```typescript
50
const variables = oas.variables();
51
// Result: { region: { default: "us", enum: ["us", "eu"] }, version: { default: "v1" } }
52
53
// Check available options
54
if (variables.region?.enum) {
55
console.log("Available regions:", variables.region.enum);
56
}
57
```
58
59
### Get Default Variables
60
61
Get default values for all server variables with user overrides.
62
63
```typescript { .api }
64
/**
65
* Get default variable values with user overrides
66
* @param selected - Index of server to get defaults for (default: 0)
67
* @returns Object with default values for each variable
68
*/
69
defaultVariables(selected?: number): ServerVariable;
70
```
71
72
**Usage Examples:**
73
74
```typescript
75
// Get defaults for first server
76
const defaults = oas.defaultVariables();
77
// Result: { region: "us", version: "v1" }
78
79
// Defaults respect user context from constructor
80
const oasWithUser = new Oas(definition, { region: "eu" });
81
const userDefaults = oasWithUser.defaultVariables();
82
// Result: { region: "eu", version: "v1" }
83
```
84
85
### Split URL into Components
86
87
Break down a server URL into text and variable components for UI rendering.
88
89
```typescript { .api }
90
/**
91
* Split server URL into text and variable components
92
* @param selected - Index of server to split (default: 0)
93
* @returns Array of text and variable components with metadata
94
*/
95
splitUrl(selected?: number): Array<{
96
key: string;
97
type: 'text' | 'variable';
98
value: string;
99
description?: string;
100
enum?: string[];
101
}>;
102
```
103
104
**Usage Examples:**
105
106
```typescript
107
// For URL: "https://{region}.api.example.com/{version}"
108
const components = oas.splitUrl();
109
// Result: [
110
// { key: "https://-0", type: "text", value: "https://" },
111
// { key: "region-1", type: "variable", value: "region", enum: ["us", "eu"] },
112
// { key: ".api.example.com/-2", type: "text", value: ".api.example.com/" },
113
// { key: "version-3", type: "variable", value: "version" }
114
// ]
115
116
// Build dynamic UI
117
components.forEach(component => {
118
if (component.type === "variable") {
119
console.log(`Variable: ${component.value}, options: ${component.enum?.join(", ")}`);
120
}
121
});
122
```
123
124
### Replace Variables in URL
125
126
Replace templated variables in any URL string with provided values.
127
128
```typescript { .api }
129
/**
130
* Replace templated variables with values in a URL
131
* @param url - URL string with {variable} templates
132
* @param variables - Variable values to substitute (falls back to user context)
133
* @returns URL with variables replaced
134
*/
135
replaceUrl(url: string, variables?: ServerVariable): string;
136
```
137
138
**Usage Examples:**
139
140
```typescript
141
// Basic replacement
142
const url = "https://{region}.example.com/{version}/api";
143
const resolved = oas.replaceUrl(url, { region: "us-west", version: "v2" });
144
// Result: "https://us-west.example.com/v2/api"
145
146
// Fallback to user context
147
const oasWithUser = new Oas(definition, { region: "eu" });
148
const userResolved = oasWithUser.replaceUrl(url);
149
// Result: "https://eu.example.com/{version}/api" (partial replacement)
150
151
// Handle missing variables gracefully
152
const partial = oas.replaceUrl("https://{region}.example.com/{missing}", { region: "us" });
153
// Result: "https://us.example.com/{missing}" (missing variables remain as-is)
154
```
155
156
### Extract Variables from URL
157
158
Extract server variables from a concrete URL by matching against server patterns.
159
160
```typescript { .api }
161
/**
162
* Extract server variables from a concrete URL
163
* @param baseUrl - Complete URL to extract variables from
164
* @returns Server selection and extracted variables, or false if no match
165
*/
166
splitVariables(baseUrl: string): Servers | false;
167
```
168
169
**Usage Examples:**
170
171
```typescript
172
// For servers: ["https://{region}.api.example.com/{version}"]
173
const extracted = oas.splitVariables("https://eu.api.example.com/v2/users");
174
// Result: { selected: 0, variables: { region: "eu", version: "v2" } }
175
176
if (extracted) {
177
console.log(`Using server ${extracted.selected} with region: ${extracted.variables.region}`);
178
179
// Reconstruct URL
180
const reconstructed = oas.url(extracted.selected, extracted.variables);
181
// Result: "https://eu.api.example.com/v2"
182
}
183
184
// No match case
185
const noMatch = oas.splitVariables("https://different.com/api");
186
// Result: false
187
```
188
189
## Advanced Usage
190
191
### Custom Variable Resolution
192
193
```typescript
194
// Complex variable handling
195
const serverUrl = "https://{env}-{region}.{domain}.com/{version}";
196
197
const variables = {
198
env: "prod",
199
region: { default: "us-east-1" }, // Object format
200
domain: "api",
201
version: "v1"
202
};
203
204
const resolved = oas.replaceUrl(serverUrl, variables);
205
// Result: "https://prod-us-east-1.api.com/v1"
206
```
207
208
### Multi-Server Management
209
210
```typescript
211
// Handle multiple servers
212
const servers = definition.servers || [];
213
servers.forEach((server, index) => {
214
console.log(`Server ${index}: ${oas.url(index)}`);
215
216
const vars = oas.variables(index);
217
if (Object.keys(vars).length > 0) {
218
console.log(`Variables: ${Object.keys(vars).join(", ")}`);
219
}
220
});
221
```
222
223
### URL Normalization
224
225
The library automatically handles URL normalization:
226
227
- Adds `https://` protocol if missing
228
- Removes trailing slashes
229
- Handles malformed URLs gracefully
230
- Converts `//example.com` to `https://example.com`
231
- Falls back to `https://example.com` for invalid servers
232
233
```typescript
234
// These all get normalized properly
235
const urls = [
236
"//api.example.com", // -> https://api.example.com
237
"api.example.com/", // -> https://api.example.com
238
"/api/v1", // -> https://example.com/api/v1
239
"" // -> https://example.com
240
];
241
```