swagger-jsdoc

repository·master·Indexed 23 days ago

https://github.com/surnet/swagger-jsdoc

A library that parses JSDoc annotations (using @openapi or @swagger tags) from source code and external YAML files to automatically generate OpenAPI 3.x, Swagger 2, or AsyncAPI 2.0 specifications. It includes a Node.js API and a CLI for generating specification files in JSON or YAML format. Requires Node.js 20.x or higher for version 6.3.0.

Tokens
6K
Snippets
19
Records
34
Agent score
81%

What's inside swagger-jsdoc

  1. Understand swagger-jsdoc's relationship with source code

    master

    It is important to note that swagger-jsdoc does not parse or interact with your actual application source code. It only reads JSDoc comments and pure YAML files to generate the OpenAPI specification. It does not perform any reading, parsing, or modification of your logic files.

    If your workflow requires a tool that analyzes your source code (e.g., TypeScript interfaces or decorators) to generate specifications, consider using an alternative like tsoa.

  2. Understand the scope and limitations of swagger-jsdoc

    master

    It is important to distinguish between documentation and implementation. swagger-jsdoc is a documentation generator that works based on code annotations or static YAML files.

    It does NOT:

    • Add logic or implementation to your API.
    • Validate the correctness of your underlying business logic.
    • Fix errors in how your API behaves at runtime.

    If you encounter errors or unexpected data when testing your API via Swagger UI, the issue lies within your application's implementation or the accuracy of your YAML descriptions, not within the swagger-jsdoc library itself.

  3. How to use swagger-jsdoc to generate OpenAPI specifications

    master

    Use swagger-jsdoc to integrate Swagger/OpenAPI documentation directly into your source code using JSDoc comments.

    By adding @swagger or @openapi annotations above your API-related code, you can describe your API using YAML syntax. The library parses these annotations (and optionally external YAML files) to output a single, unified specification file. This allows you to document living code and feed the resulting specification into other Swagger tools.

    Key Workflow:

    1. Annotate code with @swagger or @openapi followed by YAML.
    2. (Optional) Provide paths to external YAML files.
    3. Run swagger-jsdoc to generate the final specification file.
  4. Understand the relationship between the definition object and input APIs

    master

    The swagger-jsdoc library generates an OpenAPI specification by combining two distinct types of input:

    1. Definition Object: A JavaScript object that maps directly to the OpenAPI object. This typically contains top-level metadata like info (title, version, description).
    2. Input APIs: The source code parts that form the rest of the specification. These are split into two formats:
      • Annotated JSDoc comments: Placed in non-compiled logical files (like .js files) close to the actual implementation.
      • YAML files: Used for static definitions (like components or anchors) that are referenced by JSDoc comments but are not directly tied to specific implementation code.

    The final swaggerSpecification is the merged result of these two inputs.

    const swaggerJsdoc = require('swagger-jsdoc');
    const swaggerDefinition = require('./swaggerDefinition');
    
    const options = {
      swaggerDefinition,
      apis: ['./src/routes*.js'],
    };
    
    const swaggerSpecification = swaggerJsdoc(options);
  5. Use file selection patterns to discover input files

    master

    When configuring the apis option, swagger-jsdoc uses node glob to discover files.

    • Use patterns like *.js to select all JavaScript files in the current directory.
    • Use patterns like **/*.js to select all JavaScript files in sub-folders recursively.

    Note: All paths provided in the apis array are relative to the current working directory.

    const options = {
      swaggerDefinition,
      apis: ['./src/routes*.js'], // Example glob pattern
    };
  6. Annotate source code with @swagger or @openapi

    master

    To include API documentation in your source code, place the @swagger or @openapi JSDoc tag above your code. The content following the tag must be a YAML-formatted specification part. This is commonly used directly above route handlers in frameworks like Express.

    /**
     * @swagger
     *
     * /login:
     *   post:
     *     produces:
     *       - application/json
     *     parameters:
     *       - name: username
     *         in: formData
     *         required: true
     *         type: string
     *       - name: password
     *         in: formData
     *         required: true
     *         type: string
     */
    app.post('/login', (req, res) => {
      // Your implementation comes here ...
    });
  7. Install TypeScript type definitions for swagger-jsdoc

    master
    Since swagger-jsdoc is written in Vanilla JavaScript, you should install the community-maintained type definitions from DefinitelyTyped to get IntelliSense and type checking in your TypeScript projects. The types are available via the @types/swagger-jsdoc package.
  8. Generate an OpenAPI specification from JSDoc annotations

    master

    The swagger-jsdoc library reads JSDoc annotations (using the @openapi or @swagger tags) from your source files and generates a compatible OpenAPI/Swagger specification.

    Requirements:

    • Node.js 20.x or higher.
    • The library is published as a CommonJS module.

    Workflow:

    1. Annotate your code (e.g., Express routes) with @openapi or @swagger blocks containing YAML/JSON content.
    2. Configure the swaggerJsdoc function with a definition object (containing OpenAPI metadata like openapi version and info) and an apis array (glob patterns pointing to your annotated files).
    3. Call swaggerJsdoc(options) to receive the generated specification object.
    /**
     * @openapi
     * /:
     *   get:
     *     description: Welcome to swagger-jsdoc!
     *     responses:
     *       200:
     *         description: Returns a mysterious string.
     */
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    // ...
    
    const swaggerJsdoc = require('swagger-jsdoc');
    
    const options = {
      definition: {
        openapi: '3.0.0',
        info: {
          title: 'Hello World',
          version: '1.0.0',
        },
      },
      apis: ['./src/routes*.js'], // files containing annotations as above
    };
    
    const openapiSpecification = swaggerJsdoc(options);
  9. Use the swagger-jsdoc CLI

    master

    The swagger-jsdoc CLI is a thin wrapper around the Node API. You can run it directly if installed globally, or via your package manager.

    To use it via yarn:

    yarn swagger-jsdoc

    To view the help menu and all available options:

    swagger-jsdoc -h
  10. Configure the CLI with definition and input files

    master

    Use the CLI to generate an OpenAPI/Swagger specification by providing a definition file and one or more input files containing your documentation.

    Definition File

    Specify your configuration/definition file using the --definition or -d flag. Supported extensions are .cjs, .json, .yml, and .yaml.

    Input Files

    Input files are passed as positional arguments after the definition flag. You can provide them individually or use glob patterns to match multiple files (e.g., *.js or **/*.js). Paths are relative to the current working directory.

    Output File

    By default, the output is saved to swagger.json. Use the -o flag to specify a custom output path. If the output file extension is .yaml or .yml, the specification will be saved in YAML format.

  11. Source specification parts from YAML files

    master

    You can source parts of your specification from external YAML files. When these files are included in the apis array of your configuration, you can reference YAML anchors or definitions from those files within your JSDoc annotations.

    /**
     * @swagger
     * /aws:
     *   get:
     *     description: contains a reference outside this file
     *     x-amazon-apigateway-integration: *default-integration
     */
    app.get('/aws', (req, res) => {
      // Your implementation comes here ...
    });