Skip to content

OpenAPI / Swagger is generated from code, not maintained by hand

Generate OpenAPI from controllers and DTOs — the spec follows the code, not a hand-edited file.

nestjs-config-openapi-from-code

Why it matters

Failure modes if this rule is ignored
StakeIf ignored
API drift
  • A hand-maintained spec rots the moment code changes. Wrong docs are worse than no docs.
  • Three truths — controller, handwritten spec, frontend types — diverge on the first field rename.

How to fix

@nestjs/swagger generates an OpenAPI spec from DTOs and decorators. That spec is the source for the frontend client codegen (see professional-architecture-testing-contracts rule 15).

Examples

Bad
yaml
# openapi/sites.yaml — maintained by hand, drifts from controllers
paths:
  /sites:
    post:
      requestBody:
        schema:
          properties:
            title: { type: string }
Good
ts
// libs/sites-management/backend-feature/src/lib/dto/site.dto.ts
export class SiteDto {
  @ApiProperty() id!: string;
  @ApiProperty() name!: string;
  @ApiProperty() slug!: string;
}

// apps/api/src/main.ts
const config = new DocumentBuilder().setTitle('Example API').build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);
// + export to JSON in CI so the frontend can codegen

Contribute

Released under the MIT License.

esc