Generate OpenAPI 3.1 Specs and JSDoc from Route Handlers

Turns pasted Express, Fastify, or Next.js route handlers into valid OpenAPI 3.1 YAML specs, typed JSDoc blocks, and a list of undocumented error edge cases.

Agent prompt for ChatGPT and Claude

You get: OpenAPI 3.1 YAML, JSDoc Blocks and undocumented Edge Cases

Prompt

Prompt
Act as a staff backend engineer and API specification architect.

I will paste one or more route handler files (and any referenced middleware or validation schemas) right after this prompt. Your job is to extract an accurate OpenAPI 3.1 YAML specification and matching JSDoc comments directly from the code.

Follow these rules:
1. Extract every HTTP method, path parameter, query parameter, request body field, and response status code strictly from the pasted code. Never invent fields, status codes, or defaults that do not exist in the implementation.
2. Document authentication and authorization headers by inspecting middleware, guards, or header lookups in the handler.
3. Map every thrown error, early return, and catch block to its exact HTTP status code and response payload shape.
4. Write JSDoc blocks ready to paste directly above each handler function, including summary, parameter descriptions, and return types without using curly-brace placeholders.
5. Flag undocumented edge cases such as unhandled promise rejections, missing input validation, or implicit 500 responses.

Output format:
- OpenAPI 3.1 YAML: A valid YAML snippet covering paths, parameters, requestBody, security, and responses.
- JSDoc Blocks: Ready-to-paste comment blocks for each exported handler.
- Undocumented Edge Cases: A bulleted table or list of code-level gaps with line or symbol references.

End with one short line listing any middleware, external types, or global error handlers that were missing from the pasted code and had to be assumed.

Example output

Outputs generated from one refund routePOST /v1/invoices/42/refund
Documented response codes
5
201, 400, 401, 404, 409
Undocumented edge cases
3
Gateway timeout, idempotency key, path parameter
OpenAPI version
3.1.0
YAML spec plus JSDoc block

Example for: a Node.js Express billing service handling invoice refunds via POST /v1/invoices/42/refund with bearer token auth and Zod body validation.

OpenAPI 3.1 YAML
openapi: 3.1.0
info:
  title: Billing Refunds API
  version: 1.0.0
paths:
  /v1/invoices/42/refund:
    post:
      operationId: createInvoiceRefund
      summary: Issue a full or partial refund for a paid invoice
      security:
        - bearerAuth: []
      parameters:
        - name: invoiceId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - amountCents
                - reason
              properties:
                amountCents:
                  type: integer
                  minimum: 1
                reason:
                  type: string
                  enum:
                    - duplicate
                    - fraudulent
                    - requested_by_customer
      responses:
        '201':
          description: Refund created
        '400':
          description: Invalid request body or refund exceeds invoice total
        '401':
          description: Missing or invalid Authorization bearer header
        '404':
          description: Invoice not found
        '409':
          description: Invoice is already fully refunded
JSDoc Blocks
/**
 * Issues a full or partial refund for an existing paid invoice.
 * Requires a valid Authorization bearer token verified by requireAuth.
 *
 * @param req - Express request with invoiceId path param and refund body
 * @param res - Express response returning 201 on success or 4xx on error
 * @returns Promise resolving when the JSON response is sent
 */
Undocumented Edge Cases
  • Unhandled gateway timeout: The stripe.refunds.create call inside createInvoiceRefund has no try/catch block, so upstream failures bubble up as an unformatted 500 error.
  • Missing idempotency key: The handler does not read an Idempotency-Key header, allowing duplicate refunds on client retries.
  • Unvalidated path parameter: req.params.invoiceId is passed directly to the database query without UUID format validation.

Assumptions and missing context: The requireAuth middleware implementation was not pasted, so the 401 response payload shape and required JWT scopes were assumed.

Written by AI from this prompt. Your results will vary.

Tips and common edits

Why this works

  • Forces strict extraction from pasted code so the model cannot hallucinate fields, defaults, or status codes.
  • Separates OpenAPI YAML, JSDoc blocks, and edge-case audits so each artifact can be copied straight into a PR.
  • Requires an explicit assumptions line at the end to surface missing middleware or global error handlers.

Use this in GitHub Copilot Chat, ChatGPT, or Claude when documenting legacy endpoints or preparing a PR. Paste the route handler file along with any validation schemas or auth middleware it imports.

Common edits

  • Add a rule to output OpenAPI 3.0.3 instead of 3.1.0 if your Swagger UI or SDK generator does not support 3.1 yet.
  • Ask the model to include concrete JSON response examples for every 2xx and 4xx status code in the YAML.

Reuse it: Use in a workflowAdapt in the builder

Prompt details

By
Prompts-GPT editors
Published
How prompts are written and checked

Did this prompt work?

Reconcile OpenAPI Schema Drift with Backend Logic

Get a three-column alignment matrix that identifies discrepancies between your OpenAPI spec, TypeScript client types, and actual backend request validation logic.

AI Coding AgentsClaude Code

Audit AI Code Diffs for Performance Regressions

This prompt scans code changes for silent performance killers like N+1 queries, unindexed filters, and memory leaks before you merge them.

Audit API Route Handlers for Auth and Permission Leaks

Get a structured security audit of your API route handlers that evaluates tenant isolation, role-based access control, and input validation risks.

Audit a TypeScript API Route for Race Conditions, Auth, and N+1 Bugs

Get a severity-ranked security and performance audit of your TypeScript API route with exact line numbers, concrete exploit or failure scenarios, and minimal targeted fix diffs.

Draft OpenAPI 3.1 Schemas for Custom GPT API Actions

Generate production-ready OpenAPI 3.1 YAML specifications from plain-English descriptions of your API endpoints to use in ChatGPT Custom GPT actions.

Generate API Client Patches from OpenAPI Schema Diffs

This prompt analyzes OpenAPI diffs to generate precise code patches and unit test assertions for your API client SDK.