ai-api-testing / backend /services /postman_parser.py
Amitkasar's picture
Clean and flattened project initialization
3c8d218
Raw History Blame Contribute Delete
4.96 kB
import json
from typing import Dict, Any, List
def parse_postman_collection(content_str: str) -> Dict[str, Any]:
"""
Parses a Postman Collection (V2.1) JSON string.
Returns a structure compatible with the LLM planner and executor.
"""
try:
data = json.loads(content_str)
except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse Postman collection as JSON: {e}")
# Check if it's a Postman collection
info = data.get("info", {})
schema = info.get("schema", "")
if "postman.com/json/collection" not in schema:
raise ValueError("Not a valid Postman collection (missing schema identifier)")
title = info.get("name", "Postman Collection")
version = "2.1" # Standard for most modern exports
all_requests = []
def extract_items(items):
for item in items:
if "item" in item:
# This is a folder, recurse
extract_items(item["item"])
elif "request" in item:
# This is a request
request = item["request"]
name = item.get("name", "")
# Extract path and method
method = request.get("method", "GET").upper()
url_obj = request.get("url", {})
path = ""
raw_url = ""
if isinstance(url_obj, str):
raw_url = url_obj
# Try to get path from string
path = url_obj.split("?")[0]
elif isinstance(url_obj, dict):
raw_url = url_obj.get("raw", "")
path_parts = url_obj.get("path", [])
if isinstance(path_parts, list):
path = "/" + "/".join([str(p) for p in path_parts])
else:
path = str(path_parts)
# Extract headers
headers = {}
for h in request.get("header", []):
if not h.get("disabled"):
headers[h.get("key")] = h.get("value")
# Extract body
body_info = request.get("body", {})
body = None
if body_info.get("mode") == "raw":
try:
body = json.loads(body_info.get("raw", "{}"))
except:
body = body_info.get("raw")
elif body_info.get("mode") == "urlencoded":
body = {p.get("key"): p.get("value") for p in body_info.get("urlencoded", []) if not p.get("disabled")}
elif body_info.get("mode") == "formdata":
body = {p.get("key"): p.get("value") for p in body_info.get("formdata", []) if not p.get("disabled")}
# Extract description
description = request.get("description", "")
if isinstance(description, dict):
description = description.get("content", "")
all_requests.append({
"name": name,
"method": method,
"path": path,
"raw_url": raw_url,
"headers": headers,
"body": body,
"description": description
})
extract_items(data.get("item", []))
# Build simplified endpoints for the LLM planner
simplified_endpoints = []
for req in all_requests:
simplified_endpoints.append({
"path": req["path"],
"method": str(req.get("method", "GET")),
"summary": str(req.get("name", "Unnamed Request"))[:100]
})
# Prepare the "paths" object for the executor, mimicking OpenAPI structure
# The executor uses this to find schemas, but for Postman we just provide the request details directly
# since there's no formal schema in the same way.
paths = {}
for req in all_requests:
p = req["path"]
m = str(req.get("method", "get")).lower()
if p not in paths:
paths[p] = {}
# Structure this to be somewhat compatible with what api_executor expects
paths[p][m] = {
"summary": req["name"],
"description": req["description"],
"parameters": [], # Postman doesn't always have typed params
"requestBody": {
"content": {
"application/json": {
"example": req["body"]
}
}
} if req["body"] else None
}
return {
"title": title,
"version": version,
"endpoints": simplified_endpoints,
"paths": paths,
"components": {}, # No global components in Postman
"raw_requests": all_requests # Keep extra detail just in case
}