openapi-analyzer

1
0
Source

Извлечение и анализ OpenAPI 3.1.0 спецификации из MikoPBX для валидации эндпоинтов. Использовать при проверке соответствия API, генерации тестов, проверке схем эндпоинтов или интеграции с навыками endpoint-validator и api-test-generator.

Install

mkdir -p .claude/skills/openapi-analyzer && curl -L -o skill.zip "https://mcp.directory/api/skills/download/6422" && unzip -o skill.zip -d .claude/skills/openapi-analyzer && rm skill.zip

Installs to .claude/skills/openapi-analyzer

About this skill

MikoPBX OpenAPI Analyzing

Extract and analyze OpenAPI specification to validate endpoints, generate tests, and ensure API compliance.

What This Skill Does

  • Fetches OpenAPI 3.1.0 specification from MikoPBX (~9MB, 259 endpoints)
  • Extracts endpoint details: parameters, request/response schemas
  • Validates compliance with OpenAPI 3.1.0 standard
  • Compares code with spec: finds missing parameters and discrepancies
  • Generates test data: from schema examples and types
  • Provides Python/CLI interface: for automation and integration

When to Use This Skill

This is a helper skill used by other skills and in specific scenarios:

Use automatically with:

  • mikopbx-endpoint-validator - validates against OpenAPI spec
  • mikopbx-api-test-generator - generates tests from spec

Use manually when:

  • Validating API compliance before releases
  • Checking endpoint documentation completeness
  • Generating test data from schemas
  • Comparing code implementation with OpenAPI definition
  • Creating API documentation

How It Works

  1. Fetch OpenAPI spec from MikoPBX (internal or external URL)
  2. Analyze using Python analyzer or CLI commands
  3. Extract endpoint details (parameters, schemas, responses)
  4. Validate compliance with OpenAPI 3.1.0 standard
  5. Compare with code to find discrepancies
  6. Generate test data or documentation

Quick Start

Step 1: Fetch OpenAPI Specification

The OpenAPI spec is available at two endpoints:

  • Internal (no auth): http://mikopbx-php83.localhost:8081/pbxcore/api/v3/openapi:getSpecification
  • External (auth required): https://mikopbx-php83.localhost:8445/pbxcore/api/v3/openapi:getSpecification

Fetch from inside container (recommended):

# Get container ID
CONTAINER_ID=$(docker ps -q -f name=mikopbx)

# Fetch spec
docker exec $CONTAINER_ID curl -s http://mikopbx-php83.localhost:8081/pbxcore/api/v3/openapi:getSpecification > /tmp/mikopbx_openapi.json

# Verify
wc -l /tmp/mikopbx_openapi.json  # ~116K lines
ls -lh /tmp/mikopbx_openapi.json # ~9MB

Fetch from outside container (requires Bearer token):

curl -H "Authorization: Bearer $TOKEN" \
  https://mikopbx-php83.localhost:8445/pbxcore/api/v3/openapi:getSpecification \
  -k > /tmp/mikopbx_openapi.json

Step 2: Use Python Analyzer

The analyzer is located at scripts/openapi_analyzer.py.

Basic usage:

# Get API info
python3 scripts/openapi_analyzer.py info

# List all endpoints
python3 scripts/openapi_analyzer.py list

# Filter endpoints
python3 scripts/openapi_analyzer.py list extensions

# Get endpoint details
python3 scripts/openapi_analyzer.py get "/pbxcore/api/v3/extensions" POST

# Validate endpoint
python3 scripts/openapi_analyzer.py validate "/pbxcore/api/v3/extensions" POST

Python API:

import sys
sys.path.insert(0, 'scripts')
from openapi_analyzer import MikoPBXOpenAPIAnalyzer

# Load analyzer
analyzer = MikoPBXOpenAPIAnalyzer('/tmp/mikopbx_openapi.json')

# Get endpoint
endpoint = analyzer.get_endpoint('/pbxcore/api/v3/extensions', 'POST')
print(endpoint['summary'])
print(endpoint['requestBody']['required'])

# Validate compliance
result = analyzer.validate_endpoint_compliance('/pbxcore/api/v3/extensions', 'POST')
print(f"Valid: {result['valid']}, Score: {result['score']}/100")

# Generate test data
test_data = analyzer.generate_test_data(endpoint)
print(test_data)

Top 5 Use Cases

Use Case 1: Validate Endpoint Compliance

Check if endpoint meets OpenAPI 3.1.0 standards.

# Validate single endpoint
python3 scripts/openapi_analyzer.py validate "/pbxcore/api/v3/extensions" POST

Output:

{
  "valid": true,
  "issues": [],
  "warnings": [],
  "score": 100
}

What it checks:

  • ✓ Has summary and operationId
  • ✓ POST/PUT/PATCH has requestBody
  • ✓ Has responses defined
  • ✓ Has expected response codes (200, 400, 404, etc.)

Use Case 2: Compare OpenAPI with Code

Find discrepancies between spec and DataStructure implementation.

import sys
sys.path.insert(0, 'scripts')
from openapi_analyzer import MikoPBXOpenAPIAnalyzer

analyzer = MikoPBXOpenAPIAnalyzer()
endpoint = analyzer.get_endpoint('/pbxcore/api/v3/extensions', 'POST')

# Parameters from your DataStructure.php
code_params = ['number', 'type', 'callerid', 'userid', 'internal_id']

# Compare
comparison = analyzer.compare_with_code(endpoint, code_params)

print(f"Compliance: {comparison['compliance'] * 100:.1f}%")
print(f"In spec only: {comparison['in_spec_only']}")
print(f"In code only: {comparison['in_code_only']}")
print(f"In both: {comparison['in_both']}")

Output:

Compliance: 92.3%
In spec only: {'mobile_number', 'email'}
In code only: {'internal_id'}
In both: {'number', 'type', 'callerid', 'userid'}

Action: Add missing parameters to code or update OpenAPI spec.


Use Case 3: Generate Test Data

Create test data from OpenAPI examples.

analyzer = MikoPBXOpenAPIAnalyzer()
endpoint = analyzer.get_endpoint('/pbxcore/api/v3/extensions', 'POST')

# Generate test data
test_data = analyzer.generate_test_data(endpoint)
print(test_data)

Output:

{
  "number": "201",      # from example
  "type": "SIP",        # from enum
  "callerid": "Test User",  # from example
  "userid": "1"         # from example
}

Use in tests:

response = requests.post(
    f"{BASE_URL}/pbxcore/api/v3/extensions",
    json=test_data,
    headers=headers
)
assert response.status_code == 201

Use Case 4: Find Endpoints by Pattern

Discover all endpoints related to a resource.

# Find all extension endpoints
python3 scripts/openapi_analyzer.py list extensions

Output:

/pbxcore/api/v3/extensions
/pbxcore/api/v3/extensions/{id}
/pbxcore/api/v3/extensions/{id}:copy
/pbxcore/api/v3/extensions:getDefault
/pbxcore/api/v3/extensions:getForSelect

Use to:

  • Explore API structure
  • Find custom actions (with :)
  • Plan test coverage
  • Generate documentation

Use Case 5: Extract Schema Details

Get component schema for data modeling.

# Get Extension schema
python3 scripts/openapi_analyzer.py schema Extension

Output:

{
  "type": "object",
  "properties": {
    "id": {"type": "string"},
    "number": {"type": "string", "example": "201"},
    "type": {"type": "string", "enum": ["SIP", "IAX", "QUEUE"]},
    "callerid": {"type": "string"}
  },
  "required": ["number", "type"]
}

Extract required fields:

python3 scripts/openapi_analyzer.py schema Extension | jq -r '.required[]'

Use to:

  • Validate data models
  • Generate TypeScript/PHP interfaces
  • Create mock data
  • Document data structures

OpenAPI Specification Details

Metadata

  • OpenAPI Version: 3.1.0
  • API Version: 3.0.0
  • Total Endpoints: 259
  • Total Schemas: 96
  • File Size: ~9MB, 116K lines JSON

Structure

{
  "openapi": "3.1.0",
  "info": {
    "title": "MikoPBX REST API",
    "version": "3.0.0"
  },
  "paths": {
    "/pbxcore/api/v3/extensions": {
      "get": {...},
      "post": {...}
    }
  },
  "components": {
    "schemas": {
      "Extension": {...},
      "ExtensionListItem": {...}
    }
  }
}

Integration Patterns

With mikopbx-endpoint-validator

# 1. Fetch OpenAPI spec
docker exec $CONTAINER_ID curl -s http://mikopbx-php83.localhost:8081/pbxcore/api/v3/openapi:getSpecification > /tmp/openapi.json

# 2. Get endpoint from OpenAPI
python3 scripts/openapi_analyzer.py get "/pbxcore/api/v3/extensions" POST > /tmp/endpoint.json

# 3. Compare with DataStructure.php
# (Extract params from code, then compare)

# 4. Validate compliance
python3 scripts/openapi_analyzer.py validate "/pbxcore/api/v3/extensions" POST

See integration-examples.md for complete workflows.

With mikopbx-api-test-generator

# Generate pytest test from OpenAPI
analyzer = MikoPBXOpenAPIAnalyzer()
endpoint = analyzer.get_endpoint('/pbxcore/api/v3/extensions', 'POST')
test_data = analyzer.generate_test_data(endpoint)

# Use test_data in generated pytest...

See integration-examples.md for test generation.


Cache Strategy

OpenAPI spec is large (9MB), so cache it:

SPEC_FILE="/tmp/mikopbx_openapi.json"
CACHE_TTL=3600  # 1 hour

# Check cache age
if [ ! -f "$SPEC_FILE" ] || [ $(($(date +%s) - $(stat -f %m "$SPEC_FILE"))) -gt $CACHE_TTL ]; then
    echo "Fetching fresh spec..."
    docker exec $CONTAINER_ID curl -s http://mikopbx-php83.localhost:8081/pbxcore/api/v3/openapi:getSpecification > "$SPEC_FILE"
else
    echo "Using cached spec"
fi

Python caching:

# Good: Create once, reuse
analyzer = MikoPBXOpenAPIAnalyzer()
for path in paths:
    endpoint = analyzer.get_endpoint(path, 'GET')

# Bad: Recreates analyzer each time
for path in paths:
    analyzer = MikoPBXOpenAPIAnalyzer()  # Reloads 9MB file!

Common Patterns

Pattern 1: Batch Validation

Validate all endpoints and find issues:

python3 scripts/openapi_analyzer.py list | while read path; do
    for method in GET POST PUT DELETE; do
        python3 scripts/openapi_analyzer.py validate "$path" "$method" 2>/dev/null
    done
done | jq -s 'map(select(.valid == false))'

Pattern 2: Generate Compliance Report

#!/bin/bash
total=0
valid=0
total_score=0

while read path; do
    result=$(python3 scripts/openapi_analyzer.py validate "$path" "POST" 2>/dev/null)
    if [ $? -eq 0 ]; then
        total=$((total + 1))
        [ "$(echo "$result" | jq -r '.valid')" == "true" ] && valid=$((valid + 1))
        total_score=$((total_score + $(echo "$result" | jq -r '.score')))
    fi
done < <(python3 scripts/openapi_analyzer.py list)

echo "Valid: $valid/$total ($((valid * 100 / total))%)"
echo "Average score: $((total_score / total))/

---

*Content truncated.*

sqlite-inspector

mikopbx

Проверка консистентности данных в SQLite баз данных MikoPBX после операций REST API. Использовать при валидации результатов API, отладке проблем с данными, проверке связей внешних ключей или инспектировании CDR записей для тестирования.

640

restapi-translations

mikopbx

Управление переводами REST API ключей (rest_*) для MikoPBX. Автоматически находит отсутствующие русские ключи в RestApi.php и синхронизирует их с исходным кодом. Использовать при проверке переводов API, после добавления новых endpoints или перед релизом.

00

babel-compiler

mikopbx

Транспиляция ES6+ JavaScript в ES5 для совместимости с браузерами используя Docker-based Babel компилятор. Использовать при транспиляции JavaScript файлов после внесения изменений в ES6+ исходный код.

10

asterisk-validator

mikopbx

Валидация конфигурационных файлов Asterisk и анализ логов на корректность и best practices. Использовать при отладке проблем запуска Asterisk, проверке изменений конфигурации или проверке ошибок после регенерации воркерами.

00

translations

mikopbx

Управление многоязычными переводами на 29 языков с приоритетом русского языка. Использовать при добавлении новых переводов, переводе на все языки, проверке консистентности или удалении устаревших ключей.

00

auth-token-manager

mikopbx

Получение валидных JWT Bearer токенов для аутентификации MikoPBX REST API v3. Использовать когда нужно тестировать API эндпоинты, отлаживать проблемы аутентификации или при возникновении ошибок 401 Unauthorized. Автоматически обрабатывает вход с username/password и возвращает готовый к использованию access token.

50

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

641968

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

590705

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318395

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

450339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.