0
# OpenAPI 3.0 Builder
1
2
Fluent DSL for creating OpenAPI 3.0 specification documents with complete type safety and chainable operations.
3
4
## Capabilities
5
6
### OpenApiBuilder Class
7
8
Main builder class for constructing OpenAPI 3.0 documents through a fluent interface.
9
10
```typescript { .api }
11
/**
12
* Internal DSL for building an OpenAPI 3.0.x contract using a fluent interface
13
*/
14
class OpenApiBuilder {
15
rootDoc: oas30.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?: oas30.OpenAPIObject): OpenApiBuilder;
23
24
/**
25
* Constructor for OpenApiBuilder
26
* @param doc - Optional initial OpenAPI document, defaults to minimal structure
27
*/
28
constructor(doc?: oas30.OpenAPIObject);
29
}
30
```
31
32
### Document Access Methods
33
34
Methods for retrieving and serializing the OpenAPI document.
35
36
```typescript { .api }
37
/**
38
* Get the current OpenAPI document
39
* @returns The OpenAPI document object
40
*/
41
getSpec(): oas30.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
Methods for setting basic document information. All methods return `OpenApiBuilder` for chaining.
69
70
```typescript { .api }
71
/**
72
* Set the OpenAPI version
73
* @param openApiVersion - OpenAPI version string (e.g., "3.0.3")
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: oas30.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: oas30.ContactObject): OpenApiBuilder;
92
93
/**
94
* Set license information
95
* @param license - License object with name and optional url
96
* @returns Builder instance for chaining
97
*/
98
addLicense(license: oas30.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
Methods for defining API paths and operations.
132
133
```typescript { .api }
134
/**
135
* Add or merge a path item
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: oas30.PathItemObject): OpenApiBuilder;
141
```
142
143
**Usage Example:**
144
145
```typescript
146
builder.addPath("/pets", {
147
get: {
148
summary: "List all pets",
149
responses: {
150
"200": {
151
description: "A list of pets",
152
content: {
153
"application/json": {
154
schema: {
155
type: "array",
156
items: { $ref: "#/components/schemas/Pet" }
157
}
158
}
159
}
160
}
161
}
162
},
163
post: {
164
summary: "Create a pet",
165
requestBody: {
166
required: true,
167
content: {
168
"application/json": {
169
schema: { $ref: "#/components/schemas/Pet" }
170
}
171
}
172
},
173
responses: {
174
"201": {
175
description: "Pet created successfully",
176
content: {
177
"application/json": {
178
schema: { $ref: "#/components/schemas/Pet" }
179
}
180
}
181
}
182
}
183
}
184
});
185
```
186
187
### Component Methods
188
189
Methods for adding reusable components. All methods return `OpenApiBuilder` for chaining.
190
191
```typescript { .api }
192
/**
193
* Add a schema component
194
* @param name - Schema name for referencing
195
* @param schema - Schema object or reference
196
* @returns Builder instance for chaining
197
*/
198
addSchema(name: string, schema: oas30.SchemaObject | oas30.ReferenceObject): OpenApiBuilder;
199
200
/**
201
* Add a response component
202
* @param name - Response name for referencing
203
* @param response - Response object or reference
204
* @returns Builder instance for chaining
205
*/
206
addResponse(name: string, response: oas30.ResponseObject | oas30.ReferenceObject): OpenApiBuilder;
207
208
/**
209
* Add a parameter component
210
* @param name - Parameter name for referencing
211
* @param parameter - Parameter object or reference
212
* @returns Builder instance for chaining
213
*/
214
addParameter(name: string, parameter: oas30.ParameterObject | oas30.ReferenceObject): OpenApiBuilder;
215
216
/**
217
* Add an example component
218
* @param name - Example name for referencing
219
* @param example - Example object or reference
220
* @returns Builder instance for chaining
221
*/
222
addExample(name: string, example: oas30.ExampleObject | oas30.ReferenceObject): OpenApiBuilder;
223
224
/**
225
* Add a request body component
226
* @param name - Request body name for referencing
227
* @param reqBody - Request body object or reference
228
* @returns Builder instance for chaining
229
*/
230
addRequestBody(name: string, reqBody: oas30.RequestBodyObject | oas30.ReferenceObject): OpenApiBuilder;
231
232
/**
233
* Add a header component
234
* @param name - Header name for referencing
235
* @param header - Header object or reference
236
* @returns Builder instance for chaining
237
*/
238
addHeader(name: string, header: oas30.HeaderObject | oas30.ReferenceObject): OpenApiBuilder;
239
240
/**
241
* Add a security scheme component
242
* @param name - Security scheme name for referencing
243
* @param secScheme - Security scheme object or reference
244
* @returns Builder instance for chaining
245
*/
246
addSecurityScheme(name: string, secScheme: oas30.SecuritySchemeObject | oas30.ReferenceObject): OpenApiBuilder;
247
248
/**
249
* Add a link component
250
* @param name - Link name for referencing
251
* @param link - Link object or reference
252
* @returns Builder instance for chaining
253
*/
254
addLink(name: string, link: oas30.LinkObject | oas30.ReferenceObject): OpenApiBuilder;
255
256
/**
257
* Add a callback component
258
* @param name - Callback name for referencing
259
* @param callback - Callback object or reference
260
* @returns Builder instance for chaining
261
*/
262
addCallback(name: string, callback: oas30.CallbackObject | oas30.ReferenceObject): OpenApiBuilder;
263
```
264
265
**Usage Example:**
266
267
```typescript
268
builder
269
.addSchema("Pet", {
270
type: "object",
271
required: ["id", "name"],
272
properties: {
273
id: { type: "integer", format: "int64" },
274
name: { type: "string" },
275
tag: { type: "string" }
276
}
277
})
278
.addResponse("NotFound", {
279
description: "The specified resource was not found",
280
content: {
281
"application/json": {
282
schema: {
283
type: "object",
284
properties: {
285
error: { type: "string" },
286
code: { type: "integer" }
287
}
288
}
289
}
290
}
291
});
292
```
293
294
### Server and Tag Methods
295
296
Methods for adding servers and tags.
297
298
```typescript { .api }
299
/**
300
* Add a server to the document
301
* @param server - Server object with URL and description
302
* @returns Builder instance for chaining
303
*/
304
addServer(server: oas30.ServerObject): OpenApiBuilder;
305
306
/**
307
* Add a tag to the document
308
* @param tag - Tag object with name and description
309
* @returns Builder instance for chaining
310
*/
311
addTag(tag: oas30.TagObject): OpenApiBuilder;
312
313
/**
314
* Set external documentation
315
* @param extDoc - External documentation object
316
* @returns Builder instance for chaining
317
*/
318
addExternalDocs(extDoc: oas30.ExternalDocumentationObject): OpenApiBuilder;
319
```
320
321
**Usage Example:**
322
323
```typescript
324
import { Server, ServerVariable } from "openapi3-ts";
325
326
const server = new Server("https://api.example.com/v1", "Production server");
327
server.addVariable("version", new ServerVariable("v1", ["v1", "v2"], "API version"));
328
329
builder
330
.addServer(server)
331
.addTag({
332
name: "pets",
333
description: "Operations about pets"
334
})
335
.addExternalDocs({
336
description: "Find more info here",
337
url: "https://example.com/docs"
338
});
339
```
340
341
## Complete Example
342
343
```typescript
344
import { oas30, Server, ServerVariable } from "openapi3-ts";
345
346
const spec = oas30.OpenApiBuilder.create()
347
.addOpenApiVersion("3.0.3")
348
.addTitle("Pet Store API")
349
.addVersion("1.0.0")
350
.addDescription("A sample API that uses a petstore as an example")
351
.addContact({
352
name: "Swagger API Team",
353
email: "apiteam@swagger.io",
354
url: "http://swagger.io"
355
})
356
.addLicense({
357
name: "MIT",
358
url: "https://opensource.org/licenses/MIT"
359
})
360
.addServer(new Server("https://petstore.swagger.io/v2", "Swagger Petstore"))
361
.addTag({
362
name: "pet",
363
description: "Everything about your Pets"
364
})
365
.addSchema("Pet", {
366
type: "object",
367
required: ["name", "photoUrls"],
368
properties: {
369
id: { type: "integer", format: "int64" },
370
name: { type: "string", example: "doggie" },
371
photoUrls: {
372
type: "array",
373
items: { type: "string" }
374
},
375
status: {
376
type: "string",
377
enum: ["available", "pending", "sold"]
378
}
379
}
380
})
381
.addPath("/pet", {
382
post: {
383
tags: ["pet"],
384
summary: "Add a new pet to the store",
385
requestBody: {
386
description: "Pet object that needs to be added to the store",
387
required: true,
388
content: {
389
"application/json": {
390
schema: { $ref: "#/components/schemas/Pet" }
391
}
392
}
393
},
394
responses: {
395
"405": {
396
description: "Invalid input"
397
}
398
}
399
}
400
})
401
.getSpec();
402
403
// Export to different formats
404
const json = oas30.OpenApiBuilder.create(spec).getSpecAsJson(null, 2);
405
const yaml = oas30.OpenApiBuilder.create(spec).getSpecAsYaml();
406
407
// Export YAML with custom options
408
const customYaml = oas30.OpenApiBuilder.create(spec).getSpecAsYaml(
409
null, // replacer function (can filter/transform values)
410
{
411
indent: 4, // Use 4-space indentation instead of default 2
412
lineWidth: 120, // Longer line width
413
flowLevel: 2 // Use flow style for deeply nested objects
414
}
415
);
416
417
console.log("Default YAML:", yaml);
418
console.log("Custom formatted YAML:", customYaml);
419
```