0
# Interfaces
1
2
The **@nestjs/swagger** interfaces provide comprehensive TypeScript definitions for the complete OpenAPI 3.0 specification, configuration options, and utility types. These interfaces ensure type safety when working with OpenAPI documents and provide full intellisense support for all OpenAPI constructs.
3
4
## Utility Functions
5
6
### getSchemaPath { .api }
7
8
```typescript
9
import { getSchemaPath } from '@nestjs/swagger';
10
11
function getSchemaPath(model: string | Function): string
12
```
13
14
Returns the JSON Schema reference path for a given model class or schema name.
15
16
**Parameters:**
17
- `model`: Either a class constructor or a string representing the schema name
18
19
**Returns:** JSON Schema reference path in the format `#/components/schemas/{ModelName}`
20
21
**Usage:**
22
```typescript
23
import { getSchemaPath } from '@nestjs/swagger';
24
25
class User {
26
id: string;
27
name: string;
28
}
29
30
// Get reference path for a class
31
const userSchemaPath = getSchemaPath(User);
32
// Returns: "#/components/schemas/User"
33
34
// Get reference path for a string
35
const customSchemaPath = getSchemaPath('CustomSchema');
36
// Returns: "#/components/schemas/CustomSchema"
37
38
// Use in complex schema definitions
39
@ApiResponse({
40
status: 200,
41
schema: {
42
type: 'object',
43
properties: {
44
user: { $ref: getSchemaPath(User) },
45
permissions: {
46
type: 'array',
47
items: { $ref: getSchemaPath('Permission') }
48
}
49
}
50
}
51
})
52
getUserWithPermissions() {}
53
```
54
55
### refs { .api }
56
57
```typescript
58
import { refs } from '@nestjs/swagger';
59
60
function refs(...models: Function[]): Array<{ $ref: string }>
61
```
62
63
Creates an array of schema references for multiple model classes.
64
65
**Parameters:**
66
- `...models`: Variable number of class constructors
67
68
**Returns:** Array of reference objects with `$ref` properties
69
70
**Usage:**
71
```typescript
72
import { refs } from '@nestjs/swagger';
73
74
class User {}
75
class Product {}
76
class Order {}
77
78
// Create multiple schema references
79
const schemaRefs = refs(User, Product, Order);
80
// Returns: [
81
// { $ref: "#/components/schemas/User" },
82
// { $ref: "#/components/schemas/Product" },
83
// { $ref: "#/components/schemas/Order" }
84
// ]
85
86
// Use in oneOf/anyOf schemas
87
@ApiResponse({
88
status: 200,
89
schema: {
90
oneOf: refs(User, Product, Order)
91
}
92
})
93
getEntity() {}
94
```
95
96
## Core OpenAPI Interfaces
97
98
### OpenAPIObject { .api }
99
100
```typescript
101
interface OpenAPIObject {
102
openapi: string;
103
info: InfoObject;
104
servers?: ServerObject[];
105
paths: PathsObject;
106
components?: ComponentsObject;
107
security?: SecurityRequirementObject[];
108
tags?: TagObject[];
109
externalDocs?: ExternalDocumentationObject;
110
}
111
```
112
113
The root OpenAPI specification object containing all API documentation metadata.
114
115
**Properties:**
116
- `openapi`: OpenAPI specification version (e.g., "3.0.0")
117
- `info`: Required metadata about the API
118
- `servers`: Array of server objects representing API base URLs
119
- `paths`: Available paths and operations for the API
120
- `components`: Reusable components (schemas, responses, parameters, etc.)
121
- `security`: Global security requirements
122
- `tags`: List of tags for operation grouping
123
- `externalDocs`: External documentation reference
124
125
**Usage:**
126
```typescript
127
const openApiDoc: OpenAPIObject = {
128
openapi: '3.0.0',
129
info: {
130
title: 'My API',
131
version: '1.0.0'
132
},
133
paths: {
134
'/users': {
135
get: {
136
summary: 'Get users',
137
responses: {
138
'200': {
139
description: 'Successful response'
140
}
141
}
142
}
143
}
144
}
145
};
146
```
147
148
### InfoObject { .api }
149
150
```typescript
151
interface InfoObject {
152
title: string;
153
description?: string;
154
termsOfService?: string;
155
contact?: ContactObject;
156
license?: LicenseObject;
157
version: string;
158
}
159
```
160
161
Metadata about the API including title, description, version, and legal information.
162
163
**Usage:**
164
```typescript
165
const info: InfoObject = {
166
title: 'E-Commerce API',
167
description: 'Comprehensive e-commerce platform REST API',
168
version: '2.1.0',
169
termsOfService: 'https://example.com/terms',
170
contact: {
171
name: 'API Team',
172
email: 'api@example.com',
173
url: 'https://example.com/contact'
174
},
175
license: {
176
name: 'MIT',
177
url: 'https://opensource.org/licenses/MIT'
178
}
179
};
180
```
181
182
### ContactObject { .api }
183
184
```typescript
185
interface ContactObject {
186
name?: string;
187
url?: string;
188
email?: string;
189
}
190
```
191
192
Contact information for the API.
193
194
### LicenseObject { .api }
195
196
```typescript
197
interface LicenseObject {
198
name: string;
199
url?: string;
200
}
201
```
202
203
License information for the API.
204
205
## Server Configuration
206
207
### ServerObject { .api }
208
209
```typescript
210
interface ServerObject {
211
url: string;
212
description?: string;
213
variables?: Record<string, ServerVariableObject>;
214
}
215
```
216
217
Represents a server where the API is available.
218
219
**Usage:**
220
```typescript
221
const servers: ServerObject[] = [
222
{
223
url: 'https://{tenant}.api.example.com/{version}',
224
description: 'Production server',
225
variables: {
226
tenant: {
227
default: 'main',
228
enum: ['main', 'staging'],
229
description: 'Tenant identifier'
230
},
231
version: {
232
default: 'v1',
233
enum: ['v1', 'v2'],
234
description: 'API version'
235
}
236
}
237
}
238
];
239
```
240
241
### ServerVariableObject { .api }
242
243
```typescript
244
interface ServerVariableObject {
245
enum?: string[] | boolean[] | number[];
246
default: string | boolean | number;
247
description?: string;
248
}
249
```
250
251
Represents a server URL template variable.
252
253
## Components and Reusability
254
255
### ComponentsObject { .api }
256
257
```typescript
258
interface ComponentsObject {
259
schemas?: Record<string, SchemaObject | ReferenceObject>;
260
responses?: Record<string, ResponseObject | ReferenceObject>;
261
parameters?: Record<string, ParameterObject | ReferenceObject>;
262
examples?: Record<string, ExampleObject | ReferenceObject>;
263
requestBodies?: Record<string, RequestBodyObject | ReferenceObject>;
264
headers?: Record<string, HeaderObject | ReferenceObject>;
265
securitySchemes?: Record<string, SecuritySchemeObject | ReferenceObject>;
266
links?: Record<string, LinkObject | ReferenceObject>;
267
callbacks?: Record<string, CallbackObject | ReferenceObject>;
268
}
269
```
270
271
Container for reusable components in the OpenAPI specification.
272
273
**Usage:**
274
```typescript
275
const components: ComponentsObject = {
276
schemas: {
277
User: {
278
type: 'object',
279
properties: {
280
id: { type: 'string' },
281
name: { type: 'string' }
282
}
283
}
284
},
285
responses: {
286
NotFound: {
287
description: 'Resource not found'
288
}
289
},
290
securitySchemes: {
291
bearerAuth: {
292
type: 'http',
293
scheme: 'bearer',
294
bearerFormat: 'JWT'
295
}
296
}
297
};
298
```
299
300
## Paths and Operations
301
302
### PathsObject { .api }
303
304
```typescript
305
type PathsObject = Record<string, PathItemObject>
306
```
307
308
Contains all available paths and operations for the API.
309
310
### PathItemObject { .api }
311
312
```typescript
313
interface PathItemObject {
314
$ref?: string;
315
summary?: string;
316
description?: string;
317
get?: OperationObject;
318
put?: OperationObject;
319
post?: OperationObject;
320
delete?: OperationObject;
321
options?: OperationObject;
322
head?: OperationObject;
323
patch?: OperationObject;
324
trace?: OperationObject;
325
servers?: ServerObject[];
326
parameters?: (ParameterObject | ReferenceObject)[];
327
}
328
```
329
330
Describes operations available on a single path.
331
332
### OperationObject { .api }
333
334
```typescript
335
interface OperationObject {
336
tags?: string[];
337
summary?: string;
338
description?: string;
339
externalDocs?: ExternalDocumentationObject;
340
operationId?: string;
341
parameters?: (ParameterObject | ReferenceObject)[];
342
requestBody?: RequestBodyObject | ReferenceObject;
343
responses: ResponsesObject;
344
callbacks?: CallbacksObject;
345
deprecated?: boolean;
346
security?: SecurityRequirementObject[];
347
servers?: ServerObject[];
348
}
349
```
350
351
Describes a single API operation on a path.
352
353
**Usage:**
354
```typescript
355
const operation: OperationObject = {
356
tags: ['Users'],
357
summary: 'Create a new user',
358
description: 'Creates a new user account with the provided information',
359
operationId: 'createUser',
360
requestBody: {
361
required: true,
362
content: {
363
'application/json': {
364
schema: { $ref: '#/components/schemas/CreateUserRequest' }
365
}
366
}
367
},
368
responses: {
369
'201': {
370
description: 'User created successfully',
371
content: {
372
'application/json': {
373
schema: { $ref: '#/components/schemas/User' }
374
}
375
}
376
},
377
'400': {
378
description: 'Invalid request data'
379
}
380
},
381
security: [
382
{ bearerAuth: [] }
383
]
384
};
385
```
386
387
## Parameters
388
389
### ParameterObject { .api }
390
391
```typescript
392
interface ParameterObject extends BaseParameterObject {
393
name: string;
394
in: ParameterLocation;
395
}
396
397
interface BaseParameterObject {
398
description?: string;
399
required?: boolean;
400
deprecated?: boolean;
401
allowEmptyValue?: boolean;
402
style?: ParameterStyle;
403
explode?: boolean;
404
allowReserved?: boolean;
405
schema?: SchemaObject | ReferenceObject;
406
examples?: Record<string, ExampleObject | ReferenceObject>;
407
example?: any;
408
content?: ContentObject;
409
}
410
411
type ParameterLocation = 'query' | 'header' | 'path' | 'cookie';
412
type ParameterStyle = 'matrix' | 'label' | 'form' | 'simple' | 'spaceDelimited' | 'pipeDelimited' | 'deepObject';
413
```
414
415
Describes a single operation parameter.
416
417
**Usage:**
418
```typescript
419
const parameters: ParameterObject[] = [
420
{
421
name: 'id',
422
in: 'path',
423
required: true,
424
description: 'User identifier',
425
schema: {
426
type: 'string',
427
format: 'uuid'
428
}
429
},
430
{
431
name: 'limit',
432
in: 'query',
433
required: false,
434
description: 'Maximum number of results',
435
schema: {
436
type: 'integer',
437
minimum: 1,
438
maximum: 100,
439
default: 10
440
}
441
}
442
];
443
```
444
445
## Request and Response Bodies
446
447
### RequestBodyObject { .api }
448
449
```typescript
450
interface RequestBodyObject {
451
description?: string;
452
content: ContentObject;
453
required?: boolean;
454
}
455
```
456
457
Describes request body content for an operation.
458
459
### ResponseObject { .api }
460
461
```typescript
462
interface ResponseObject {
463
description: string;
464
headers?: HeadersObject;
465
content?: ContentObject;
466
links?: LinksObject;
467
}
468
469
interface ResponsesObject extends Record<string, ResponseObject | ReferenceObject | undefined> {
470
default?: ResponseObject | ReferenceObject;
471
}
472
```
473
474
Describes a single response from an API operation.
475
476
### ContentObject { .api }
477
478
```typescript
479
type ContentObject = Record<string, MediaTypeObject>
480
481
interface MediaTypeObject {
482
schema?: SchemaObject | ReferenceObject;
483
examples?: ExamplesObject;
484
example?: any;
485
encoding?: EncodingObject;
486
}
487
```
488
489
Describes the content of a request or response body.
490
491
**Usage:**
492
```typescript
493
const responseContent: ContentObject = {
494
'application/json': {
495
schema: {
496
type: 'object',
497
properties: {
498
users: {
499
type: 'array',
500
items: { $ref: '#/components/schemas/User' }
501
},
502
total: {
503
type: 'integer'
504
}
505
}
506
},
507
examples: {
508
userList: {
509
summary: 'List of users',
510
value: {
511
users: [
512
{ id: '1', name: 'John Doe' },
513
{ id: '2', name: 'Jane Smith' }
514
],
515
total: 2
516
}
517
}
518
}
519
}
520
};
521
```
522
523
## Schema Definitions
524
525
### SchemaObject { .api }
526
527
```typescript
528
interface SchemaObject {
529
// Type and format
530
type?: string;
531
format?: string;
532
533
// Validation
534
minimum?: number;
535
maximum?: number;
536
exclusiveMinimum?: boolean;
537
exclusiveMaximum?: boolean;
538
multipleOf?: number;
539
minLength?: number;
540
maxLength?: number;
541
pattern?: string;
542
minItems?: number;
543
maxItems?: number;
544
uniqueItems?: boolean;
545
minProperties?: number;
546
maxProperties?: number;
547
required?: string[];
548
enum?: any[];
549
550
// Structure
551
properties?: Record<string, SchemaObject | ReferenceObject>;
552
additionalProperties?: SchemaObject | ReferenceObject | boolean;
553
items?: SchemaObject | ReferenceObject;
554
555
// Composition
556
allOf?: (SchemaObject | ReferenceObject)[];
557
oneOf?: (SchemaObject | ReferenceObject)[];
558
anyOf?: (SchemaObject | ReferenceObject)[];
559
not?: SchemaObject | ReferenceObject;
560
561
// Metadata
562
title?: string;
563
description?: string;
564
default?: any;
565
example?: any;
566
examples?: any[] | Record<string, any>;
567
568
// OpenAPI Extensions
569
nullable?: boolean;
570
readOnly?: boolean;
571
writeOnly?: boolean;
572
deprecated?: boolean;
573
discriminator?: DiscriminatorObject;
574
xml?: XmlObject;
575
externalDocs?: ExternalDocumentationObject;
576
'x-enumNames'?: string[];
577
}
578
```
579
580
JSON Schema definition for data models.
581
582
**Usage:**
583
```typescript
584
const userSchema: SchemaObject = {
585
type: 'object',
586
required: ['name', 'email'],
587
properties: {
588
id: {
589
type: 'string',
590
format: 'uuid',
591
description: 'Unique user identifier',
592
readOnly: true
593
},
594
name: {
595
type: 'string',
596
minLength: 1,
597
maxLength: 100,
598
description: 'User full name'
599
},
600
email: {
601
type: 'string',
602
format: 'email',
603
description: 'User email address'
604
},
605
age: {
606
type: 'integer',
607
minimum: 0,
608
maximum: 120,
609
description: 'User age'
610
},
611
role: {
612
type: 'string',
613
enum: ['user', 'admin', 'moderator'],
614
'x-enumNames': ['User', 'Administrator', 'Moderator']
615
}
616
},
617
example: {
618
id: '123e4567-e89b-12d3-a456-426614174000',
619
name: 'John Doe',
620
email: 'john@example.com',
621
age: 30,
622
role: 'user'
623
}
624
};
625
```
626
627
### ReferenceObject { .api }
628
629
```typescript
630
interface ReferenceObject {
631
$ref: string;
632
}
633
```
634
635
Reference to another schema or component.
636
637
## Security
638
639
### SecuritySchemeObject { .api }
640
641
```typescript
642
interface SecuritySchemeObject {
643
type: SecuritySchemeType;
644
description?: string;
645
name?: string;
646
in?: string;
647
scheme?: string;
648
bearerFormat?: string;
649
flows?: OAuthFlowsObject;
650
openIdConnectUrl?: string;
651
'x-tokenName'?: string;
652
[extension: `x-${string}`]: any;
653
}
654
655
type SecuritySchemeType = 'apiKey' | 'http' | 'oauth2' | 'openIdConnect';
656
```
657
658
Defines a security scheme that can be used by operations.
659
660
**Usage:**
661
```typescript
662
const securitySchemes: Record<string, SecuritySchemeObject> = {
663
bearerAuth: {
664
type: 'http',
665
scheme: 'bearer',
666
bearerFormat: 'JWT',
667
description: 'JWT authorization header'
668
},
669
apiKey: {
670
type: 'apiKey',
671
in: 'header',
672
name: 'X-API-Key',
673
description: 'API key authentication'
674
},
675
oauth2: {
676
type: 'oauth2',
677
description: 'OAuth2 authentication',
678
flows: {
679
authorizationCode: {
680
authorizationUrl: 'https://auth.example.com/oauth/authorize',
681
tokenUrl: 'https://auth.example.com/oauth/token',
682
scopes: {
683
'read': 'Read access',
684
'write': 'Write access',
685
'admin': 'Administrative access'
686
}
687
}
688
}
689
}
690
};
691
```
692
693
### OAuthFlowsObject { .api }
694
695
```typescript
696
interface OAuthFlowsObject {
697
implicit?: OAuthFlowObject;
698
password?: OAuthFlowObject;
699
clientCredentials?: OAuthFlowObject;
700
authorizationCode?: OAuthFlowObject;
701
}
702
703
interface OAuthFlowObject {
704
authorizationUrl?: string;
705
tokenUrl?: string;
706
refreshUrl?: string;
707
scopes: ScopesObject;
708
}
709
710
type ScopesObject = Record<string, any>;
711
type SecurityRequirementObject = Record<string, string[]>;
712
```
713
714
OAuth2 flow configurations and security requirements.
715
716
## Configuration Interfaces
717
718
### SwaggerDocumentOptions { .api }
719
720
```typescript
721
interface SwaggerDocumentOptions {
722
include?: Function[];
723
extraModels?: Function[];
724
ignoreGlobalPrefix?: boolean;
725
deepScanRoutes?: boolean;
726
operationIdFactory?: OperationIdFactory;
727
linkNameFactory?: (controllerKey: string, methodKey: string, fieldKey: string) => string;
728
autoTagControllers?: boolean;
729
}
730
731
type OperationIdFactory = (controllerKey: string, methodKey: string, version?: string) => string;
732
```
733
734
Options for controlling OpenAPI document generation behavior.
735
736
**Usage:**
737
```typescript
738
const documentOptions: SwaggerDocumentOptions = {
739
include: [UserModule, ProductModule],
740
extraModels: [BaseResponse, ErrorResponse],
741
deepScanRoutes: true,
742
operationIdFactory: (controllerKey, methodKey, version) =>
743
`${controllerKey.toLowerCase()}_${methodKey}${version ? `_v${version}` : ''}`,
744
autoTagControllers: true,
745
ignoreGlobalPrefix: false
746
};
747
```
748
749
### SwaggerCustomOptions { .api }
750
751
```typescript
752
interface SwaggerCustomOptions {
753
useGlobalPrefix?: boolean;
754
ui?: boolean;
755
raw?: boolean | Array<'json' | 'yaml'>;
756
swaggerUrl?: string;
757
jsonDocumentUrl?: string;
758
yamlDocumentUrl?: string;
759
patchDocumentOnRequest?: <TRequest = any, TResponse = any>(
760
req: TRequest,
761
res: TResponse,
762
document: OpenAPIObject
763
) => OpenAPIObject;
764
explorer?: boolean;
765
swaggerOptions?: SwaggerUiOptions;
766
customCss?: string;
767
customCssUrl?: string | string[];
768
customJs?: string | string[];
769
customJsStr?: string | string[];
770
customfavIcon?: string;
771
customSiteTitle?: string;
772
customSwaggerUiPath?: string;
773
}
774
```
775
776
Options for customizing Swagger UI setup and behavior.
777
778
**Usage:**
779
```typescript
780
const swaggerOptions: SwaggerCustomOptions = {
781
useGlobalPrefix: true,
782
explorer: true,
783
customSiteTitle: 'My API Documentation',
784
swaggerOptions: {
785
persistAuthorization: true,
786
displayRequestDuration: true
787
},
788
customCss: '.swagger-ui .topbar { display: none; }',
789
patchDocumentOnRequest: (req, res, document) => {
790
// Add user-specific modifications
791
return document;
792
}
793
};
794
```
795
796
## Additional Supporting Interfaces
797
798
### ExampleObject { .api }
799
800
```typescript
801
interface ExampleObject {
802
summary?: string;
803
description?: string;
804
value?: any;
805
externalValue?: string;
806
}
807
```
808
809
Example values for schemas and parameters.
810
811
### TagObject { .api }
812
813
```typescript
814
interface TagObject {
815
name: string;
816
description?: string;
817
externalDocs?: ExternalDocumentationObject;
818
}
819
```
820
821
Tag information for grouping operations.
822
823
### ExternalDocumentationObject { .api }
824
825
```typescript
826
interface ExternalDocumentationObject {
827
description?: string;
828
url: string;
829
}
830
```
831
832
Reference to external documentation.
833
834
### LinkObject { .api }
835
836
```typescript
837
interface LinkObject {
838
operationRef?: string;
839
operationId?: string;
840
parameters?: LinkParametersObject;
841
requestBody?: any | string;
842
description?: string;
843
server?: ServerObject;
844
}
845
846
type LinkParametersObject = Record<string, any>;
847
```
848
849
Describes relationships between operations.
850
851
### CallbackObject { .api }
852
853
```typescript
854
type CallbackObject = Record<string, PathItemObject>;
855
type CallbacksObject = Record<string, CallbackObject | ReferenceObject>;
856
```
857
858
Callback definitions for asynchronous operations.
859
860
These comprehensive interfaces provide complete type safety and intellisense support for all OpenAPI 3.0 constructs, ensuring your API documentation is both accurate and maintainable.