Skip to content
NestPath

Exercises — Swagger / OpenAPI

Covers: @nestjs/swagger setup with DocumentBuilder (title/description/version, addBearerAuth + reference names, addCookieAuth, addTag), SwaggerModule.createDocument/setup, UI options (persistAuthorization, sorters), the CLI plugin (classValidatorShim, introspectComments, dtoFileNameSuffix), @ApiProperty vs plugin auto-generation, controller decorators (@ApiTags, @ApiBearerAuth, @ApiOperation, @ApiResponse, @ApiParam, @ApiBody, @ApiCookieAuth), custom composed decorators via applyDecorators, documenting the interceptor envelope (ApiExtraModels, getSchemaPath, $ref), disabling Swagger in production, testing auth flows in the UI, the /api/docs-json spec for codegen.


Part A — Concept Checks (closed book)

  1. Why can't Swagger see your DTO property types by default? (Same root cause as a Module 02 concept — name it.)
  2. What are the two solutions to that problem, and which does the lesson prefer? What tediousness does the plugin remove?
  3. What do classValidatorShim and introspectComments each do? Give two concrete decorator→OpenAPI conversions the shim performs.
  4. Why must you fully restart the dev server after enabling the plugin?
  5. In addBearerAuth({...}, 'access-token') — what is the second argument, and where is it used again?
  6. Swagger UI can't exercise the refresh flow properly — why not? What does addCookieAuth accomplish anyway?
  7. @ApiOperation: what's the difference in purpose between summary and description?
  8. Why does the lesson insist on schema.example in @ApiResponse instead of leaving generated types?
  9. What does applyDecorators() do and what problem (name the principle) do custom decorators like ApiAuthResponses() solve?
  10. Your TransformInterceptor wraps every response — why doesn't Swagger know, and what's the advanced fix's key ingredients (three swagger utilities)?
  11. Why disable Swagger in production, and how?
  12. Where does the raw OpenAPI JSON live, and name one use for it beyond human reading.
  13. What does persistAuthorization: true change about your Swagger workflow?
  14. @ApiParam({ name: 'id' }) — what must name match exactly?

Part B — Guided Exercises

B1. Bootstrap

  1. npm i @nestjs/swagger. Add the full DocumentBuilder config from the lesson: title/description/version, bearer auth (named access-token), cookie auth (named refresh-token), tags Auth + Tasks, mounted at /api/docs with persistAuthorization, tagsSorter: 'alpha', operationsSorter: 'method'.
  2. Open the UI. Write down 3 things that are wrong/missing in this barebones state (compare against what the lesson predicts).

B2. Plugin

  1. Enable the plugin in nest-cli.json with all three options. Full restart.
  2. Inspect CreateTaskDto in the UI schemas section: confirm required/optional and constraints (maxLength etc.) appeared with zero @ApiProperty decorators.
  3. Add JSDoc comments above two DTO properties, e.g. typescript /** Task title shown in lists @example "Buy groceries" */ and verify introspectComments surfaces them.
  4. Add one explicit @ApiProperty({ example: ... }) where the plugin's output isn't good enough (e.g., the password field's rules). Note when manual beats auto.

B3. Decorate the controllers

  1. @ApiTags('Tasks') + @ApiBearerAuth('access-token') at class level on TasksController; @ApiTags('Auth') on AuthController.
  2. Every route gets @ApiOperation({ summary }); write real summaries, not placeholders.
  3. Document at minimum on each route: the success status (200/201) and the realistic failures (400/401/403/404/409) with descriptions.
  4. @ApiParam for :id with an example ObjectId.
  5. @ApiCookieAuth('refresh-token') on the refresh endpoint.

Checkpoint: In the UI — click Authorize, paste a real access token from a login, and successfully run GET /tasks and POST /tasks through "Try it out." Lock icons appear on protected routes; @Public() login/register show none required.

B4. DRY decorators

  1. Build ApiAuthResponses(), ApiValidationResponse() (with the full envelope example), and parameterized ApiNotFoundResponse(entity) using applyDecorators.
  2. Sweep both controllers replacing repeated @ApiResponse stacks. Count the lines you deleted.

B5. Envelope documentation + prod hardening

  1. Implement ApiWrappedResponse(status, description, dataDto?, isArray?) from the lesson using ApiExtraModels + getSchemaPath. You'll need a TaskResponseDto class (id, title, description, done, priority, ownerId, timestamps) since Swagger $refs classes, not interfaces.
  2. Apply to GET /tasks (isArray) and GET /tasks/:id. Verify the docs now show the { success, data, timestamp, path } shape with the Task schema nested under data.
  3. Wrap Swagger setup in if (process.env.NODE_ENV !== 'production'). Prove it: NODE_ENV=production npm run start → /api/docs is 404.

Part C — Independent Challenges

C1. Document the whole auth story

Auth endpoints fully documented: register (201 + 409 duplicate + 400 validation), login (200 with { accessToken } example + note that refreshToken arrives via Set-Cookie, 401 invalid credentials), refresh (cookie auth, 200, 401/403 with the reuse-detection story in the description), logout. A stranger should be able to integrate from the docs alone — that's the acceptance test.

C2. curl appendix from the spec

Fetch /api/docs-json, and from the spec alone (not your memory of the code) write the curl command for creating a task, including auth header and exact body. This validates the spec is self-sufficient.

C3. Error catalogue page

Use DocumentBuilder.setDescription() with markdown to embed a table of every errorCode from Module 03 C1 and its meaning at the top of your docs.

C4. Versioned docs

Research NestJS URI versioning (app.enableVersioning). Create a v2 of one endpoint and make Swagger display both versions distinctly. (Beyond the lesson — docs reading practice.)


Part D — Debug Drills

D1

Plugin enabled in nest-cli.json, but schemas in the UI still show empty objects. The dev "restarted" with hot reload still running from before. What's the actual restart requirement and why (compile-time vs runtime)?

D2

ts
@ApiBearerAuth() // no argument

Endpoints show lock icons, but pressing Authorize and pasting the token doesn't attach it to requests. What must the argument match?

D3

DTO renamed to create-task.request.ts. Its schema vanished from Swagger. Which plugin option explains this and two fixes?

D4

ts
@Get(':id')
@ApiParam({ name: 'taskId', example: '65a...' })
findOne(@Param('id') id: string) {}

The docs show a taskId param but "Try it out" builds /tasks/{id} with the field unfilled/mismatched. What's the rule?

D5

ApiWrappedResponse throws or renders a broken $ref when passed the Task interface. Why do $ref/getSchemaPath demand a class, and what's the standard workaround?

D6

Swagger UI's "Try it out" on POST /auth/refresh always 401s even though the curl flow works with a cookie jar. Is this a bug in your API? What browser/HttpOnly limitation does the lesson call out?


Part E — Prediction Drills

  1. The plugin is on, and UpdateTaskDto extends PartialType(CreateTaskDto) — how do its fields appear (required-wise) in the schema?
  2. A DTO field has @IsOptional() @MaxLength(500) — what two OpenAPI properties does the shim emit?
  3. You add @ApiResponse({ status: 200 }) to POST /tasks and nothing else. What status does "Try it out" actually get and does the doc match reality?
  4. NODE_ENV=production: what do /api/docs and /api/docs-json return?
  5. A route has @ApiBearerAuth('access-token') in docs but is actually @Public() in code. What happens in the UI vs reality — and which file is "lying"?

Part F — Stretch Goals

  1. Generate a typed API client from /api/docs-json with openapi-typescript (or orval); consume one endpoint from a scratch TS file.
  2. Protect docs in staging instead of removing: basic-auth middleware in front of /api/docs (Module 06 skills!).
  3. Explore @ApiExcludeEndpoint() / @ApiExcludeController() — hide an internal route from docs and discuss security-by-obscurity honestly.

Self-Assessment Checklist

  • Bootstrapped Swagger with bearer + cookie schemes and tags from memory
  • I understand exactly what the plugin auto-generates vs what I must write
  • Every endpoint has summary, realistic status codes, and examples
  • I've composed decorators with applyDecorators to kill repetition
  • The envelope wrapper is documented with $ref schemas
  • Docs are disabled (or protected) in production, and I tested it

Answers & Hints

A1: TypeScript types are erased at runtime — same "compile-time lie" from Module 02. Swagger has no runtime metadata to read.

A2: Manual @ApiProperty() on every field, or the CLI plugin that generates the metadata at compile time from types/validators/JSDoc. Lesson prefers the plugin; it removes per-property decorator boilerplate (DRY).

A3: Shim converts class-validator decorators into OpenAPI constraints (@IsString()→type string, @IsOptional()→required:false, @MinLength(8)→minLength:8, @MaxLength→maxLength...). introspectComments turns JSDoc comments into descriptions/examples.

A4: The plugin runs at compile time via nest-cli — hot reload of unchanged config won't re-run it; the build must restart.

A5: A security-scheme reference name; reused in @ApiBearerAuth('access-token') on controllers/routes to bind endpoints to that scheme.

A6: The refresh token is an HttpOnly cookie the browser controls — Swagger UI (JS) cannot set it. addCookieAuth documents the mechanism for humans even though the UI can't exercise it.

A7: summary = collapsed one-liner (what it does); description = expanded detail (how, edge cases, special behavior).

A8: Generated generic types are nearly useless for integrators; concrete example JSON is what people copy.

A9: Composes multiple decorators into one reusable decorator. Solves repetition — DRY for documentation.

A10: The interceptor transforms outside the controller's return type, invisible to static analysis. Fix ingredients: ApiExtraModels (register the DTO), getSchemaPath (produce the $ref), a manual schema.properties describing the envelope.

A11: Public docs are an attacker's API map. Wrap the whole Swagger setup in if (process.env.NODE_ENV !== 'production').

A12: /api/docs-json. Uses: client codegen, contract testing, importing into Postman.

A13: The UI remembers your pasted token across page refreshes — no re-authorizing constantly.

A14: The route parameter name — :id → name: 'id'.

D1: Compile-time plugin: kill the watcher and run npm run start:dev fresh so the build pipeline re-runs with the plugin.

D2: The reference name from addBearerAuth(..., 'access-token'). Without/mismatched, the scheme binding fails and the Authorize token isn't attached.

D3: dtoFileNameSuffix: ['.dto.ts', '.schema.ts'] — .request.ts isn't processed. Fix: rename back, or add the suffix to the plugin options.

D4: @ApiParam.name must exactly match the :param token in the route path ('id').

D5: Interfaces don't exist at runtime — nothing to reference. Create a response DTO class (or use the schema class) for $refs.

D6: Not your bug. Browsers won't let the UI attach HttpOnly cookies cross-context reliably (and Swagger can't set them). The lesson's answer: test the cookie flow with curl (-c/-b) instead.

E1: All inherited fields shown as optional (required:false) with their constraints intact — PartialType metadata carries through the shim.

E2: required: false and maxLength: 500 on that property.

E3: Reality returns 201 (Nest default for POST); the doc claiming 200 is wrong — docs assert, they don't enforce. Fix the doc (or use @HttpCode).

E4: Both 404 — setup never ran, so neither route exists.

E5: The UI demands a token (lock) but reality accepts anonymous requests — the documentation is lying; code is the source of truth. Docs drift is why decorators should be reviewed like code.