0
# DocumentBuilder
1
2
The **DocumentBuilder** class provides a fluent, builder-pattern interface for creating and configuring OpenAPI document specifications. It serves as the foundation for generating comprehensive API documentation by allowing you to set metadata, servers, security schemes, and other OpenAPI document properties.
3
4
## Class Overview
5
6
```typescript { .api }
7
import { DocumentBuilder } from '@nestjs/swagger';
8
9
class DocumentBuilder {
10
constructor();
11
build(): Omit<OpenAPIObject, 'paths'>;
12
}
13
```
14
15
The DocumentBuilder uses the builder pattern, where each method returns `this` to allow method chaining, and finally `build()` returns the configured OpenAPI document specification.
16
17
## Basic Information Methods
18
19
### setTitle { .api }
20
21
```typescript
22
setTitle(title: string): this
23
```
24
25
Sets the title of the API in the OpenAPI document.
26
27
**Usage:**
28
```typescript
29
const config = new DocumentBuilder()
30
.setTitle('E-Commerce API')
31
.build();
32
33
// Results in:
34
// {
35
// "info": {
36
// "title": "E-Commerce API"
37
// }
38
// }
39
```
40
41
### setDescription { .api }
42
43
```typescript
44
setDescription(description: string): this
45
```
46
47
Sets the description of the API, supporting Markdown formatting.
48
49
**Usage:**
50
```typescript
51
const config = new DocumentBuilder()
52
.setTitle('E-Commerce API')
53
.setDescription(`
54
A comprehensive API for managing e-commerce operations.
55
56
## Features
57
- Product management
58
- Order processing
59
- User authentication
60
- Payment processing
61
`)
62
.build();
63
```
64
65
### setVersion { .api }
66
67
```typescript
68
setVersion(version: string): this
69
```
70
71
Sets the version of the API following semantic versioning.
72
73
**Usage:**
74
```typescript
75
const config = new DocumentBuilder()
76
.setTitle('E-Commerce API')
77
.setVersion('2.1.0')
78
.build();
79
```
80
81
### setTermsOfService { .api }
82
83
```typescript
84
setTermsOfService(termsOfService: string): this
85
```
86
87
Sets the URL to the Terms of Service for the API.
88
89
**Usage:**
90
```typescript
91
const config = new DocumentBuilder()
92
.setTitle('E-Commerce API')
93
.setTermsOfService('https://example.com/terms')
94
.build();
95
```
96
97
### setContact { .api }
98
99
```typescript
100
setContact(name: string, url: string, email: string): this
101
```
102
103
Sets contact information for the API including name, URL, and email.
104
105
**Usage:**
106
```typescript
107
const config = new DocumentBuilder()
108
.setTitle('E-Commerce API')
109
.setContact('API Team', 'https://example.com/contact', 'api@example.com')
110
.build();
111
112
// Results in:
113
// {
114
// "info": {
115
// "contact": {
116
// "name": "API Team",
117
// "url": "https://example.com/contact",
118
// "email": "api@example.com"
119
// }
120
// }
121
// }
122
```
123
124
### setLicense { .api }
125
126
```typescript
127
setLicense(name: string, url: string): this
128
```
129
130
Sets license information for the API.
131
132
**Usage:**
133
```typescript
134
const config = new DocumentBuilder()
135
.setTitle('E-Commerce API')
136
.setLicense('MIT', 'https://opensource.org/licenses/MIT')
137
.build();
138
139
// Results in:
140
// {
141
// "info": {
142
// "license": {
143
// "name": "MIT",
144
// "url": "https://opensource.org/licenses/MIT"
145
// }
146
// }
147
// }
148
```
149
150
### setOpenAPIVersion { .api }
151
152
```typescript
153
setOpenAPIVersion(version: string): this
154
```
155
156
Sets the OpenAPI specification version. Must follow the format "x.x.x" (e.g., "3.0.0").
157
158
**Usage:**
159
```typescript
160
const config = new DocumentBuilder()
161
.setTitle('E-Commerce API')
162
.setOpenAPIVersion('3.0.3') // Defaults to 3.0.0 if not specified
163
.build();
164
```
165
166
## Server Configuration
167
168
### addServer { .api }
169
170
```typescript
171
addServer(
172
url: string,
173
description?: string,
174
variables?: Record<string, ServerVariableObject>
175
): this
176
```
177
178
Adds a server to the OpenAPI document. Multiple servers can be added to represent different environments.
179
180
**Type Definitions:**
181
```typescript
182
interface ServerVariableObject {
183
default: string;
184
description?: string;
185
enum?: string[];
186
}
187
```
188
189
**Usage:**
190
```typescript
191
const config = new DocumentBuilder()
192
.setTitle('E-Commerce API')
193
.addServer('https://api.example.com', 'Production server')
194
.addServer('https://staging-api.example.com', 'Staging server')
195
.addServer('http://localhost:3000', 'Development server')
196
.build();
197
198
// Server with variables
199
const configWithVars = new DocumentBuilder()
200
.setTitle('Multi-tenant API')
201
.addServer(
202
'https://{tenant}.api.example.com/{version}',
203
'Tenant-specific API server',
204
{
205
tenant: {
206
default: 'demo',
207
description: 'Tenant identifier',
208
enum: ['demo', 'staging', 'production']
209
},
210
version: {
211
default: 'v1',
212
description: 'API version',
213
enum: ['v1', 'v2']
214
}
215
}
216
)
217
.build();
218
```
219
220
## Documentation and Tagging
221
222
### setExternalDoc { .api }
223
224
```typescript
225
setExternalDoc(description: string, url: string): this
226
```
227
228
Sets external documentation reference for the entire API.
229
230
**Usage:**
231
```typescript
232
const config = new DocumentBuilder()
233
.setTitle('E-Commerce API')
234
.setExternalDoc('API Documentation', 'https://docs.example.com/api')
235
.build();
236
237
// Results in:
238
// {
239
// "externalDocs": {
240
// "description": "API Documentation",
241
// "url": "https://docs.example.com/api"
242
// }
243
// }
244
```
245
246
### addTag { .api }
247
248
```typescript
249
addTag(
250
name: string,
251
description?: string,
252
externalDocs?: ExternalDocumentationObject
253
): this
254
```
255
256
Adds tags for grouping operations in the Swagger UI.
257
258
**Type Definitions:**
259
```typescript
260
interface ExternalDocumentationObject {
261
description?: string;
262
url: string;
263
}
264
```
265
266
**Usage:**
267
```typescript
268
const config = new DocumentBuilder()
269
.setTitle('E-Commerce API')
270
.addTag('Products', 'Product management operations')
271
.addTag('Orders', 'Order processing and tracking')
272
.addTag('Users', 'User authentication and profiles', {
273
description: 'User guide',
274
url: 'https://docs.example.com/users'
275
})
276
.addTag('Payments', 'Payment processing and billing')
277
.build();
278
279
// Results in tags that group related endpoints in Swagger UI
280
```
281
282
## Extensions and Custom Properties
283
284
### addExtension { .api }
285
286
```typescript
287
addExtension(
288
extensionKey: string,
289
extensionProperties: any,
290
location?: ExtensionLocation
291
): this
292
```
293
294
Adds custom OpenAPI extensions (x-* properties) to the document.
295
296
**Type Definitions:**
297
```typescript
298
type ExtensionLocation = 'root' | 'info' | 'components';
299
```
300
301
**Usage:**
302
```typescript
303
const config = new DocumentBuilder()
304
.setTitle('E-Commerce API')
305
.addExtension('x-api-id', 'ecommerce-api-v2')
306
.addExtension('x-logo', {
307
url: 'https://example.com/logo.png',
308
altText: 'Company Logo'
309
})
310
.addExtension('x-code-samples', {
311
languages: ['javascript', 'python', 'curl']
312
}, 'info') // Add to info object instead of root
313
.build();
314
315
// Extensions must start with 'x-' prefix or an error will be thrown
316
```
317
318
## Security Configuration
319
320
### addSecurity { .api }
321
322
```typescript
323
addSecurity(name: string, options: SecuritySchemeObject): this
324
```
325
326
Adds a security scheme definition to the OpenAPI document components.
327
328
**Type Definitions:**
329
```typescript
330
interface SecuritySchemeObject {
331
type: 'apiKey' | 'http' | 'oauth2' | 'openIdConnect';
332
description?: string;
333
name?: string; // For apiKey
334
in?: 'query' | 'header' | 'cookie'; // For apiKey
335
scheme?: string; // For http (e.g., 'basic', 'bearer')
336
bearerFormat?: string; // For http bearer
337
flows?: OAuthFlowsObject; // For oauth2
338
openIdConnectUrl?: string; // For openIdConnect
339
}
340
```
341
342
**Usage:**
343
```typescript
344
const config = new DocumentBuilder()
345
.setTitle('E-Commerce API')
346
.addSecurity('custom-api-key', {
347
type: 'apiKey',
348
in: 'header',
349
name: 'X-API-Key',
350
description: 'Custom API key authentication'
351
})
352
.addSecurity('jwt-auth', {
353
type: 'http',
354
scheme: 'bearer',
355
bearerFormat: 'JWT',
356
description: 'JWT token authentication'
357
})
358
.build();
359
```
360
361
### addBearerAuth { .api }
362
363
```typescript
364
addBearerAuth(
365
options?: SecuritySchemeObject,
366
name?: string
367
): this
368
```
369
370
Adds JWT Bearer token authentication. Defaults to name 'bearer'.
371
372
**Usage:**
373
```typescript
374
const config = new DocumentBuilder()
375
.setTitle('E-Commerce API')
376
.addBearerAuth() // Default configuration
377
.build();
378
379
// Custom Bearer auth
380
const customConfig = new DocumentBuilder()
381
.setTitle('E-Commerce API')
382
.addBearerAuth({
383
type: 'http',
384
scheme: 'bearer',
385
bearerFormat: 'JWT',
386
description: 'JWT authorization token'
387
}, 'jwt-token')
388
.build();
389
```
390
391
### addOAuth2 { .api }
392
393
```typescript
394
addOAuth2(
395
options?: SecuritySchemeObject,
396
name?: string
397
): this
398
```
399
400
Adds OAuth2 authentication configuration. Defaults to name 'oauth2'.
401
402
**Usage:**
403
```typescript
404
const config = new DocumentBuilder()
405
.setTitle('E-Commerce API')
406
.addOAuth2({
407
type: 'oauth2',
408
flows: {
409
authorizationCode: {
410
authorizationUrl: 'https://auth.example.com/oauth/authorize',
411
tokenUrl: 'https://auth.example.com/oauth/token',
412
scopes: {
413
'read': 'Read access',
414
'write': 'Write access',
415
'admin': 'Administrative access'
416
}
417
},
418
clientCredentials: {
419
tokenUrl: 'https://auth.example.com/oauth/token',
420
scopes: {
421
'service': 'Service-to-service access'
422
}
423
}
424
}
425
})
426
.build();
427
```
428
429
### addApiKey { .api }
430
431
```typescript
432
addApiKey(
433
options?: SecuritySchemeObject,
434
name?: string
435
): this
436
```
437
438
Adds API key authentication. Defaults to header-based API key with name 'api_key'.
439
440
**Usage:**
441
```typescript
442
const config = new DocumentBuilder()
443
.setTitle('E-Commerce API')
444
.addApiKey() // Default: header-based with name 'api_key'
445
.build();
446
447
// Custom API key configuration
448
const customConfig = new DocumentBuilder()
449
.setTitle('E-Commerce API')
450
.addApiKey({
451
type: 'apiKey',
452
in: 'query',
453
name: 'access_token',
454
description: 'API access token'
455
}, 'query-token')
456
.build();
457
```
458
459
### addBasicAuth { .api }
460
461
```typescript
462
addBasicAuth(
463
options?: SecuritySchemeObject,
464
name?: string
465
): this
466
```
467
468
Adds HTTP Basic authentication. Defaults to name 'basic'.
469
470
**Usage:**
471
```typescript
472
const config = new DocumentBuilder()
473
.setTitle('E-Commerce API')
474
.addBasicAuth() // Default Basic auth
475
.build();
476
477
// Custom Basic auth
478
const customConfig = new DocumentBuilder()
479
.setTitle('E-Commerce API')
480
.addBasicAuth({
481
type: 'http',
482
scheme: 'basic',
483
description: 'Username and password authentication'
484
}, 'http-basic')
485
.build();
486
```
487
488
### addCookieAuth { .api }
489
490
```typescript
491
addCookieAuth(
492
cookieName?: string,
493
options?: SecuritySchemeObject,
494
securityName?: string
495
): this
496
```
497
498
Adds cookie-based authentication. Defaults to cookie name 'connect.sid' and security name 'cookie'.
499
500
**Usage:**
501
```typescript
502
const config = new DocumentBuilder()
503
.setTitle('E-Commerce API')
504
.addCookieAuth() // Default: 'connect.sid' cookie
505
.build();
506
507
// Custom cookie auth
508
const customConfig = new DocumentBuilder()
509
.setTitle('E-Commerce API')
510
.addCookieAuth('sessionId', {
511
type: 'apiKey',
512
in: 'cookie',
513
description: 'Session cookie authentication'
514
}, 'session-auth')
515
.build();
516
```
517
518
### addSecurityRequirements { .api }
519
520
```typescript
521
addSecurityRequirements(
522
name: string | SecurityRequirementObject,
523
requirements?: string[]
524
): this
525
```
526
527
Adds global security requirements that apply to all operations unless overridden.
528
529
**Type Definitions:**
530
```typescript
531
type SecurityRequirementObject = Record<string, string[]>;
532
```
533
534
**Usage:**
535
```typescript
536
const config = new DocumentBuilder()
537
.setTitle('E-Commerce API')
538
.addBearerAuth()
539
.addApiKey()
540
.addSecurityRequirements('bearer') // All endpoints require Bearer token
541
.addSecurityRequirements('api_key') // Alternative: API key
542
.build();
543
544
// OAuth2 with specific scopes
545
const oauthConfig = new DocumentBuilder()
546
.setTitle('E-Commerce API')
547
.addOAuth2()
548
.addSecurityRequirements('oauth2', ['read', 'write']) // Require specific scopes
549
.build();
550
551
// Multiple requirements (both must be satisfied)
552
const multiConfig = new DocumentBuilder()
553
.setTitle('E-Commerce API')
554
.addBearerAuth()
555
.addApiKey()
556
.addSecurityRequirements({ 'bearer': [], 'api_key': [] })
557
.build();
558
```
559
560
## Global Configuration
561
562
### addGlobalResponse { .api }
563
564
```typescript
565
addGlobalResponse(...responses: ApiResponseOptions[]): this
566
```
567
568
Adds global response definitions that apply to all operations.
569
570
**Type Definitions:**
571
```typescript
572
interface ApiResponseOptions {
573
status?: number | 'default';
574
description?: string;
575
type?: any;
576
isArray?: boolean;
577
schema?: SchemaObject & Partial<ReferenceObject>;
578
}
579
```
580
581
**Usage:**
582
```typescript
583
const config = new DocumentBuilder()
584
.setTitle('E-Commerce API')
585
.addGlobalResponse({
586
status: 401,
587
description: 'Unauthorized - Invalid or missing authentication'
588
})
589
.addGlobalResponse({
590
status: 403,
591
description: 'Forbidden - Insufficient permissions'
592
})
593
.addGlobalResponse({
594
status: 500,
595
description: 'Internal server error',
596
schema: {
597
type: 'object',
598
properties: {
599
error: { type: 'string' },
600
message: { type: 'string' },
601
timestamp: { type: 'string', format: 'date-time' }
602
}
603
}
604
})
605
.build();
606
```
607
608
### addGlobalParameters { .api }
609
610
```typescript
611
addGlobalParameters(
612
...parameters: Omit<ParameterObject, 'example' | 'examples'>[]
613
): this
614
```
615
616
Adds global parameters that apply to all operations.
617
618
**Type Definitions:**
619
```typescript
620
interface ParameterObject {
621
name: string;
622
in: 'query' | 'header' | 'path' | 'cookie';
623
description?: string;
624
required?: boolean;
625
deprecated?: boolean;
626
allowEmptyValue?: boolean;
627
schema?: SchemaObject;
628
style?: ParameterStyle;
629
explode?: boolean;
630
allowReserved?: boolean;
631
}
632
```
633
634
**Usage:**
635
```typescript
636
const config = new DocumentBuilder()
637
.setTitle('E-Commerce API')
638
.addGlobalParameters(
639
{
640
name: 'X-Request-ID',
641
in: 'header',
642
description: 'Unique request identifier for tracing',
643
required: false,
644
schema: {
645
type: 'string',
646
format: 'uuid'
647
}
648
},
649
{
650
name: 'Accept-Language',
651
in: 'header',
652
description: 'Preferred language for response',
653
required: false,
654
schema: {
655
type: 'string',
656
enum: ['en-US', 'es-ES', 'fr-FR'],
657
default: 'en-US'
658
}
659
}
660
)
661
.build();
662
```
663
664
## Building the Document
665
666
### build { .api }
667
668
```typescript
669
build(): Omit<OpenAPIObject, 'paths'>
670
```
671
672
Finalizes and returns the configured OpenAPI document specification. The `paths` property is omitted as it will be generated from your NestJS controllers and decorators.
673
674
**Usage:**
675
```typescript
676
const config = new DocumentBuilder()
677
.setTitle('E-Commerce API')
678
.setDescription('Comprehensive e-commerce platform API')
679
.setVersion('2.0.0')
680
.addServer('https://api.example.com', 'Production')
681
.addServer('http://localhost:3000', 'Development')
682
.addBearerAuth()
683
.addTag('Products', 'Product catalog operations')
684
.addTag('Orders', 'Order management')
685
.build();
686
687
// Use with SwaggerModule
688
const document = SwaggerModule.createDocument(app, config);
689
SwaggerModule.setup('api', app, document);
690
```
691
692
## Complete Example
693
694
### Comprehensive API Configuration
695
696
```typescript
697
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
698
import { NestFactory } from '@nestjs/core';
699
import { AppModule } from './app.module';
700
701
async function bootstrap() {
702
const app = await NestFactory.create(AppModule);
703
704
const config = new DocumentBuilder()
705
// Basic information
706
.setTitle('E-Commerce Platform API')
707
.setDescription(`
708
A comprehensive RESTful API for e-commerce operations.
709
710
## Authentication
711
This API uses JWT Bearer tokens for authentication. Include your token in the Authorization header.
712
713
## Rate Limiting
714
API calls are limited to 1000 requests per hour per API key.
715
716
## Support
717
For API support, contact our developer team.
718
`)
719
.setVersion('2.1.0')
720
.setTermsOfService('https://example.com/terms')
721
.setContact('API Team', 'https://example.com/contact', 'api-support@example.com')
722
.setLicense('MIT', 'https://opensource.org/licenses/MIT')
723
724
// Servers
725
.addServer('https://api.example.com', 'Production server')
726
.addServer('https://staging-api.example.com', 'Staging server')
727
.addServer('http://localhost:3000', 'Development server')
728
729
// External documentation
730
.setExternalDoc('Complete API Guide', 'https://docs.example.com')
731
732
// Tags for organization
733
.addTag('Authentication', 'User authentication and authorization')
734
.addTag('Products', 'Product catalog and inventory management')
735
.addTag('Orders', 'Order processing and fulfillment')
736
.addTag('Users', 'User profile and account management')
737
.addTag('Payments', 'Payment processing and billing')
738
.addTag('Admin', 'Administrative operations', {
739
description: 'Admin operations guide',
740
url: 'https://docs.example.com/admin'
741
})
742
743
// Security schemes
744
.addBearerAuth({
745
type: 'http',
746
scheme: 'bearer',
747
bearerFormat: 'JWT',
748
description: 'JWT authorization token'
749
}, 'jwt-auth')
750
.addApiKey({
751
type: 'apiKey',
752
in: 'header',
753
name: 'X-API-Key',
754
description: 'API key for service-to-service communication'
755
}, 'api-key')
756
.addOAuth2({
757
type: 'oauth2',
758
flows: {
759
authorizationCode: {
760
authorizationUrl: 'https://auth.example.com/oauth/authorize',
761
tokenUrl: 'https://auth.example.com/oauth/token',
762
scopes: {
763
'products:read': 'Read product information',
764
'products:write': 'Create and modify products',
765
'orders:read': 'Read order information',
766
'orders:write': 'Create and modify orders',
767
'admin': 'Full administrative access'
768
}
769
}
770
}
771
})
772
773
// Global security requirements (JWT required by default)
774
.addSecurityRequirements('jwt-auth')
775
776
// Global responses
777
.addGlobalResponse({
778
status: 401,
779
description: 'Unauthorized - Authentication required'
780
})
781
.addGlobalResponse({
782
status: 403,
783
description: 'Forbidden - Insufficient permissions'
784
})
785
.addGlobalResponse({
786
status: 429,
787
description: 'Too Many Requests - Rate limit exceeded'
788
})
789
.addGlobalResponse({
790
status: 500,
791
description: 'Internal Server Error'
792
})
793
794
// Global parameters
795
.addGlobalParameters(
796
{
797
name: 'X-Request-ID',
798
in: 'header',
799
description: 'Unique identifier for request tracing',
800
required: false,
801
schema: { type: 'string', format: 'uuid' }
802
},
803
{
804
name: 'Accept-Language',
805
in: 'header',
806
description: 'Preferred response language',
807
required: false,
808
schema: {
809
type: 'string',
810
enum: ['en-US', 'es-ES', 'fr-FR'],
811
default: 'en-US'
812
}
813
}
814
)
815
816
// Custom extensions
817
.addExtension('x-api-id', 'ecommerce-platform')
818
.addExtension('x-logo', {
819
url: 'https://example.com/logo.png',
820
altText: 'E-Commerce Platform'
821
})
822
823
.build();
824
825
const document = SwaggerModule.createDocument(app, config);
826
SwaggerModule.setup('api-docs', app, document, {
827
swaggerOptions: {
828
persistAuthorization: true,
829
displayRequestDuration: true
830
}
831
});
832
833
await app.listen(3000);
834
}
835
836
bootstrap();
837
```
838
839
This comprehensive DocumentBuilder configuration provides a professional, well-documented API specification that includes all necessary metadata, security schemes, and organizational structure for a production e-commerce platform.