ai-api-testing / backend /services /swagger_parser.py
Amitkasar's picture
solved issue
f1c3c6d
Raw History Blame Contribute Delete
2.71 kB
import json
import yaml
from prance import ResolvingParser
from typing import Dict, Any
def parse_spec(spec_content: str) -> Dict[str, Any]:
"""
Parses a Swagger/OpenAPI spec (JSON or YAML string).
Returns the RAW spec dictionary. Resolution of $refs is deferred to execution time
to handle large files (e.g. GitHub API) efficiently.
"""
try:
spec_dict = json.loads(spec_content)
except json.JSONDecodeError:
try:
spec_dict = yaml.safe_load(spec_content)
except yaml.YAMLError as e:
raise ValueError(f"Failed to parse spec as JSON or YAML: {e}")
# We skip ResolvingParser for large spec support.
# The executor (main.py) already handles on-the-fly $ref resolution.
# Build a simplified endpoint list for the planner LLM
simplified_endpoints = []
paths = spec_dict.get("paths", {})
for path, methods in paths.items():
if not isinstance(methods, dict):
continue
for method, details in methods.items():
if method.lower() not in ["get", "post", "put", "delete", "patch"]:
continue
# Note: details might be a $ref, but usually in OpenAPI 'paths' contain
# the methods directly, or a $ref to a path item.
if isinstance(details, dict):
endpoint_info = {
"path": path,
"method": method.upper(),
"summary": details.get("summary", details.get("description", ""))[:100] # Cap summary length
}
simplified_endpoints.append(endpoint_info)
# Extract the first server URL so the frontend can auto-populate the base URL field.
# We expose it even if it looks like a placeholder — the user can edit it.
servers = spec_dict.get("servers", [])
suggested_base_url = None
if servers and isinstance(servers, list):
first_url = servers[0].get("url", "") if isinstance(servers[0], dict) else ""
if first_url:
suggested_base_url = first_url.rstrip("/")
return {
# Raw spec — used by executor to look up and resolve specific schemas on-the-fly
"paths": paths,
"components": spec_dict.get("components", {}),
"openapi": spec_dict.get("openapi", spec_dict.get("swagger", "3.0")),
# Metadata
"title": spec_dict.get("info", {}).get("title", "API Spec"),
"version": spec_dict.get("info", {}).get("version", "1.0"),
# Simplified list — used by planner LLM
"endpoints": simplified_endpoints,
# Server URL hint for the frontend
"suggested_base_url": suggested_base_url,
}