@nestjs/swagger OpenAPI Module
repository·master·Indexed 23 days ago
https://github.com/nestjs/swaggerAn OpenAPI (Swagger) module for the NestJS framework that enables automatic generation of interactive API documentation. It provides a comprehensive suite of decorators for documenting DTOs (@ApiProperty, @ApiSchema), endpoints (@ApiOperation, @ApiTags), and request/response parameters, alongside a DocumentBuilder for configuring global API metadata, security schemes, and server settings.
What's inside @nestjs/swagger
- For a comprehensive overview and a step-by-step tutorial on how to integrate and use Swagger within your NestJS project, refer to the official NestJS documentation.
Install @nestjs/swagger
masterTo use OpenAPI (Swagger) documentation in your NestJS application, install the
@nestjs/swaggerpackage using npm.$ npm i --save @nestjs/swaggerConfigure OpenAPI links with the link option
masterThe
linkoption in@ApiProperty(andApiPropertyCommonOptions) allows you to define Swagger link objects. You provide a lazy function that returns the type for which the decorated property can be used as an ID.To fully implement this, use
@ApiDefaultGetteron the getter route of the target type to generate the actual OpenAPI link objects.Configure SwaggerCustomOptions
masterThe
SwaggerCustomOptionsinterface is used to configure the behavior of the Swagger module, including how the Swagger UI is served, how API definitions (JSON/YAML) are accessed, and how the OpenAPI document can be modified before being served.Key configuration areas include:
- Endpoint Control: Use
uito enable/disable the Swagger UI andrawto enable/disable or restrict the formats (e.g.,raw: ['json']) of the raw API definitions. - Path Customization: Configure
jsonDocumentUrl,yamlDocumentUrl, andswaggerUrlto change the default paths for documentation assets. - UI Customization: Inject custom styles via
customCssorcustomCssUrl, and custom logic viacustomJsorcustomJsStr. You can also set acustomSiteTitleorcustomfavIcon. - Document Transformation: Use
patchDocumentOnRequestto intercept and modify the OpenAPI document dynamically before it is served.
- Endpoint Control: Use
Configure SwaggerDocumentOptions for document generation
masterThe
SwaggerDocumentOptionsinterface is used to customize the generation of the Swagger/OpenAPI specification. It allows you to control which modules are included, how operation IDs and links are named, how tags are generated, and how schema examples are handled.Key configuration options include:
include: A list of modules to include in the specification.extraModels: Additional models to be inspected and included.ignoreGlobalPrefix: Iftrue, ignores the global prefix set viasetGlobalPrefix().deepScanRoutes: Iftrue, also loads routes from modules imported by theincludemodules.operationIdFactory: A custom function to generateoperationIdvalues.linkNameFactory: A custom function to generate names for links in response fields.autoTagControllers: Iftrue(default), uses the controller name (minus theControllersuffix) as the tag. Iffalse, you must manually use@ApiTags().onlyIncludeDecoratedEndpoints: Iftrue, only routes decorated with@ApiIncludeEndpoint()are included.excludeDynamicDefaults: Iftrue, omitsdefaultvalues on schema properties that are non-plain objects (likenew Date()) to prevent spec changes on every restart.exampleMaxDepth: Truncates nested object/array depth forexampleandexamplesvalues to prevent document inflation.0collapses non-primitives to{}or[].
Configure Swagger CLI Plugin options
masterThe Swagger CLI plugin can be customized using the
PluginOptionsinterface. These options control how the plugin identifies DTOs and controllers, how it handles comments, and how it generates OpenAPI metadata.Key Configuration Options
Option Type Default Description dtoFileNameSuffixstring | string[]['.dto.ts', '.entity.ts']Suffixes used to identify DTO files. Can be a single string or an array of strings. controllerFileNameSuffixstring | string[]['.controller.ts']Suffixes used to identify Controller files. classValidatorShimbooleantrueWhether to shim class-validatorclassTransformerShimboolean | 'exclusive'falseWhether to shim class-transformerdtoKeyOfCommentstring'description'The comment key used for DTO properties. controllerKeyOfCommentstring'summary'The comment key used for controller methods. introspectCommentsbooleanfalseWhether to introspect comments. skipAutoHttpCodebooleanundefinedSkip auto-annotating controller methods with HTTP status codes (e.g. @HttpCode(201)).skipDefaultValuesbooleanfalseSkip adding defaultfor properties that do not specify default values.autoFillEnumNamebooleanundefinedAutomatically add enumNameto@ApiPropertywhen the property type is an enum to prevent duplicate inline definitions.debugbooleanfalseEnable debug logging. Important Constraints
- Suffixes: When providing
dtoFileNameSuffixorcontrollerFileNameSuffix, do not include.tsin the patterns. The plugin will automatically filter out.tsto prevent unwanted behavior and will issue a warning if it is detected.
- Suffixes: When providing
Create a partial version of a DTO with PartialType
masterUse the
PartialTypefunction to create a new class that has all the properties of an existing class (DTO) marked as optional. This is particularly useful for creating 'Update' DTOs where all fields are optional, while maintaining the Swagger documentation and validation metadata from the original class.Configuration Options
Option Type Default Description skipNullPropertiesbooleantrueIf true, validations are ignored if a property isnullorundefined. Iffalse, validations are ignored only if the property isundefined.When you use
PartialType, it automatically:- Inherits validation metadata.
- Inherits transformation metadata.
- Sets
required: falsefor all properties in the generated Swagger documentation via@ApiProperty.
Use DeepPartialType to create recursive optional DTOs
masterThe
DeepPartialTypefunction creates a new class where all properties of the provided DTO class—including nested DTO classes—are made optional.Unlike the standard
PartialTypewhich only makes top-level properties optional,DeepPartialTyperecursively wraps nested DTO properties in their ownDeepPartialTypeversion. This is useful for creating 'Update' DTOs where you might want to partially update a deeply nested object structure.Options
Option Type Default Description skipNullPropertiesbooleantrueIf true, validations are ignored if a property isnullorundefined. Iffalse, validations are only ignored if the property isundefined.export function DeepPartialType<T>( classRef: Type<T>, options: { skipNullProperties?: boolean; } = {} ): Type<DeepPartial<T>>Add servers to the OpenAPI document
masterTheaddServermethod allows you to define one or more server URLs where the API can be accessed. You can provide a description and variables for the URL. You can also passserverExtraPropertiesto include additional OpenAPI server object properties.Add global parameters and responses
masterUse
addGlobalParametersandaddGlobalResponseto define parameters or responses that should be available across multiple endpoints.Note: For
addGlobalParameters, top-level attributes are ignored; examples should be specified under theschemaobject. ForaddGlobalResponse, responses are grouped by their HTTP status code.Configure security schemes and requirements
masterYou can define how your API is secured using several specialized methods or the genericaddSecuritymethod. Once a scheme is defined, useaddSecurityRequirementsto apply it globally to the document.Configure OpenAPI document metadata with DocumentBuilder
masterUse theDocumentBuilderclass to set the basic information for your OpenAPI document, such as title, description, version, and contact details. These methods follow a fluent API pattern, allowing you to chain calls.