0
# API Execution and Operations
1
2
Execute operations against OpenAPI specifications with parameter handling, security, and response processing.
3
4
## Capabilities
5
6
### Execute Function
7
8
Execute an operation by operationId or path/method combination.
9
10
```javascript { .api }
11
/**
12
* Execute an OpenAPI operation
13
* @param options - Execution configuration
14
* @returns Promise resolving to response object
15
*/
16
function execute(options: ExecutionOptions): Promise<ResponseObject>;
17
18
interface ExecutionOptions {
19
/** OpenAPI specification object */
20
spec: object;
21
/** Operation ID to execute */
22
operationId?: string;
23
/** Path name for the operation (alternative to operationId) */
24
pathName?: string;
25
/** HTTP method for the operation (alternative to operationId) */
26
method?: string;
27
/** Parameter values for the operation */
28
parameters?: ParameterValues;
29
/** Security requirements and credentials */
30
securities?: SecurityRequirements;
31
/** Base URL override */
32
baseURL?: string;
33
/** Context URL for relative URL resolution */
34
contextUrl?: string;
35
/** Server URL override (for OpenAPI 3.x) */
36
server?: string;
37
/** Server variable values (for OpenAPI 3.x) */
38
serverVariables?: Record<string, string>;
39
/** Function to intercept and modify requests */
40
requestInterceptor?: RequestInterceptor;
41
/** Function to intercept and modify responses */
42
responseInterceptor?: ResponseInterceptor;
43
/** Custom HTTP client */
44
http?: HttpClient;
45
/** Legacy fetch function */
46
fetch?: FetchFunction;
47
/** Custom fetch implementation */
48
userFetch?: FetchFunction;
49
/** AbortSignal for request cancellation */
50
signal?: AbortSignal;
51
/** URL scheme override (for Swagger 2.0) */
52
scheme?: string;
53
/** Response content type preference */
54
responseContentType?: string;
55
/** Custom parameter builders */
56
parameterBuilders?: ParameterBuilders;
57
/** Server variable encoder function */
58
serverVariableEncoder?: (value: string) => string;
59
}
60
61
interface ResponseObject {
62
/** Request URL */
63
url: string;
64
/** HTTP method used */
65
method: string;
66
/** HTTP status code */
67
status: number;
68
/** HTTP status text */
69
statusText: string;
70
/** Response headers */
71
headers: Record<string, string>;
72
/** Response body as text */
73
text: string;
74
/** Parsed response body */
75
body: any;
76
/** Alias for body */
77
obj: any;
78
/** Whether response was successful (2xx status) */
79
ok: boolean;
80
/** Alias for body */
81
data: any;
82
}
83
```
84
85
**Usage Examples:**
86
87
```javascript
88
import { execute } from "swagger-client";
89
90
// Execute by operation ID
91
const response = await execute({
92
spec: openApiSpec,
93
operationId: "getPetById",
94
parameters: {
95
petId: 123
96
}
97
});
98
99
// Execute by path and method
100
const response = await execute({
101
spec: openApiSpec,
102
pathName: "/pets/{petId}",
103
method: "GET",
104
parameters: {
105
petId: 123
106
}
107
});
108
109
// Execute with security
110
const response = await execute({
111
spec: openApiSpec,
112
operationId: "createPet",
113
parameters: {
114
body: {
115
name: "Fluffy",
116
status: "available"
117
}
118
},
119
securities: {
120
authorized: {
121
ApiKeyAuth: { value: "your-api-key" }
122
}
123
}
124
});
125
126
// Execute with custom base URL
127
const response = await execute({
128
spec: openApiSpec,
129
operationId: "listPets",
130
baseURL: "https://api-staging.example.com"
131
});
132
133
// Execute with interceptors
134
const response = await execute({
135
spec: openApiSpec,
136
operationId: "getPetById",
137
parameters: { petId: 123 },
138
requestInterceptor: (req) => {
139
console.log("Sending request:", req.method, req.url);
140
req.headers["X-Request-ID"] = crypto.randomUUID();
141
return req;
142
},
143
responseInterceptor: (res) => {
144
console.log("Received response:", res.status);
145
return res;
146
}
147
});
148
```
149
150
### Operation Execution Errors
151
152
Handle common execution errors and exceptions.
153
154
```javascript { .api }
155
/**
156
* Error thrown when operation ID cannot be found in the spec
157
*/
158
class OperationNotFoundError extends Error {
159
constructor(message: string);
160
name: "OperationNotFoundError";
161
}
162
163
// Usage example:
164
try {
165
const response = await execute({
166
spec: openApiSpec,
167
operationId: "nonExistentOperation"
168
});
169
} catch (error) {
170
if (error instanceof OperationNotFoundError) {
171
console.error("Operation not found:", error.message);
172
}
173
}
174
```
175
176
### Parameter Handling
177
178
How parameters are processed and validated for different OpenAPI versions.
179
180
```javascript { .api }
181
interface ParameterValues {
182
/** Parameter values by name */
183
[parameterName: string]: any;
184
/** Alternative format: parameter values by location and name */
185
[locationAndName: string]: any; // e.g., "query.limit", "header.authorization"
186
}
187
188
interface ParameterBuilders {
189
/** Build path parameters */
190
path?: ParameterBuilder;
191
/** Build query parameters */
192
query?: ParameterBuilder;
193
/** Build header parameters */
194
header?: ParameterBuilder;
195
/** Build cookie parameters */
196
cookie?: ParameterBuilder;
197
/** Build form data parameters */
198
formData?: ParameterBuilder;
199
/** Build request body */
200
body?: ParameterBuilder;
201
}
202
203
interface ParameterBuilder {
204
(options: ParameterBuildOptions): void;
205
}
206
207
interface ParameterBuildOptions {
208
req: RequestObject;
209
parameter: ParameterObject;
210
value: any;
211
operation: OperationObject;
212
spec: object;
213
baseURL: string;
214
}
215
```
216
217
**Parameter Examples:**
218
219
```javascript
220
// Path parameters
221
await execute({
222
spec: openApiSpec,
223
operationId: "getUserById",
224
parameters: {
225
userId: "12345" // Replaces {userId} in path
226
}
227
});
228
229
// Query parameters
230
await execute({
231
spec: openApiSpec,
232
operationId: "searchUsers",
233
parameters: {
234
q: "john",
235
limit: 10,
236
offset: 0
237
}
238
});
239
240
// Header parameters
241
await execute({
242
spec: openApiSpec,
243
operationId: "getProtectedResource",
244
parameters: {
245
"X-API-Key": "your-api-key",
246
"Accept-Language": "en-US"
247
}
248
});
249
250
// Request body (OpenAPI 3.x)
251
await execute({
252
spec: openApiSpec,
253
operationId: "createUser",
254
parameters: {
255
body: {
256
name: "John Doe",
257
email: "john@example.com"
258
}
259
}
260
});
261
262
// Form data (Swagger 2.0)
263
await execute({
264
spec: swagger2Spec,
265
operationId: "uploadFile",
266
parameters: {
267
file: fileObject,
268
description: "My file"
269
}
270
});
271
272
// Ambiguous parameter names (use location.name format)
273
await execute({
274
spec: openApiSpec,
275
operationId: "operation",
276
parameters: {
277
"query.id": "query-id",
278
"header.id": "header-id"
279
}
280
});
281
```
282
283
### Security Requirements
284
285
Handle authentication and authorization for protected operations.
286
287
```javascript { .api }
288
interface SecurityRequirements {
289
/** Authorized security schemes */
290
authorized?: SecurityAuthorizations;
291
}
292
293
interface SecurityAuthorizations {
294
[securityName: string]: SecurityValue;
295
}
296
297
interface SecurityValue {
298
/** Username for HTTP Basic auth */
299
username?: string;
300
/** Password for HTTP Basic auth */
301
password?: string;
302
/** Client ID for OAuth2 */
303
clientId?: string;
304
/** Client secret for OAuth2 */
305
clientSecret?: string;
306
/** API key or bearer token value */
307
value?: string;
308
}
309
```
310
311
**Security Examples:**
312
313
```javascript
314
// API Key authentication
315
const response = await execute({
316
spec: openApiSpec,
317
operationId: "getProtectedData",
318
securities: {
319
authorized: {
320
ApiKeyAuth: { value: "your-api-key" }
321
}
322
}
323
});
324
325
// Basic authentication
326
const response = await execute({
327
spec: openApiSpec,
328
operationId: "getProtectedData",
329
securities: {
330
authorized: {
331
BasicAuth: {
332
username: "user",
333
password: "password"
334
}
335
}
336
}
337
});
338
339
// Bearer token authentication
340
const response = await execute({
341
spec: openApiSpec,
342
operationId: "getProtectedData",
343
securities: {
344
authorized: {
345
BearerAuth: { value: "jwt-token-here" }
346
}
347
}
348
});
349
350
// OAuth2 authentication
351
const response = await execute({
352
spec: openApiSpec,
353
operationId: "getProtectedData",
354
securities: {
355
authorized: {
356
OAuth2: {
357
clientId: "client-id",
358
clientSecret: "client-secret"
359
}
360
}
361
}
362
});
363
```
364
365
### Server Selection (OpenAPI 3.x)
366
367
Override server URLs and server variables for OpenAPI 3.x specifications.
368
369
```javascript { .api }
370
// Server selection by URL
371
const response = await execute({
372
spec: openApiSpec,
373
operationId: "getData",
374
server: "https://api-staging.example.com"
375
});
376
377
// Server variables
378
const response = await execute({
379
spec: openApiSpec,
380
operationId: "getData",
381
server: "https://{environment}.example.com",
382
serverVariables: {
383
environment: "staging"
384
}
385
});
386
387
// Custom server variable encoder
388
const response = await execute({
389
spec: openApiSpec,
390
operationId: "getData",
391
serverVariables: {
392
version: "v2"
393
},
394
serverVariableEncoder: (value) => encodeURIComponent(value)
395
});
396
```
397
398
## Common Types
399
400
```javascript { .api }
401
interface RequestInterceptor {
402
(request: RequestObject): RequestObject | Promise<RequestObject>;
403
}
404
405
interface ResponseInterceptor {
406
(response: ResponseObject): ResponseObject | Promise<ResponseObject>;
407
}
408
409
interface HttpClient {
410
(url: string, options?: HttpOptions): Promise<ResponseObject>;
411
withCredentials?: boolean;
412
}
413
414
interface FetchFunction {
415
(url: string, options?: RequestInit): Promise<Response>;
416
}
417
418
interface RequestObject {
419
url: string;
420
method: string;
421
headers: Record<string, string>;
422
body?: any;
423
credentials: RequestCredentials;
424
signal?: AbortSignal;
425
requestInterceptor?: RequestInterceptor;
426
responseInterceptor?: ResponseInterceptor;
427
userFetch?: FetchFunction;
428
}
429
430
interface ParameterObject {
431
name: string;
432
in: "query" | "header" | "path" | "cookie" | "body" | "formData";
433
required?: boolean;
434
schema?: SchemaObject;
435
type?: string;
436
default?: any;
437
allowEmptyValue?: boolean;
438
}
439
440
interface OperationObject {
441
operationId?: string;
442
tags?: string[];
443
parameters?: ParameterObject[];
444
security?: SecurityRequirement[];
445
servers?: ServerObject[];
446
}
447
```