#!/bin/bash # Oracle solution: API Contract Validator CLI Tool set -e echo "=== Creating API Contract Validator CLI Tool ===" cat > /app/apivalidator << 'PYTHON_EOF' #!/usr/bin/env python3 """ API Contract Validator CLI Tool Validates API endpoints against OpenAPI/Swagger specifications. """ import argparse import json import sys import time from pathlib import Path from typing import Dict, List, Any, Optional from urllib.parse import urljoin try: import requests except ImportError: print("Error: 'requests' library is required. Install with: pip install requests", file=sys.stderr) sys.exit(1) try: import yaml except ImportError: print("Error: 'pyyaml' library is required. Install with: pip install pyyaml", file=sys.stderr) sys.exit(1) try: import jsonschema from jsonschema import validate, ValidationError except ImportError: print("Error: 'jsonschema' library is required. Install with: pip install jsonschema", file=sys.stderr) sys.exit(1) class APIContractValidator: """Main API contract validator class.""" def __init__(self, spec_file: Path, base_url: str, output_file: Path, format_type: str = "json", endpoints: List[str] = None, methods: List[str] = None, timeout: int = 10, auth_token: Optional[str] = None, validate_request: bool = False, validate_response: bool = True, generate_tests: bool = False, verbose: bool = False): self.spec_file = Path(spec_file) self.base_url = base_url.rstrip('/') self.output_file = Path(output_file) self.format_type = format_type self.endpoints = endpoints or [] self.methods = methods or [] self.timeout = timeout self.auth_token = auth_token self.validate_request = validate_request self.validate_response = validate_response self.generate_tests = generate_tests self.verbose = verbose self.spec = None self.results = { "summary": { "total_endpoints": 0, "tested_endpoints": 0, "passed": 0, "failed": 0, "errors": 0, "validation_errors": [] }, "endpoints": [], "test_cases": [] } def load_specification(self): """Load and parse OpenAPI/Swagger specification.""" if not self.spec_file.exists(): print(f"Error: Specification file '{self.spec_file}' does not exist", file=sys.stderr) sys.exit(1) try: content = self.spec_file.read_text() if self.spec_file.suffix.lower() in ['.yaml', '.yml']: self.spec = yaml.safe_load(content) else: self.spec = json.loads(content) except yaml.YAMLError as e: print(f"Error: Invalid YAML in specification file: {e}", file=sys.stderr) sys.exit(1) except json.JSONDecodeError as e: print(f"Error: Invalid JSON in specification file: {e}", file=sys.stderr) sys.exit(1) except Exception as e: print(f"Error: Failed to read specification file: {e}", file=sys.stderr) sys.exit(1) # Check OpenAPI version if 'openapi' in self.spec: version = self.spec['openapi'] if not version.startswith('3.0') and not version.startswith('3.1'): print(f"Warning: OpenAPI version {version} may not be fully supported", file=sys.stderr) elif 'swagger' in self.spec: version = self.spec['swagger'] if not version.startswith('2.0'): print(f"Warning: Swagger version {version} may not be fully supported", file=sys.stderr) else: print("Warning: Specification does not appear to be OpenAPI or Swagger", file=sys.stderr) def get_paths(self) -> Dict[str, Dict]: """Extract paths from specification.""" if not self.spec or 'paths' not in self.spec: return {} paths = self.spec['paths'] # Filter by endpoints if specified if self.endpoints: filtered_paths = {} for endpoint in self.endpoints: if endpoint in paths: filtered_paths[endpoint] = paths[endpoint] return filtered_paths return paths def get_methods_for_path(self, path_spec: Dict) -> List[str]: """Get HTTP methods for a path.""" methods = [] for method in ['get', 'post', 'put', 'patch', 'delete', 'head', 'options']: if method in path_spec: methods.append(method.upper()) # Filter by methods if specified if self.methods: methods = [m for m in methods if m in [meth.upper() for meth in self.methods]] return methods def generate_sample_data(self, schema: Dict) -> Any: """Generate sample data based on JSON schema.""" if 'type' not in schema: return None schema_type = schema['type'] if schema_type == 'string': if 'enum' in schema: return schema['enum'][0] if 'format' == 'email': return 'test@example.com' if 'format' == 'date': return '2024-01-01' return 'sample_string' elif schema_type == 'integer': return 42 elif schema_type == 'number': return 3.14 elif schema_type == 'boolean': return True elif schema_type == 'array': items_schema = schema.get('items', {}) return [self.generate_sample_data(items_schema)] elif schema_type == 'object': obj = {} if 'properties' in schema: for prop_name, prop_schema in schema['properties'].items(): if prop_name not in schema.get('required', []): continue # Skip optional for simplicity obj[prop_name] = self.generate_sample_data(prop_schema) return obj elif schema_type == 'null': return None return None def validate_schema(self, data: Any, schema: Dict) -> List[str]: """Validate data against JSON schema.""" errors = [] try: validate(instance=data, schema=schema) except ValidationError as e: errors.append(f"Schema validation error: {e.message}") except Exception as e: errors.append(f"Validation error: {str(e)}") return errors def test_endpoint(self, path: str, method: str, operation: Dict) -> Dict[str, Any]: """Test a single endpoint.""" result = { "path": path, "method": method, "status": "unknown", "status_code": None, "response_time_ms": None, "validations": { "status_code": False, "response_schema": False, "headers": False }, "errors": [] } # Build URL url = urljoin(self.base_url, path) # Prepare request headers = {'Content-Type': 'application/json'} if self.auth_token: headers['Authorization'] = f'Bearer {self.auth_token}' # Prepare request body if needed data = None if method in ['POST', 'PUT', 'PATCH']: request_body = operation.get('requestBody', {}) if request_body: content = request_body.get('content', {}) json_content = content.get('application/json', {}) if json_content and 'schema' in json_content: data = self.generate_sample_data(json_content['schema']) # Make request try: start_time = time.time() response = requests.request( method=method, url=url, headers=headers, json=data, timeout=self.timeout ) response_time = (time.time() - start_time) * 1000 result["status_code"] = response.status_code result["response_time_ms"] = int(response_time) # Check expected status codes expected_statuses = list(operation.get('responses', {}).keys()) if str(response.status_code) in expected_statuses: result["validations"]["status_code"] = True result["status"] = "passed" else: result["validations"]["status_code"] = False result["status"] = "failed" result["errors"].append( f"Unexpected status code {response.status_code}, expected one of: {expected_statuses}" ) # Validate response schema if enabled if self.validate_response and response.status_code < 400: response_spec = operation.get('responses', {}).get(str(response.status_code), {}) content = response_spec.get('content', {}) json_content = content.get('application/json', {}) if json_content and 'schema' in json_content: try: response_data = response.json() schema_errors = self.validate_schema(response_data, json_content['schema']) if not schema_errors: result["validations"]["response_schema"] = True else: result["validations"]["response_schema"] = False result["errors"].extend(schema_errors) except json.JSONDecodeError: result["errors"].append("Response is not valid JSON") except Exception as e: result["errors"].append(f"Schema validation error: {str(e)}") except requests.exceptions.Timeout: result["status"] = "error" result["errors"].append(f"Request timeout after {self.timeout} seconds") except requests.exceptions.ConnectionError: result["status"] = "error" result["errors"].append("Connection error - could not reach server") except Exception as e: result["status"] = "error" result["errors"].append(f"Request error: {str(e)}") return result def validate_contracts(self): """Validate all API contracts.""" paths = self.get_paths() self.results["summary"]["total_endpoints"] = sum( len(self.get_methods_for_path(path_spec)) for path_spec in paths.values() ) for path, path_spec in paths.items(): methods = self.get_methods_for_path(path_spec) for method in methods: operation = path_spec[method.lower()] result = self.test_endpoint(path, method, operation) self.results["endpoints"].append(result) self.results["summary"]["tested_endpoints"] += 1 if result["status"] == "passed": self.results["summary"]["passed"] += 1 elif result["status"] == "failed": self.results["summary"]["failed"] += 1 self.results["summary"]["validation_errors"].append({ "endpoint": path, "method": method, "status_code": result["status_code"], "error_type": "validation", "message": "; ".join(result["errors"]) if result["errors"] else "Validation failed" }) else: self.results["summary"]["errors"] += 1 # Generate test cases if requested if self.generate_tests: self.generate_test_cases() def generate_test_cases(self): """Generate test cases for endpoints.""" paths = self.get_paths() for path, path_spec in paths.items(): methods = self.get_methods_for_path(path_spec) for method in methods: operation = path_spec[method.lower()] test_case = { "endpoint": path, "method": method, "url": urljoin(self.base_url, path), "expected_status": list(operation.get('responses', {}).keys())[0] if operation.get('responses') else "200", "request_body": None, "headers": {} } if method in ['POST', 'PUT', 'PATCH']: request_body = operation.get('requestBody', {}) if request_body: content = request_body.get('content', {}) json_content = content.get('application/json', {}) if json_content and 'schema' in json_content: test_case["request_body"] = self.generate_sample_data(json_content['schema']) if self.auth_token: test_case["headers"]["Authorization"] = f"Bearer {self.auth_token}" self.results["test_cases"].append(test_case) def generate_json_output(self): """Generate JSON output.""" with open(self.output_file, 'w') as f: json.dump(self.results, f, indent=2) def generate_markdown_output(self): """Generate Markdown output.""" lines = ["# API Contract Validation Report\n\n"] # Summary summary = self.results["summary"] lines.append("## Summary\n\n") lines.append(f"- **Total Endpoints**: {summary['total_endpoints']}\n") lines.append(f"- **Tested Endpoints**: {summary['tested_endpoints']}\n") lines.append(f"- **Passed**: {summary['passed']}\n") lines.append(f"- **Failed**: {summary['failed']}\n") lines.append(f"- **Errors**: {summary['errors']}\n\n") # Endpoints if self.results["endpoints"]: lines.append("## Endpoint Results\n\n") for endpoint in self.results["endpoints"]: status_icon = "✅" if endpoint["status"] == "passed" else "❌" lines.append(f"### {status_icon} {endpoint['method']} {endpoint['path']}\n\n") lines.append(f"- **Status**: {endpoint['status']}\n") if endpoint["status_code"]: lines.append(f"- **Status Code**: {endpoint['status_code']}\n") if endpoint["response_time_ms"]: lines.append(f"- **Response Time**: {endpoint['response_time_ms']} ms\n") if endpoint["errors"]: lines.append("- **Errors**:\n") for error in endpoint["errors"]: lines.append(f" - {error}\n") lines.append("\n") with open(self.output_file, 'w') as f: f.writelines(lines) def generate_html_output(self): """Generate HTML output.""" summary = self.results["summary"] html = f"""
Total Endpoints: {summary['total_endpoints']}
Tested: {summary['tested_endpoints']}
Passed: {summary['passed']}
Failed: {summary['failed']}
Errors: {summary['errors']}