Skip to main content
hooksSource-backedReview first Safety Privacy

API Doc Generator

PostToolUse hook that extracts JSDoc and pydoc comments from modified API endpoint files and generates OpenAPI 3.1.0-compatible YAML documentation on every save.

by JSONbored·added 2025-09-19·
HarnessClaude Code
Trigger:PostToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://github.com/Surnet/swagger-jsdoc, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/api-endpoint-documentation-generator.mdx
Safety notes
Runs automatically after write or edit tool calls on route, controller, and API files., Invokes npx swagger-jsdoc or npx jsdoc to generate docs; executes python -m pydoc for Python files., Writes generated documentation files to ./docs/api/ in the project directory.
Privacy notes
Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

3 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens.

2 areas
  • SafetyLocal filesRuns automatically after write or edit tool calls on route, controller, and API files.
  • SafetyLocal filesInvokes npx swagger-jsdoc or npx jsdoc to generate docs; executes python -m pydoc for Python files.
  • SafetyLocal filesWrites generated documentation files to ./docs/api/ in the project directory.
  • PrivacyCredentials & tokensReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Safety notes

  • Runs automatically after write or edit tool calls on route, controller, and API files.
  • Invokes npx swagger-jsdoc or npx jsdoc to generate docs; executes python -m pydoc for Python files.
  • Writes generated documentation files to ./docs/api/ in the project directory.

Privacy notes

  • Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Schema details

Install type
cli
Reading time
1 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://github.com/Surnet/swagger-jsdochttps://swagger.io/specification/https://jsdoc.app/
Runtime and command metadata
Trigger
PostToolUse
Script language
bash
Script body
#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if it's an API-related file
if [[ "$FILE_PATH" == *routes/* ]] || [[ "$FILE_PATH" == *controllers/* ]] || [[ "$FILE_PATH" == *api/* ]]; then
  echo "📚 Generating API documentation for $FILE_PATH..."
  
  # Get file extension
  EXT="${FILE_PATH##*.}"
  
  case "$EXT" in
    js|jsx|ts|tsx)
      # JavaScript/TypeScript API files
      if command -v swagger-jsdoc &> /dev/null && [ -f "swaggerDef.js" ]; then
        echo "Generating Swagger documentation..."
        npx swagger-jsdoc -d swaggerDef.js -o ./docs/api.json "$FILE_PATH" 2>/dev/null
        echo "✅ Swagger documentation updated" >&2
      elif command -v npx &> /dev/null; then
        echo "Generating JSDoc documentation..."
        npx jsdoc "$FILE_PATH" -d ./docs/api/ 2>/dev/null
        echo "✅ JSDoc documentation updated" >&2
      fi
      ;;
    py)
      # Python API files
      if command -v pydoc &> /dev/null; then
        echo "Generating Python API documentation..."
        python -m pydoc -w "$FILE_PATH" 2>/dev/null
        echo "✅ Python documentation updated" >&2
      fi
      ;;
  esac
else
  echo "File not in API directory, skipping documentation generation" >&2
fi

exit 0
Full copyable content
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/api-endpoint-documentation-generator.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}

About this resource

Features

  • Fires on every write or edit to files under routes/, controllers/, or api/ directories
  • Runs swagger-jsdoc to generate an OpenAPI JSON spec from JSDoc @openapi annotations in JavaScript/TypeScript files
  • Falls back to npx jsdoc for HTML documentation when no swaggerDef.js is present
  • Runs python -m pydoc for Python endpoint files to generate module documentation
  • Writes generated docs to ./docs/api/ in the project root

Use Cases

  • Keep OpenAPI specs in sync with route code without a separate doc build step
  • Generate JSDoc HTML documentation for JavaScript/TypeScript API directories on every save
  • Auto-run pydoc on Python API modules during development
  • Ensure API documentation is always current when working with Claude Code

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/api-endpoint-documentation-generator.sh
  3. Make executable: chmod +x .claude/hooks/api-endpoint-documentation-generator.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Bash shell available
  • jq installed (for JSON parsing)
  • swagger-jsdoc ^6.0.0 (for JavaScript/TypeScript: npm i -D swagger-jsdoc) or FastAPI ^0.115.0 (for Python: pip install fastapi)
  • Node.js and npm (for swagger-jsdoc) or Python 3.8+ and pip (for FastAPI) depending on project language

Hook Configuration

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/api-endpoint-documentation-generator.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Hook Script

#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if it's an API-related file
if [[ "$FILE_PATH" == *routes/* ]] || [[ "$FILE_PATH" == *controllers/* ]] || [[ "$FILE_PATH" == *api/* ]]; then
  echo "📚 Generating API documentation for $FILE_PATH..."

  # Get file extension
  EXT="${FILE_PATH##*.}"

  case "$EXT" in
    js|jsx|ts|tsx)
      # JavaScript/TypeScript API files
      if command -v swagger-jsdoc &> /dev/null && [ -f "swaggerDef.js" ]; then
        echo "Generating Swagger documentation..."
        npx swagger-jsdoc -d swaggerDef.js -o ./docs/api.json "$FILE_PATH" 2>/dev/null
        echo "✅ Swagger documentation updated" >&2
      elif command -v npx &> /dev/null; then
        echo "Generating JSDoc documentation..."
        npx jsdoc "$FILE_PATH" -d ./docs/api/ 2>/dev/null
        echo "✅ JSDoc documentation updated" >&2
      fi
      ;;
    py)
      # Python API files
      if command -v pydoc &> /dev/null; then
        echo "Generating Python API documentation..."
        python -m pydoc -w "$FILE_PATH" 2>/dev/null
        echo "✅ Python documentation updated" >&2
      fi
      ;;
  esac
else
  echo "File not in API directory, skipping documentation generation" >&2
fi

exit 0

Examples

API Endpoint Documentation Generator Hook Script

Complete hook script that generates API documentation for JavaScript, TypeScript, and Python API files using swagger-jsdoc, JSDoc, or FastAPI

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path // .tool_input.path // \"\"")
if [ -z "$FILE_PATH" ]; then exit 0; fi
if [[ "$FILE_PATH" == *routes/* ]] || [[ "$FILE_PATH" == *controllers/* ]] || [[ "$FILE_PATH" == *api/* ]]; then
  echo "Generating API documentation for $FILE_PATH..." >&2
  EXT="${FILE_PATH##*.}"
  case "$EXT" in
    js|jsx|ts|tsx)
      if command -v swagger-jsdoc &> /dev/null && [ -f "swaggerDef.js" ]; then
        npx swagger-jsdoc -d swaggerDef.js -o ./docs/api.json "$FILE_PATH" 2>/dev/null
        echo "OpenAPI documentation updated" >&2
      elif command -v npx &> /dev/null; then
        npx jsdoc "$FILE_PATH" -d ./docs/api/ 2>/dev/null
        echo "JSDoc documentation updated" >&2
      fi
      ;;
    py)
      if command -v python &> /dev/null && python -c "import fastapi" 2>/dev/null; then
        echo "FastAPI OpenAPI docs available at /docs and /redoc endpoints" >&2
      fi
      ;;
  esac
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable automatic API documentation generation on file writes and edits

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "./.claude/hooks/api-endpoint-documentation-generator.sh"
          }
        ]
      }
    ]
  }
}

swagger-jsdoc Configuration with OpenAPI 3.1.0

Example swagger-jsdoc configuration for generating OpenAPI 3.1.0 specification with validation enabled

const swaggerJsdoc = require("swagger-jsdoc");
const options = {
  definition: {
    openapi: "3.1.0",
    info: {
      title: "My API",
      version: "1.0.0",
    },
  },
  apis: ["./src/routes/*.js"],
  failOnErrors: true,
};
const openapiSpecification = swaggerJsdoc(options);

JSDoc OpenAPI Annotation Example

Example JSDoc annotation for OpenAPI 3.1.0 endpoint documentation using @openapi tag

/**
 * @openapi
 * /users:
 *   get:
 *     summary: Get all users
 *     responses:
 *       200:
 *         description: List of users
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/User'
 */
app.get("/users", (req, res) => {
  res.json([]);
});

FastAPI Automatic OpenAPI Generation

Example FastAPI application with automatic OpenAPI 3.1.0 documentation generation

from fastapi import FastAPI
app = FastAPI(
  title="My API",
  version="1.0.0",
  openapi_version="3.1.0"
)

@app.get("/users/")
async def get_users():
  return []

# OpenAPI docs automatically available at /docs and /redoc

Troubleshooting

Hook triggers but file path pattern match fails

Debug path detection: echo "$FILE_PATH" | grep -E 'routes|controllers|api'. Verify directory structure matches expected patterns. Add custom paths to case statement. Check file extension extraction: EXT="${FILE_PATH##*.}".

swagger-jsdoc command not found during execution

Install dependencies: npm i -D swagger-jsdoc@^6.0.0. Verify swaggerDef.js exists in project root. Check node_modules/.bin is in PATH. Use npx for local binaries: npx swagger-jsdoc. Verify package.json includes swagger-jsdoc as devDependency.

Documentation generates but writes to wrong location

Create docs/api directory: mkdir -p ./docs/api. Verify write permissions on output paths. Check current working directory in hook context: pwd >&2. Use absolute paths for output: -o "$CLAUDE_PROJECT_DIR/docs/api.json".

PostToolUse fires on all edits not just API files

Enhance path filtering in script. Use stricter regex: [["$FILE_PATH" =~ (routes|api)/.*.(ts|js)$]]. Add early exit for non-matching paths. Check file extension before processing: if [["$EXT" != "js" && "$EXT" != "ts" && "$EXT" != "py"]]; then exit 0; fi.

Hook processes file but npx commands timeout silently

Remove 2>/dev/null to see actual errors. Add timeout wrapper: timeout 30s npx swagger-jsdoc. Check for hanging processes: ps aux | grep jsdoc. Verify npm registry access: npm ping. Check network connectivity for package downloads.

OpenAPI 3.1.0 spec generation fails with validation errors

Enable failOnErrors in swagger-jsdoc options: failOnErrors: true. Check JSDoc annotation syntax matches OpenAPI 3.1.0 format. Verify swaggerDef.js uses openapi: '3.1.0'. Review validation errors in output for specific issues.

FastAPI OpenAPI docs not updating after code changes

FastAPI generates OpenAPI schema at runtime - restart FastAPI server to see changes. Use auto-reload: uvicorn main:app --reload. Verify FastAPI version supports OpenAPI 3.1.0: pip show fastapi. Check /openapi.json endpoint for current schema.

swagger-jsdoc generates empty or incomplete documentation

Verify JSDoc annotations use correct @openapi or @swagger tags. Check apis array includes correct file patterns: apis: ['./src/routes/*.js']. Ensure swaggerDef.js configuration is correct. Test with single file first: npx swagger-jsdoc -d swaggerDef.js route.js.

Source citations

Add this badge to your README

Show that API Doc Generator is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/api-endpoint-documentation-generator.svg)](https://heyclau.de/entry/hooks/api-endpoint-documentation-generator)

How it compares

API Doc Generator side by side with its closest alternative on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Field

PostToolUse hook that extracts JSDoc and pydoc comments from modified API endpoint files and generates OpenAPI 3.1.0-compatible YAML documentation on every save.

Open dossier

Automatically generates and updates project documentation from code comments, README files, and API definitions. This PostToolUse hook provides real-time documentation generation when code files are modified, supporting multiple programming languages and documentation formats.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backed
Submitter
Install riskReview firstReview first
Notes Safety Privacy Safety Privacy
Brand
Categoryhookshooks
Sourcesource-backedsource-backed
AuthorJSONboredJSONbored
Added2025-09-192025-09-16
Platforms
Claude Code
Claude Code
Source repo
Safety notesRuns automatically after write or edit tool calls on route, controller, and API files. Invokes npx swagger-jsdoc or npx jsdoc to generate docs; executes python -m pydoc for Python files. Writes generated documentation files to ./docs/api/ in the project directory.Runs automatically after write/edit tool use and may invoke local documentation generators such as npx jsdoc, jsdoc2md, typedoc, pdoc, pydoc, go doc, or cargo doc. Can write generated documentation under ./docs and may be slow on large source files or projects with expensive documentation tooling.
Privacy notesReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Reads modified source, README, Markdown, and package metadata files to count comments, links, functions, classes, and documentation sections. Generated documentation may include source comments, API details, project names, and README content from the local workspace.
Prerequisites— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/api-endpoint-documentation-generator.sh && chmod +x .claude/hooks/api-endpoint-documentation-generator.sh
mkdir -p .claude/hooks && touch .claude/hooks/documentation-generator.sh && chmod +x .claude/hooks/documentation-generator.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/api-endpoint-documentation-generator.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/documentation-generator.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimed
Open in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.