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)
- Why can't Swagger see your DTO property types by default? (Same root cause as a Module 02 concept — name it.)
- What are the two solutions to that problem, and which does the lesson prefer? What tediousness does the plugin remove?
- What do
classValidatorShimandintrospectCommentseach do? Give two concrete decorator→OpenAPI conversions the shim performs. - Why must you fully restart the dev server after enabling the plugin?
- In
addBearerAuth({...}, 'access-token')— what is the second argument, and where is it used again? - Swagger UI can't exercise the refresh flow properly — why not? What does
addCookieAuthaccomplish anyway? @ApiOperation: what's the difference in purpose betweensummaryanddescription?- Why does the lesson insist on
schema.examplein@ApiResponseinstead of leaving generated types? - What does
applyDecorators()do and what problem (name the principle) do custom decorators likeApiAuthResponses()solve? - Your TransformInterceptor wraps every response — why doesn't Swagger know, and what's the advanced fix's key ingredients (three swagger utilities)?
- Why disable Swagger in production, and how?
- Where does the raw OpenAPI JSON live, and name one use for it beyond human reading.
- What does
persistAuthorization: truechange about your Swagger workflow? @ApiParam({ name: 'id' })— what mustnamematch exactly?
Part B — Guided Exercises
B1. Bootstrap
npm i @nestjs/swagger. Add the fullDocumentBuilderconfig from the lesson: title/description/version, bearer auth (namedaccess-token), cookie auth (namedrefresh-token), tagsAuth+Tasks, mounted at/api/docswithpersistAuthorization,tagsSorter: 'alpha',operationsSorter: 'method'.- Open the UI. Write down 3 things that are wrong/missing in this barebones state (compare against what the lesson predicts).
B2. Plugin
- Enable the plugin in
nest-cli.jsonwith all three options. Full restart. - Inspect
CreateTaskDtoin the UI schemas section: confirm required/optional and constraints (maxLength etc.) appeared with zero@ApiPropertydecorators. - Add JSDoc comments above two DTO properties, e.g.
typescript /** Task title shown in lists @example "Buy groceries" */and verifyintrospectCommentssurfaces them. - 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
@ApiTags('Tasks')+@ApiBearerAuth('access-token')at class level on TasksController;@ApiTags('Auth')on AuthController.- Every route gets
@ApiOperation({ summary }); write real summaries, not placeholders. - Document at minimum on each route: the success status (200/201) and the realistic failures (400/401/403/404/409) with descriptions.
@ApiParamfor:idwith an example ObjectId.@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
- Build
ApiAuthResponses(),ApiValidationResponse()(with the full envelope example), and parameterizedApiNotFoundResponse(entity)usingapplyDecorators. - Sweep both controllers replacing repeated
@ApiResponsestacks. Count the lines you deleted.
B5. Envelope documentation + prod hardening
- Implement
ApiWrappedResponse(status, description, dataDto?, isArray?)from the lesson usingApiExtraModels+getSchemaPath. You'll need aTaskResponseDtoclass (id, title, description, done, priority, ownerId, timestamps) since Swagger$refs classes, not interfaces. - Apply to
GET /tasks(isArray) andGET /tasks/:id. Verify the docs now show the{ success, data, timestamp, path }shape with the Task schema nested underdata. - Wrap Swagger setup in
if (process.env.NODE_ENV !== 'production'). Prove it:NODE_ENV=production npm run start→/api/docsis 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
@ApiBearerAuth() // no argumentEndpoints 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
@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
- The plugin is on, and
UpdateTaskDto extends PartialType(CreateTaskDto)— how do its fields appear (required-wise) in the schema? - A DTO field has
@IsOptional() @MaxLength(500)— what two OpenAPI properties does the shim emit? - You add
@ApiResponse({ status: 200 })toPOST /tasksand nothing else. What status does "Try it out" actually get and does the doc match reality? NODE_ENV=production: what do/api/docsand/api/docs-jsonreturn?- 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
- Generate a typed API client from
/api/docs-jsonwithopenapi-typescript(ororval); consume one endpoint from a scratch TS file. - Protect docs in staging instead of removing: basic-auth middleware in front of
/api/docs(Module 06 skills!). - 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.
