0
# OpenAPI 3.1 Builder
1
2
Fluent DSL for creating OpenAPI 3.1 specification documents with enhanced JSON Schema support and webhook capabilities.
3
4
## Capabilities
5
6
### OpenApiBuilder Class
7
8
Main builder class for constructing OpenAPI 3.1 documents through a fluent interface. Inherits all OpenAPI 3.0 capabilities with 3.1-specific enhancements.
9
10
```typescript { .api }
11
/**
12
* Internal DSL for building an OpenAPI 3.1.x contract using a fluent interface
13
*/
14
class OpenApiBuilder {
15
rootDoc: oas31.OpenAPIObject;
16
17
/**
18
* Factory method to create a new builder instance
19
* @param doc - Optional initial OpenAPI document
20
* @returns New OpenApiBuilder instance
21
*/
22
static create(doc?: oas31.OpenAPIObject): OpenApiBuilder;
23
24
/**
25
* Constructor for OpenApiBuilder
26
* @param doc - Optional initial OpenAPI document, defaults to minimal 3.1 structure
27
*/
28
constructor(doc?: oas31.OpenAPIObject);
29
}
30
```
31
32
### Document Access Methods
33
34
Same as OpenAPI 3.0 with OpenAPI 3.1 document support.
35
36
```typescript { .api }
37
/**
38
* Get the current OpenAPI 3.1 document
39
* @returns The OpenAPI 3.1 document object
40
*/
41
getSpec(): oas31.OpenAPIObject;
42
43
/**
44
* Serialize the OpenAPI document to JSON string
45
* @param replacer - JSON.stringify replacer function
46
* @param space - Indentation for pretty printing
47
* @returns JSON string representation
48
*/
49
getSpecAsJson(
50
replacer?: (key: string, value: unknown) => unknown,
51
space?: string | number
52
): string;
53
54
/**
55
* Serialize the OpenAPI document to YAML string
56
* @param replacer - YAML stringify replacer
57
* @param options - YAML stringify options
58
* @returns YAML string representation
59
*/
60
getSpecAsYaml(
61
replacer?: Parameters<typeof yaml.stringify>[1],
62
options?: Parameters<typeof yaml.stringify>[2]
63
): string;
64
```
65
66
### Document Metadata Methods
67
68
All OpenAPI 3.0 metadata methods are available with OpenAPI 3.1 type support. All methods return `OpenApiBuilder` for chaining.
69
70
```typescript { .api }
71
/**
72
* Set the OpenAPI version (defaults to 3.1.0)
73
* @param openApiVersion - OpenAPI version string (e.g., "3.1.0")
74
* @returns Builder instance for chaining
75
* @throws Error if version format is invalid
76
*/
77
addOpenApiVersion(openApiVersion: string): OpenApiBuilder;
78
79
/**
80
* Set the info object
81
* @param info - Complete info object
82
* @returns Builder instance for chaining
83
*/
84
addInfo(info: oas31.InfoObject): OpenApiBuilder;
85
86
/**
87
* Set contact information
88
* @param contact - Contact object with name, url, email
89
* @returns Builder instance for chaining
90
*/
91
addContact(contact: oas31.ContactObject): OpenApiBuilder;
92
93
/**
94
* Set license information (with optional identifier field for OpenAPI 3.1)
95
* @param license - License object with name, optional url and identifier
96
* @returns Builder instance for chaining
97
*/
98
addLicense(license: oas31.LicenseObject): OpenApiBuilder;
99
100
/**
101
* Set API title
102
* @param title - API title string
103
* @returns Builder instance for chaining
104
*/
105
addTitle(title: string): OpenApiBuilder;
106
107
/**
108
* Set API description
109
* @param description - API description string
110
* @returns Builder instance for chaining
111
*/
112
addDescription(description: string): OpenApiBuilder;
113
114
/**
115
* Set terms of service URL
116
* @param termsOfService - Terms of service URL
117
* @returns Builder instance for chaining
118
*/
119
addTermsOfService(termsOfService: string): OpenApiBuilder;
120
121
/**
122
* Set API version
123
* @param version - API version string
124
* @returns Builder instance for chaining
125
*/
126
addVersion(version: string): OpenApiBuilder;
127
```
128
129
### Path and Operation Methods
130
131
Enhanced path support with optional paths object in OpenAPI 3.1.
132
133
```typescript { .api }
134
/**
135
* Add or merge a path item (paths object is optional in OpenAPI 3.1)
136
* @param path - URL path string (e.g., "/pets/{id}")
137
* @param pathItem - Path item object with operations
138
* @returns Builder instance for chaining
139
*/
140
addPath(path: string, pathItem: oas31.PathItemObject): OpenApiBuilder;
141
```
142
143
### Webhook Methods (OpenAPI 3.1 Specific)
144
145
OpenAPI 3.1 introduces webhook support for defining callback operations initiated by the API provider.
146
147
```typescript { .api }
148
/**
149
* Add a webhook definition (OpenAPI 3.1 feature)
150
* @param webhook - Webhook name/key
151
* @param webhookItem - Path item describing the webhook callback
152
* @returns Builder instance for chaining
153
*/
154
addWebhook(webhook: string, webhookItem: oas31.PathItemObject): OpenApiBuilder;
155
```
156
157
**Usage Example:**
158
159
```typescript
160
builder.addWebhook("petUpdated", {
161
post: {
162
summary: "Pet updated webhook",
163
description: "Called when a pet is updated in the system",
164
requestBody: {
165
description: "Updated pet information",
166
content: {
167
"application/json": {
168
schema: { $ref: "#/components/schemas/Pet" }
169
}
170
}
171
},
172
responses: {
173
"200": {
174
description: "Webhook successfully processed"
175
}
176
}
177
}
178
});
179
```
180
181
### Component Methods
182
183
All OpenAPI 3.0 component methods with OpenAPI 3.1 type support and enhanced components.
184
185
```typescript { .api }
186
/**
187
* Add a schema component (with enhanced OpenAPI 3.1 JSON Schema support)
188
* @param name - Schema name for referencing
189
* @param schema - Schema object or reference
190
* @returns Builder instance for chaining
191
*/
192
addSchema(name: string, schema: oas31.SchemaObject | oas31.ReferenceObject): OpenApiBuilder;
193
194
/**
195
* Add a response component
196
* @param name - Response name for referencing
197
* @param response - Response object or reference
198
* @returns Builder instance for chaining
199
*/
200
addResponse(name: string, response: oas31.ResponseObject | oas31.ReferenceObject): OpenApiBuilder;
201
202
/**
203
* Add a parameter component
204
* @param name - Parameter name for referencing
205
* @param parameter - Parameter object or reference
206
* @returns Builder instance for chaining
207
*/
208
addParameter(name: string, parameter: oas31.ParameterObject | oas31.ReferenceObject): OpenApiBuilder;
209
210
/**
211
* Add an example component
212
* @param name - Example name for referencing
213
* @param example - Example object or reference
214
* @returns Builder instance for chaining
215
*/
216
addExample(name: string, example: oas31.ExampleObject | oas31.ReferenceObject): OpenApiBuilder;
217
218
/**
219
* Add a request body component
220
* @param name - Request body name for referencing
221
* @param reqBody - Request body object or reference
222
* @returns Builder instance for chaining
223
*/
224
addRequestBody(name: string, reqBody: oas31.RequestBodyObject | oas31.ReferenceObject): OpenApiBuilder;
225
226
/**
227
* Add a header component
228
* @param name - Header name for referencing
229
* @param header - Header object or reference
230
* @returns Builder instance for chaining
231
*/
232
addHeader(name: string, header: oas31.HeaderObject | oas31.ReferenceObject): OpenApiBuilder;
233
234
/**
235
* Add a security scheme component
236
* @param name - Security scheme name for referencing
237
* @param secScheme - Security scheme object or reference
238
* @returns Builder instance for chaining
239
*/
240
addSecurityScheme(name: string, secScheme: oas31.SecuritySchemeObject | oas31.ReferenceObject): OpenApiBuilder;
241
242
/**
243
* Add a link component
244
* @param name - Link name for referencing
245
* @param link - Link object or reference
246
* @returns Builder instance for chaining
247
*/
248
addLink(name: string, link: oas31.LinkObject | oas31.ReferenceObject): OpenApiBuilder;
249
250
/**
251
* Add a callback component
252
* @param name - Callback name for referencing
253
* @param callback - Callback object or reference
254
* @returns Builder instance for chaining
255
*/
256
addCallback(name: string, callback: oas31.CallbackObject | oas31.ReferenceObject): OpenApiBuilder;
257
```
258
259
### Server and Tag Methods
260
261
Same as OpenAPI 3.0 with OpenAPI 3.1 type support.
262
263
```typescript { .api }
264
/**
265
* Add a server to the document
266
* @param server - Server object with URL and description
267
* @returns Builder instance for chaining
268
*/
269
addServer(server: oas31.ServerObject): OpenApiBuilder;
270
271
/**
272
* Add a tag to the document
273
* @param tag - Tag object with name and description
274
* @returns Builder instance for chaining
275
*/
276
addTag(tag: oas31.TagObject): OpenApiBuilder;
277
278
/**
279
* Set external documentation
280
* @param extDoc - External documentation object
281
* @returns Builder instance for chaining
282
*/
283
addExternalDocs(extDoc: oas31.ExternalDocumentationObject): OpenApiBuilder;
284
```
285
286
## OpenAPI 3.1 Enhanced Features
287
288
### Enhanced JSON Schema Support
289
290
OpenAPI 3.1 schemas support JSON Schema Draft 2020-12 features:
291
292
```typescript
293
builder.addSchema("EnhancedPet", {
294
type: "object",
295
required: ["name"],
296
properties: {
297
name: { type: "string" },
298
age: {
299
type: "integer",
300
minimum: 0,
301
exclusiveMinimum: 0, // Numeric value in 3.1 (vs boolean in 3.0)
302
maximum: 30,
303
exclusiveMaximum: 30 // Numeric value in 3.1 (vs boolean in 3.0)
304
},
305
type: {
306
const: "pet" // const keyword support
307
},
308
tags: {
309
type: "array",
310
prefixItems: [ // Tuple validation support
311
{ type: "string" },
312
{ type: "string" }
313
],
314
items: false // No additional items allowed
315
},
316
metadata: {
317
type: "string",
318
contentMediaType: "application/json", // Content media type
319
contentEncoding: "base64" // Content encoding
320
}
321
},
322
propertyNames: { // Property name constraints
323
pattern: "^[a-zA-Z_][a-zA-Z0-9_]*$"
324
}
325
});
326
```
327
328
### Enhanced Reference Objects
329
330
OpenAPI 3.1 reference objects support summary and description:
331
332
```typescript
333
builder.addSchema("PetReference", {
334
$ref: "#/components/schemas/Pet",
335
summary: "Pet model reference",
336
description: "Reference to the main Pet schema with additional context"
337
});
338
```
339
340
## Complete OpenAPI 3.1 Example
341
342
```typescript
343
import { oas31, Server } from "openapi3-ts";
344
345
const spec = oas31.OpenApiBuilder.create()
346
.addOpenApiVersion("3.1.0")
347
.addTitle("Advanced Pet Store API")
348
.addVersion("2.0.0")
349
.addDescription("An enhanced API with OpenAPI 3.1 features")
350
.addLicense({
351
name: "MIT",
352
identifier: "MIT", // OpenAPI 3.1 license identifier
353
url: "https://opensource.org/licenses/MIT"
354
})
355
.addServer(new Server("https://api.petstore.com", "Production server"))
356
.addSchema("Pet", {
357
type: "object",
358
required: ["name"],
359
properties: {
360
id: { type: "integer", format: "int64" },
361
name: { type: "string" },
362
status: {
363
type: "string",
364
enum: ["available", "pending", "sold"]
365
},
366
category: {
367
type: "object",
368
properties: {
369
id: { type: "integer" },
370
name: {
371
type: "string",
372
const: "pet-category" // OpenAPI 3.1 const support
373
}
374
}
375
},
376
metadata: {
377
type: "string",
378
contentMediaType: "application/json",
379
contentEncoding: "base64"
380
}
381
},
382
propertyNames: {
383
pattern: "^[a-zA-Z_][a-zA-Z0-9_]*$"
384
}
385
})
386
.addPath("/pets", {
387
get: {
388
summary: "List pets",
389
responses: {
390
"200": {
391
description: "Successful response",
392
content: {
393
"application/json": {
394
schema: {
395
type: "array",
396
items: { $ref: "#/components/schemas/Pet" }
397
}
398
}
399
}
400
}
401
}
402
}
403
})
404
.addWebhook("petStatusChanged", {
405
post: {
406
summary: "Pet status changed webhook",
407
requestBody: {
408
content: {
409
"application/json": {
410
schema: { $ref: "#/components/schemas/Pet" }
411
}
412
}
413
},
414
responses: {
415
"200": {
416
description: "Webhook processed successfully"
417
}
418
}
419
}
420
})
421
.getSpec();
422
423
// Export to different formats with enhanced OpenAPI 3.1 features
424
const json = builder.getSpecAsJson(null, 2);
425
const yaml = builder.getSpecAsYaml();
426
427
// Export YAML with custom formatting for OpenAPI 3.1
428
const customYaml = builder.getSpecAsYaml(
429
null, // replacer function
430
{
431
indent: 4, // 4-space indentation
432
lineWidth: 100, // Wrap long lines
433
flowLevel: 3, // Use flow style for deep nesting
434
sortKeys: true // Sort object keys alphabetically
435
}
436
);
437
438
console.log("OpenAPI 3.1 YAML:", yaml);
439
console.log("Custom formatted:", customYaml);
440
```