|
| 1 | +import sys |
| 2 | +import os |
| 3 | +import json |
| 4 | +import yaml |
| 5 | +import subprocess |
| 6 | +import re |
| 7 | + |
| 8 | +def execute_request(file_path): |
| 9 | + if not os.path.exists(file_path): |
| 10 | + print(f"Error: File {file_path} not found.") |
| 11 | + return |
| 12 | + |
| 13 | + with open(file_path, 'r') as f: |
| 14 | + content = f.read() |
| 15 | + |
| 16 | + # Simple regex to split frontmatter and body |
| 17 | + match = re.match(r'^---\s*\n(.*?)\n---\s*\n(.*)', content, re.DOTALL) |
| 18 | + if not match: |
| 19 | + print("Error: Invalid Markdown format. Missing frontmatter.") |
| 20 | + return |
| 21 | + |
| 22 | + frontmatter_raw = match.group(1) |
| 23 | + body = match.group(2).strip() |
| 24 | + |
| 25 | + try: |
| 26 | + config = yaml.safe_load(frontmatter_raw) |
| 27 | + except yaml.YAMLError as e: |
| 28 | + print(f"Error: YAML parsing failed: {e}") |
| 29 | + return |
| 30 | + |
| 31 | + method = config.get('method', 'GET').upper() |
| 32 | + url = config.get('url') |
| 33 | + headers = config.get('headers', {}) |
| 34 | + |
| 35 | + if not url: |
| 36 | + print("Error: 'url' is required in frontmatter.") |
| 37 | + return |
| 38 | + |
| 39 | + # Replace environment variables in URL, headers, and body |
| 40 | + def replace_env(text): |
| 41 | + if not isinstance(text, str): return text |
| 42 | + return re.sub(r'\{\{(.*?)\}\}', lambda m: os.environ.get(m.group(1), m.group(0)), text) |
| 43 | + |
| 44 | + url = replace_env(url) |
| 45 | + for k, v in headers.items(): |
| 46 | + headers[k] = replace_env(v) |
| 47 | + body = replace_env(body) |
| 48 | + |
| 49 | + # Build curl command |
| 50 | + curl_cmd = ['curl', '-s', '-i', '-X', method, url] |
| 51 | + |
| 52 | + for k, v in headers.items(): |
| 53 | + curl_cmd.extend(['-H', f"{k}: {v}"]) |
| 54 | + |
| 55 | + if body and method in ['POST', 'PUT', 'PATCH']: |
| 56 | + curl_cmd.extend(['-d', body]) |
| 57 | + |
| 58 | + try: |
| 59 | + result = subprocess.run(curl_cmd, capture_output=True, text=True, timeout=30) |
| 60 | + |
| 61 | + output = result.stdout |
| 62 | + if result.stderr: |
| 63 | + output += f"\n--- Stderr ---\n{result.stderr}" |
| 64 | + |
| 65 | + # Truncate if too long |
| 66 | + max_lines = 100 |
| 67 | + lines = output.splitlines() |
| 68 | + if len(lines) > max_lines: |
| 69 | + print("\n".join(lines[:max_lines])) |
| 70 | + print(f"\n... [TRUNCATED {len(lines) - max_lines} LINES] ...") |
| 71 | + else: |
| 72 | + print(output) |
| 73 | + |
| 74 | + except subprocess.TimeoutExpired: |
| 75 | + print("Error: Request timed out.") |
| 76 | + except Exception as e: |
| 77 | + print(f"Error: Execution failed: {e}") |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + if len(sys.argv) < 2: |
| 81 | + print("Usage: python execute_api_request.py <path_to_markdown_file>") |
| 82 | + else: |
| 83 | + execute_request(sys.argv[1]) |
0 commit comments