Skip to main content

scripts-generate-openapi

#!/usr/bin/env python3 """

title: "Generate Openapi" component_type: script version: "1.0.0" audience: contributor status: stable summary: "CODITECT OpenAPI Specification Generator ========================================" keywords: ['api', 'generate', 'generation', 'openapi', 'security'] tokens: ~500 created: 2025-12-22 updated: 2025-12-22 script_name: "generate_openapi.py" language: python executable: true usage: "python3 scripts/generate_openapi.py [options]" python_version: "3.10+" dependencies: [] modifies_files: false network_access: false requires_auth: false

CODITECT OpenAPI Specification Generator

STATUS: STUB - Not yet implemented VERSION: 0.1.0 (placeholder) AUTHOR: CODITECT Core Team

DESCRIPTION: Generates OpenAPI 3.x specifications from code annotations, docstrings, and existing API definitions. Supports multiple frameworks (FastAPI, Flask, Express, Actix) with automatic schema extraction.

PURPOSE: - Extract API definitions from code (routes, handlers, models) - Generate OpenAPI 3.0/3.1 compliant specifications - Merge multiple API sources into unified spec - Validate specs against OpenAPI schema - Generate client SDKs from specs

EXPECTED INPUTS: --source : Source type (fastapi, flask, express, actix, manual) --paths : Paths to scan for API definitions --output : Output file path (default: openapi.json) --format : Output format (json, yaml) --version : OpenAPI version (3.0.3, 3.1.0) --title : API title --api-version : API version string --servers : Server URLs (comma-separated) --merge : Additional spec files to merge

EXPECTED OUTPUTS: - openapi.json/yaml conforming to OpenAPI 3.x with: - info (title, version, description) - servers (URLs, descriptions) - paths (endpoints with operations) - components (schemas, security, parameters) - tags (endpoint grouping) - security (authentication schemes)

DEPENDENCIES: - pyyaml - YAML support - jsonschema - spec validation - apispec (optional) - framework integrations - openapi-spec-validator - spec validation

IMPLEMENTATION REQUIREMENTS: 1. AST parsing for route extraction (Python, JS, Rust) 2. Docstring/comment parsing for descriptions 3. Type hint extraction for schema generation 4. Request/response model inference 5. Security scheme detection 6. Multiple framework support 7. Incremental generation (only changed files) 8. Spec merging with conflict resolution 9. Validation against OpenAPI schema 10. SDK generation integration (openapi-generator)

FRAMEWORK SUPPORT: Python: FastAPI (native), Flask (apispec), Django REST JavaScript: Express (swagger-jsdoc), Fastify, NestJS Rust: Actix-web (paperclip), Axum Go: Gin (swag), Echo

USAGE EXAMPLES: # Generate from FastAPI app python scripts/generate_openapi.py \ --source fastapi \ --paths src/api/ \ --output docs/api/openapi.json

# Merge multiple specs
python scripts/generate_openapi.py \\
--source manual \\
--merge api-v1.yaml,api-v2.yaml \\
--output openapi-combined.yaml

# With custom metadata
python scripts/generate_openapi.py \\
--source flask \\
--title "CODITECT API" \\
--api-version "2.0.0" \\
--servers "https://api.coditect.ai,https://staging.coditect.ai"

RELATED COMMANDS: - /doc-generate : Documentation generation - /api-documentation : API docs skill

SEE ALSO: - commands/doc-generate.md - docs/api/API-DOCUMENTATION-GUIDE.md """

import argparse import json import sys from datetime import datetime from pathlib import Path

def main(): parser = argparse.ArgumentParser( description='OpenAPI Specification Generator', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=''' Examples: %(prog)s --source fastapi --paths src/api/ %(prog)s --merge api-v1.yaml,api-v2.yaml --output combined.yaml %(prog)s --source flask --title "My API" --api-version "1.0.0"

Status: STUB - Implementation required ''' )

parser.add_argument('--source', default='manual',
choices=['fastapi', 'flask', 'express', 'actix', 'manual'],
help='Source type for extraction')
parser.add_argument('--paths', nargs='*', default=['.'],
help='Paths to scan for API definitions')
parser.add_argument('--output', default='openapi.json',
help='Output file path')
parser.add_argument('--format', default='json',
choices=['json', 'yaml'],
help='Output format')
parser.add_argument('--version', default='3.0.3',
choices=['3.0.3', '3.1.0'],
help='OpenAPI version')
parser.add_argument('--title', default='CODITECT API',
help='API title')
parser.add_argument('--api-version', default='1.0.0',
help='API version string')
parser.add_argument('--servers', default=None,
help='Server URLs (comma-separated)')
parser.add_argument('--merge', default=None,
help='Additional spec files to merge')
parser.add_argument('--validate', action='store_true',
help='Validate output against OpenAPI schema')

args = parser.parse_args()

print("=" * 70)
print("CODITECT OPENAPI-GENERATOR - STUB IMPLEMENTATION")
print("=" * 70)
print(f"\nThis script is a placeholder stub.")
print(f"Full implementation is required.\n")
print(f"Configuration:")
print(f" Source: {args.source}")
print(f" Paths: {args.paths}")
print(f" Output: {args.output}")
print(f" Format: {args.format}")
print(f" OpenAPI Version: {args.version}")
print(f" Title: {args.title}")
print(f" API Version: {args.api_version}")
print(f" Servers: {args.servers or 'default'}")
print()

# Create stub OpenAPI spec
servers = []
if args.servers:
for url in args.servers.split(','):
servers.append({"url": url.strip()})
else:
servers = [{"url": "http://localhost:8000", "description": "Development"}]

stub_spec = {
"openapi": args.version,
"info": {
"title": args.title,
"version": args.api_version,
"description": "STUB: OpenAPI specification not yet generated"
},
"servers": servers,
"paths": {},
"components": {
"schemas": {},
"securitySchemes": {}
},
"tags": []
}

# Write output
output_path = Path(args.output)
with open(output_path, 'w') as f:
if args.format == 'yaml':
try:
import yaml
yaml.dump(stub_spec, f, default_flow_style=False)
except ImportError:
json.dump(stub_spec, f, indent=2)
print("Note: PyYAML not installed, wrote JSON instead")
else:
json.dump(stub_spec, f, indent=2)

print(f"Stub spec written to: {output_path}")
print("\nTo implement this script, see the docstring requirements above.")

return 0

if name == 'main': sys.exit(main())