File size: 4,962 Bytes
3c8d218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
    }