0
# Client Construction and Configuration
1
2
SwaggerClient constructor and configuration options for initializing clients with OpenAPI specifications.
3
4
## Capabilities
5
6
### SwaggerClient Constructor
7
8
Creates a SwaggerClient instance with automatic spec resolution and interface generation.
9
10
```javascript { .api }
11
/**
12
* Creates a SwaggerClient instance
13
* @param options - Configuration options for the client
14
* @returns Promise resolving to configured SwaggerClient instance
15
*/
16
function SwaggerClient(options?: SwaggerClientOptions): Promise<SwaggerClientInstance>;
17
function SwaggerClient(url: string, options?: SwaggerClientOptions): Promise<SwaggerClientInstance>;
18
19
interface SwaggerClientOptions {
20
/** URL to fetch the OpenAPI spec from */
21
url?: string;
22
/** OpenAPI spec object (alternative to url) */
23
spec?: object;
24
/** Security authorizations for protected operations */
25
authorizations?: SecurityAuthorizations;
26
/** Function to intercept and modify requests before sending */
27
requestInterceptor?: RequestInterceptor;
28
/** Function to intercept and modify responses after receiving */
29
responseInterceptor?: ResponseInterceptor;
30
/** Allow patching of meta patches during resolution */
31
allowMetaPatches?: boolean;
32
/** Use circular structures during resolution */
33
useCircularStructures?: boolean;
34
/** Custom HTTP client implementation */
35
http?: HttpClient;
36
/** Legacy fetch function (use userFetch instead) */
37
fetch?: FetchFunction;
38
/** Custom fetch implementation */
39
userFetch?: FetchFunction;
40
/** Disable automatic interface generation */
41
disableInterfaces?: boolean;
42
/** Skip normalization during resolution */
43
skipNormalization?: boolean;
44
/** Array of paths to discriminate during resolution */
45
pathDiscriminator?: string[];
46
/** Use v2 operation ID compatibility mode */
47
v2OperationIdCompatibilityMode?: boolean;
48
}
49
50
interface SwaggerClientInstance {
51
/** Resolved OpenAPI specification */
52
spec: object;
53
/** Original spec before resolution */
54
originalSpec?: object;
55
/** Resolution errors encountered */
56
errors: ResolutionError[];
57
/** Tag-based operation interfaces */
58
apis: TaggedOperations;
59
/** Security authorizations */
60
authorizations?: SecurityAuthorizations;
61
/** Execute an operation */
62
execute(options: ExecutionOptions): Promise<ResponseObject>;
63
/** Re-resolve the specification */
64
resolve(options?: ResolveOptions): Promise<SwaggerClientInstance>;
65
}
66
```
67
68
**Usage Examples:**
69
70
```javascript
71
// Initialize with URL
72
const client = await SwaggerClient({
73
url: "https://petstore.swagger.io/v2/swagger.json"
74
});
75
76
// Initialize with spec object
77
const client = await SwaggerClient({
78
spec: {
79
openapi: "3.0.0",
80
info: { title: "API", version: "1.0.0" },
81
paths: {}
82
}
83
});
84
85
// Initialize with URL as first parameter
86
const client = await SwaggerClient("https://api.example.com/openapi.json");
87
88
// Initialize with authorizations
89
const client = await SwaggerClient({
90
url: "https://api.example.com/openapi.json",
91
authorizations: {
92
ApiKeyAuth: { value: "your-api-key" },
93
BasicAuth: { username: "user", password: "pass" }
94
}
95
});
96
97
// Initialize with interceptors
98
const client = await SwaggerClient({
99
url: "https://api.example.com/openapi.json",
100
requestInterceptor: (req) => {
101
req.headers["X-Custom-Header"] = "value";
102
return req;
103
},
104
responseInterceptor: (res) => {
105
console.log("Response received:", res.status);
106
return res;
107
}
108
});
109
```
110
111
### Static Methods
112
113
Static methods available on the SwaggerClient constructor.
114
115
```javascript { .api }
116
/** Default HTTP client */
117
SwaggerClient.http: HttpFunction;
118
119
/** Create custom HTTP client wrapper */
120
SwaggerClient.makeHttp: (httpFn: HttpFunction, preFetch?: Function, postFetch?: Function) => HttpFunction;
121
122
/** Resolve OpenAPI specifications */
123
SwaggerClient.resolve: (options: ResolveOptions) => Promise<ResolutionResult>;
124
125
/** Resolve specification subtrees */
126
SwaggerClient.resolveSubtree: (options: ResolveOptions) => Promise<ResolutionResult>;
127
128
/** Execute operations */
129
SwaggerClient.execute: (options: ExecutionOptions) => Promise<ResponseObject>;
130
131
/** Build HTTP requests */
132
SwaggerClient.buildRequest: (options: BuildRequestOptions) => RequestObject;
133
134
/** Get base URL for operations */
135
SwaggerClient.getBaseUrl: (options: BaseUrlOptions) => string;
136
137
/** Serialize responses */
138
SwaggerClient.serializeRes: (response: Response, url: string, request: RequestObject) => Promise<ResponseObject>;
139
140
/** Serialize headers */
141
SwaggerClient.serializeHeaders: (headers: Headers) => Record<string, string>;
142
143
/** Clear resolver caches */
144
SwaggerClient.clearCache: () => void;
145
146
/** Create tag-based operation interfaces */
147
SwaggerClient.makeApisTagOperation: (swaggerClient: SwaggerClientInstance) => { apis: TaggedOperations };
148
149
/** Create custom resolver with strategies */
150
SwaggerClient.makeResolve: (defaultOptions: ResolveOptions) => (options: ResolveOptions) => Promise<ResolutionResult>;
151
152
/** Create custom subtree resolver with strategies */
153
SwaggerClient.makeResolveSubtree: (defaultOptions: SubtreeOptions) => (obj: object, path: string[], options?: SubtreeOptions) => Promise<ResolutionResult>;
154
155
/** Helper utilities */
156
SwaggerClient.helpers: {
157
opId: (operation: OperationObject, pathName: string, method: string, options?: OpIdOptions) => string;
158
};
159
```
160
161
### Resolution Strategies
162
163
Available resolution strategies for different OpenAPI versions.
164
165
```javascript { .api }
166
SwaggerClient.resolveStrategies: {
167
"openapi-3-1-apidom": ResolveStrategy;
168
"openapi-3-0": ResolveStrategy;
169
"openapi-2-0": ResolveStrategy;
170
"generic": ResolveStrategy;
171
};
172
173
interface ResolveStrategy {
174
match(spec: object): boolean;
175
normalize(spec: object): object;
176
resolve(options: ResolveOptions): Promise<ResolutionResult>;
177
}
178
```
179
180
### ApiDOM Integration
181
182
Advanced parsing and dereferencing capabilities using ApiDOM.
183
184
```javascript { .api }
185
SwaggerClient.apidom: {
186
resolve: {
187
resolvers: {
188
HTTPResolverSwaggerClient: ApiDOMResolver;
189
};
190
};
191
parse: {
192
parsers: {
193
JsonParser: ApiDOMParser;
194
YamlParser: ApiDOMParser;
195
OpenApiJson3_1Parser: ApiDOMParser;
196
OpenApiYaml3_1Parser: ApiDOMParser;
197
};
198
};
199
dereference: {
200
strategies: {
201
OpenApi3_1SwaggerClientDereferenceStrategy: ApiDOMDereferenceStrategy;
202
};
203
};
204
};
205
```
206
207
### Instance Methods
208
209
Methods available on SwaggerClient instances.
210
211
```javascript { .api }
212
/**
213
* Execute an operation on this client instance
214
* @param options - Execution options
215
* @returns Promise resolving to response object
216
*/
217
execute(options: Omit<ExecutionOptions, 'spec'>): Promise<ResponseObject>;
218
219
/**
220
* Re-resolve the specification for this client instance
221
* @param options - Resolution options
222
* @returns Promise resolving to this client instance
223
*/
224
resolve(options?: ResolveOptions): Promise<SwaggerClientInstance>;
225
226
/**
227
* Apply default values to the specification
228
* Adds default hosts, schemes, servers for different OpenAPI versions
229
*/
230
applyDefaults(): void;
231
```
232
233
## Common Types
234
235
```javascript { .api }
236
interface SecurityAuthorizations {
237
[securityName: string]: SecurityValue;
238
}
239
240
interface SecurityValue {
241
/** Username for basic auth */
242
username?: string;
243
/** Password for basic auth */
244
password?: string;
245
/** Client ID for OAuth2 */
246
clientId?: string;
247
/** Client secret for OAuth2 */
248
clientSecret?: string;
249
/** API key or bearer token value */
250
value?: string;
251
}
252
253
interface RequestInterceptor {
254
(request: RequestObject): RequestObject | Promise<RequestObject>;
255
}
256
257
interface ResponseInterceptor {
258
(response: ResponseObject): ResponseObject | Promise<ResponseObject>;
259
}
260
261
interface HttpClient {
262
(url: string, options?: HttpOptions): Promise<ResponseObject>;
263
withCredentials?: boolean;
264
}
265
266
interface FetchFunction {
267
(url: string, options?: RequestInit): Promise<Response>;
268
}
269
270
interface ResolutionError {
271
message: string;
272
fullPath: string[];
273
}
274
275
interface TaggedOperations {
276
[tagName: string]: {
277
[operationId: string]: (parameters?: ParameterValues, options?: ExecutionOptions) => Promise<ResponseObject>;
278
};
279
}
280
281
interface SubtreeOptions {
282
/** Return entire tree instead of just the subtree */
283
returnEntireTree?: boolean;
284
/** Base document for resolution context */
285
baseDoc?: object;
286
/** Function to intercept requests */
287
requestInterceptor?: RequestInterceptor;
288
/** Function to intercept responses */
289
responseInterceptor?: ResponseInterceptor;
290
/** Use circular structures in resolution */
291
useCircularStructures?: boolean;
292
/** Resolution strategies to use */
293
strategies?: ResolveStrategy[];
294
}
295
296
interface ResolveStrategy {
297
/** Check if this strategy can handle the given spec */
298
match(spec: object): boolean;
299
/** Normalize the specification */
300
normalize(spec: object): object;
301
/** Resolve the specification */
302
resolve(options: ResolveOptions): Promise<ResolutionResult>;
303
}
304
```