@nestjs/swagger OpenAPI Module

repository·master·Indexed 23 days ago

https://github.com/nestjs/swagger

An 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.

Tokens
8K
Snippets
14
Records
50
Agent score
78%

What's inside @nestjs/swagger

  1. Configure SwaggerCustomOptions

    master

    The SwaggerCustomOptions interface 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 ui to enable/disable the Swagger UI and raw to enable/disable or restrict the formats (e.g., raw: ['json']) of the raw API definitions.
    • Path Customization: Configure jsonDocumentUrl, yamlDocumentUrl, and swaggerUrl to change the default paths for documentation assets.
    • UI Customization: Inject custom styles via customCss or customCssUrl, and custom logic via customJs or customJsStr. You can also set a customSiteTitle or customfavIcon.
    • Document Transformation: Use patchDocumentOnRequest to intercept and modify the OpenAPI document dynamically before it is served.
  2. Configure SwaggerDocumentOptions for document generation

    master

    The SwaggerDocumentOptions interface 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: If true, ignores the global prefix set via setGlobalPrefix().
    • deepScanRoutes: If true, also loads routes from modules imported by the include modules.
    • operationIdFactory: A custom function to generate operationId values.
    • linkNameFactory: A custom function to generate names for links in response fields.
    • autoTagControllers: If true (default), uses the controller name (minus the Controller suffix) as the tag. If false, you must manually use @ApiTags().
    • onlyIncludeDecoratedEndpoints: If true, only routes decorated with @ApiIncludeEndpoint() are included.
    • excludeDynamicDefaults: If true, omits default values on schema properties that are non-plain objects (like new Date()) to prevent spec changes on every restart.
    • exampleMaxDepth: Truncates nested object/array depth for example and examples values to prevent document inflation. 0 collapses non-primitives to {} or [].
  3. Configure Swagger CLI Plugin options

    master

    The Swagger CLI plugin can be customized using the PluginOptions interface. These options control how the plugin identifies DTOs and controllers, how it handles comments, and how it generates OpenAPI metadata.

    Key Configuration Options

    OptionTypeDefaultDescription
    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-validator
    classTransformerShimboolean | 'exclusive'falseWhether to shim class-transformer
    dtoKeyOfCommentstring'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 default for properties that do not specify default values.
    autoFillEnumNamebooleanundefinedAutomatically add enumName to @ApiProperty when the property type is an enum to prevent duplicate inline definitions.
    debugbooleanfalseEnable debug logging.

    Important Constraints

    • Suffixes: When providing dtoFileNameSuffix or controllerFileNameSuffix, do not include .ts in the patterns. The plugin will automatically filter out .ts to prevent unwanted behavior and will issue a warning if it is detected.
  4. Create a partial version of a DTO with PartialType

    master

    Use the PartialType function 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

    OptionTypeDefaultDescription
    skipNullPropertiesbooleantrueIf true, validations are ignored if a property is null or undefined. If false, validations are ignored only if the property is undefined.

    When you use PartialType, it automatically:

    1. Inherits validation metadata.
    2. Inherits transformation metadata.
    3. Sets required: false for all properties in the generated Swagger documentation via @ApiProperty.
  5. Use DeepPartialType to create recursive optional DTOs

    master

    The DeepPartialType function creates a new class where all properties of the provided DTO class—including nested DTO classes—are made optional.

    Unlike the standard PartialType which only makes top-level properties optional, DeepPartialType recursively wraps nested DTO properties in their own DeepPartialType version. This is useful for creating 'Update' DTOs where you might want to partially update a deeply nested object structure.

    Options

    OptionTypeDefaultDescription
    skipNullPropertiesbooleantrueIf true, validations are ignored if a property is null or undefined. If false, validations are only ignored if the property is undefined.
    export function DeepPartialType<T>(
      classRef: Type<T>,
      options: {
        skipNullProperties?: boolean;
      } = {}
    ): Type<DeepPartial<T>>
  6. Add servers to the OpenAPI document

    master
    The addServer method 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 pass serverExtraProperties to include additional OpenAPI server object properties.
  7. Add global parameters and responses

    master

    Use addGlobalParameters and addGlobalResponse to define parameters or responses that should be available across multiple endpoints.

    Note: For addGlobalParameters, top-level attributes are ignored; examples should be specified under the schema object. For addGlobalResponse, responses are grouped by their HTTP status code.

  8. Configure OpenAPI document metadata with DocumentBuilder

    master
    Use the DocumentBuilder class 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.