0

Prompt: Auto-Generate OpenAPI Documentation from Code

1. Complete YAML/JSON Structure: - openapi: "3.1.0" - Full info section (title, version, description, contact, license) - Servers section (dev, staging, prod with variables) - All paths with every HTTP method - Components section (schemas, securitySchemes, responses, parameters)

Prompt · برومبت

Works with

claude-code (compatible), claude (compatible), codex (compatible), chatgpt (compatible), gemini-cli (compatible), cursor (compatible), copilot (compatible), opencode (compatible), amp (compatible), roo (compatible), kiro (compatible), goose (compatible), junie (compatible), trae (compatible), cline (compatible), continue (compatible), antigravity (compatible), windsurf (compatible), augment (compatible), qwen-code (compatible), aider (compatible)

Content

Prompt: Auto-Generate OpenAPI Documentation from Code

Purpose: Automatically generate comprehensive, production-quality OpenAPI 3.1 documentation from existing API code with examples, authentication schemes, and error responses.

Best For: FastAPI, Flask, Express.js, Django REST Framework, Spring Boot APIs

Model Recommendation: Claude Sonnet 4.5, GPT-4o, Gemini 1.5 Pro

Usage Instructions:

  1. Paste your API route files (or relevant code sections) after this prompt.
  2. Specify your framework and any existing partial documentation.
  3. Claude will generate a complete openapi.yaml file.

---

THE PROMPT

You are an expert API documentation engineer. Analyze the provided API code and generate a complete, production-quality OpenAPI 3.1.0 specification.

**DOCUMENTATION REQUIREMENTS:**

1. **Complete YAML/JSON Structure:**
   - openapi: "3.1.0"
   - Full info section (title, version, description, contact, license)
   - Servers section (dev, staging, prod with variables)
   - All paths with every HTTP method
   - Components section (schemas, securitySchemes, responses, parameters)

2. **For Each Endpoint, Generate:**
   - Summary (≤10 words) and description (2-3 sentences explaining business purpose)
   - All path/query/header parameters with types, constraints, and examples
   - Request body with JSON schema validation (required fields, formats, min/max)
   - ALL possible response codes: 200, 201, 400, 401, 403, 404, 409, 422, 429, 500
   - Realistic example requests and responses (not "string" or 0, use real data)
   - Tags for grouping endpoints logically

3. **Security Documentation:**
   - Document ALL authentication methods found in code
   - JWT Bearer: show token format and expiry
   - API Keys: show header name
   - OAuth2: show scopes and flows
   - Mark which endpoints are public vs authenticated

4. **Schema Design:**
   - Create reusable $ref components for repeated structures
   - Add property descriptions for every field
   - Include validation constraints (pattern, minimum, maximum, enum)
   - Show nullable fields explicitly
   - Document deprecated fields with migration path

5. **Error Response Standardization:**
   Create a consistent error schema:

ErrorResponse: type: object properties: error: type: string description: Machine-readable error code message: type: string description: Human-readable error description details: type: array items: type: object request_id: type: string format: uuid timestamp: type: string format: date-time


6. **After Generating YAML, Also Provide:**
   - Postman collection JSON (importable)
   - List of any ambiguous endpoints needing clarification
   - Security vulnerabilities found in the API design
   - Missing standard endpoints (e.g., health check, pagination)
   - Rate limiting recommendations

**CODE TO DOCUMENT:**
[Paste your API routes/controllers here]

**Framework:** [FastAPI / Flask / Express / DRF / Spring Boot]
**Auth Method:** [JWT / OAuth2 / API Key / Session]
**Base URL:** [https://api.example.com/v1]

---

Example Input:

# Flask API routes
@app.route('/users', methods=['POST'])
@require_auth
def create_user():
    data = request.json
    user = User(
        email=data['email'],
        name=data.get('name', ''),
        role=data.get('role', 'viewer')
    )
    db.session.add(user)
    db.session.commit()
    return jsonify(user.to_dict()), 201

@app.route('/users/<int:user_id>', methods=['GET', 'PUT', 'DELETE'])
@require_auth
def user_detail(user_id):
    user = User.query.get_or_404(user_id)
    if request.method == 'GET':
        return jsonify(user.to_dict())
    elif request.method == 'PUT':
        # update logic
    elif request.method == 'DELETE':
        db.session.delete(user)
        db.session.commit()
        return '', 204

Example Output (excerpt):

openapi: "3.1.0"
info:
  title: User Management API
  version: "1.0.0"
  description: |
    RESTful API for user lifecycle management including creation, 
    retrieval, updates, and deletion with role-based access control.
  contact:
    name: API Support
    email: api@company.com

paths:
  /users:
    post:
      operationId: createUser
      summary: Create a new user account
      description: |
        Creates a new user in the system. Requires admin role. 
        Email must be unique across the platform.
      tags: [Users]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'
            example:
              email: "ahmed.hassan@company.com"
              name: "Ahmed Hassan"
              role: "editor"
      responses:
        '201':
          description: User created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          description: Email already exists
          content:
            application/json:
              example:
                error: "DUPLICATE_EMAIL"
                message: "A user with this email already exists"

Source and license

Source
Enterprise AI Prompts
Original
m0shaban/enterprise-ai-prompts/prompts/claude-code/api-documentation-generator.md
License
MIT