Bird
Raised Fist0
Expressframework~10 mins

swagger-jsdoc setup in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - swagger-jsdoc setup
Import swagger-jsdoc
↓
Define swagger options
↓
Generate swaggerSpec with swagger-jsdoc
↓
Use swaggerSpec in Express app
↓
Serve Swagger UI with generated docs
This flow shows how to import swagger-jsdoc, define options, generate docs, and serve them in an Express app.
Execution Sample
Express
const swaggerJSDoc = require('swagger-jsdoc');

const options = {
  definition: { openapi: '3.0.0', info: { title: 'API', version: '1.0.0' } },
  apis: ['./routes/*.js']
};

const swaggerSpec = swaggerJSDoc(options);
This code imports swagger-jsdoc, sets options with API info and files, then generates the swaggerSpec object.
Execution Table
StepActionInput/StateOutput/State
1Import swagger-jsdocNoneswaggerJSDoc function available
2Define options objectSet openapi version, info, apis pathoptions object created
3Call swaggerJSDoc(options)options objectswaggerSpec object generated with API docs
4Use swaggerSpec in ExpressswaggerSpec objectSwagger UI can serve API docs
5Serve Swagger UI routeExpress app configuredAPI docs accessible at /api-docs
💡 Swagger docs are ready and served in Express app
Variable Tracker
VariableStartAfter Step 2After Step 3Final
swaggerJSDocundefinedfunction importedfunction importedfunction imported
optionsundefined{definition, apis}{definition, apis}{definition, apis}
swaggerSpecundefinedundefinedgenerated swaggerSpec objectgenerated swaggerSpec object
Key Moments - 3 Insights
Why do we need to specify the 'apis' path in options?
The 'apis' path tells swagger-jsdoc where to find the API route files with comments to generate docs, as shown in step 2 of the execution_table.
What does swagger-jsdoc(options) return?
It returns a swaggerSpec object containing the OpenAPI documentation generated from the options and API comments, as seen in step 3.
How do we make the generated docs visible in the Express app?
By using the swaggerSpec object with a Swagger UI middleware route in Express, as described in steps 4 and 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output after step 3?
Aswagger-jsdoc function imported
Boptions object with API paths
CswaggerSpec object with API docs
DExpress app configured
💡 Hint
Check the 'Output/State' column for step 3 in execution_table
At which step do we define the API info like title and version?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Input/State' columns in execution_table for where options are created
If we change the 'apis' path in options, what changes in the execution?
Aswagger-jsdoc function will not import
BswaggerSpec will include docs from new API files
CExpress app will crash
DNo change in swaggerSpec
💡 Hint
Refer to the role of 'apis' in step 2 and 3 of execution_table
Concept Snapshot
swagger-jsdoc setup:
1. Import swagger-jsdoc
2. Define options with OpenAPI info and API file paths
3. Generate swaggerSpec by calling swaggerJSDoc(options)
4. Use swaggerSpec in Express to serve docs
5. Access docs via Swagger UI route
Full Transcript
This visual execution shows how to set up swagger-jsdoc in an Express app. First, you import the swagger-jsdoc library. Then, you create an options object that includes OpenAPI version, API information like title and version, and the paths to your API route files. Next, you call swaggerJSDoc with these options to generate a swaggerSpec object containing your API documentation. Finally, you use this swaggerSpec in your Express app to serve the Swagger UI, making your API docs accessible to users. The execution table traces each step, showing how variables change and how the setup progresses until the docs are ready to serve.

Practice

(1/5)
1. What is the main purpose of swagger-jsdoc in an Express app?
easy
A. To connect to a database
B. To handle HTTP requests and responses
C. To generate API documentation from comments in your code
D. To serve static files like images and CSS

Solution

  1. Step 1: Understand swagger-jsdoc role

    swagger-jsdoc reads specially formatted comments in your Express code to create API documentation automatically.
  2. Step 2: Compare with other options

    Handling HTTP requests is Express's job, not swagger-jsdoc. Database connection and serving static files are unrelated tasks.
  3. Final Answer:

    To generate API documentation from comments in your code -> Option C
  4. Quick Check:

    swagger-jsdoc = API docs generator [OK]
Hint: swagger-jsdoc creates docs from code comments [OK]
Common Mistakes:
  • Confusing swagger-jsdoc with Express routing
  • Thinking swagger-jsdoc manages databases
  • Assuming swagger-jsdoc serves static files
2. Which of the following is the correct way to import and initialize swagger-jsdoc in an ES modules-based Express app?
easy
A. import swaggerJSDoc from 'swagger-jsdoc'; const specs = swaggerJSDoc(options);
B. const swaggerJSDoc = require('swagger-jsdoc'); const specs = swaggerJSDoc();
C. const swaggerJSDoc = require('swagger-jsdoc'); const specs = swaggerJSDoc(options);
D. import swaggerJSDoc from 'swagger-jsdoc'; const specs = swaggerJSDoc();

Solution

  1. Step 1: Use modern ES module import

    In modern Express apps using ES modules, import swaggerJSDoc from 'swagger-jsdoc' is correct.
  2. Step 2: Initialize swagger-jsdoc with options

    swaggerJSDoc requires an options object to generate specs, so calling it without arguments is incorrect.
  3. Final Answer:

    import swaggerJSDoc from 'swagger-jsdoc'; const specs = swaggerJSDoc(options); -> Option A
  4. Quick Check:

    Import + call with options = C [OK]
Hint: Use import and pass options to swaggerJSDoc() [OK]
Common Mistakes:
  • Calling swaggerJSDoc() without options
  • Using require instead of import in ES modules
  • Not assigning the result to a variable
3. Given this swagger-jsdoc options object, what will specs contain after calling swaggerJSDoc(options)?
const options = {
  definition: {
    openapi: '3.0.0',
    info: { title: 'Test API', version: '1.0.0' }
  },
  apis: ['./routes/*.js']
};
const specs = swaggerJSDoc(options);
medium
A. A string containing raw JavaScript code from './routes/*.js'
B. An object with OpenAPI info and paths extracted from comments in './routes/*.js'
C. An error because 'apis' path is incorrect
D. An empty object because no API comments exist

Solution

  1. Step 1: Understand swagger-jsdoc output

    swagger-jsdoc returns a JSON object with OpenAPI info and paths parsed from specified files.
  2. Step 2: Check options correctness

    The options specify OpenAPI version and info, and a valid path pattern for API files, so it will parse comments there.
  3. Final Answer:

    An object with OpenAPI info and paths extracted from comments in './routes/*.js' -> Option B
  4. Quick Check:

    swaggerJSDoc(options) = OpenAPI JSON object [OK]
Hint: swaggerJSDoc returns parsed OpenAPI JSON from code comments [OK]
Common Mistakes:
  • Expecting raw code instead of parsed JSON
  • Assuming error without checking file existence
  • Thinking output is empty without comments
4. Identify the error in this swagger-jsdoc setup snippet:
import swaggerJSDoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
const options = {
  definition: {
    openapi: '3.0.0',
    info: { title: 'API', version: '1.0' }
  },
  apis: ['./api/*.js']
};
const specs = swaggerJSDoc();

app.use('/docs', swaggerUi.serve, swaggerUi.setup(specs));
medium
A. swaggerJSDoc is called without passing the options object
B. The 'apis' path should be './api/*.ts' instead of '.js'
C. swaggerUi.setup() should be called before swaggerUi.serve
D. Missing import for swaggerUi from 'swagger-ui-express'

Solution

  1. Step 1: Check swaggerJSDoc call

    The code calls swaggerJSDoc() without arguments, but it requires the options object to generate specs.
  2. Step 2: Verify other parts

    The 'apis' path is valid for JavaScript files. swaggerUi.setup() after serve is correct usage.
  3. Final Answer:

    swaggerJSDoc is called without passing the options object -> Option A
  4. Quick Check:

    Call swaggerJSDoc(options) not empty () [OK]
Hint: Always pass options to swaggerJSDoc() [OK]
Common Mistakes:
  • Calling swaggerJSDoc() without options
  • Confusing order of swaggerUi middleware
  • Ignoring missing imports
5. You want to set up swagger-jsdoc in your Express app to document APIs ONLY in routes/users.js and routes/products.js (assuming there are other .js files in the routes directory that should not be documented). Which apis option correctly includes both files for swagger-jsdoc?
hard
A. ['./routes/users.js', './routes/products']
B. ['./routes/*.js']
C. ['./routes/users.js|./routes/products.js']
D. ['./routes/users.js', './routes/products.js']

Solution

  1. Step 1: Understand 'apis' option format

    The 'apis' option is an array of file paths or glob patterns to scan for comments.
  2. Step 2: Check each option

    ['./routes/users.js', './routes/products.js'] lists both files explicitly, which is correct. ['./routes/*.js'] uses a glob that includes both files but may include others. ['./routes/users.js|./routes/products.js'] uses an invalid string with '|'. ['./routes/users.js', './routes/products'] has a missing file extension for products.js.
  3. Final Answer:

    ['./routes/users.js', './routes/products.js'] -> Option D
  4. Quick Check:

    List each file path separately in array [OK]
Hint: List each file path separately in 'apis' array [OK]
Common Mistakes:
  • Using invalid string with '|' instead of array items
  • Omitting file extensions
  • Using too broad glob patterns unintentionally
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard