""" Interactive API Documentation with OpenAPI 3.0 Enhanced developer experience with comprehensive docs """ from typing import Any, Dict, List from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from fastapi.responses import HTMLResponse from core.logging.advanced_logging import structured_logger class EnhancedAPIDocumentation: """Enhanced API documentation with interactive features""" def __init__(self, app: FastAPI): self.app = app self.logger = structured_logger self.custom_examples = {} self.api_insights = {} def add_custom_examples(self, endpoint: str, examples: Dict[str, Any]): """Add custom examples for API endpoints""" self.custom_examples[endpoint] = examples def generate_enhanced_openapi(self) -> Dict[str, Any]: """Generate enhanced OpenAPI specification""" # Get base OpenAPI spec openapi_schema = get_openapi( title=self.app.title, version=self.app.version, description=self.app.description, routes=self.app.routes, ) # Enhance with custom metadata openapi_schema["info"]["contact"] = { "name": "Zenith Fraud Detection Platform", "email": "support@zenith-fraud.com", "url": "https://zenith-fraud.com" } openapi_schema["info"]["license"] = { "name": "Enterprise License", "url": "https://zenith-fraud.com/license" } openapi_schema["info"]["x-logo"] = { "url": "https://zenith-fraud.com/logo.png", "altText": "Zenith Fraud Detection Platform" } # Add security schemes openapi_schema["components"]["securitySchemes"] = { "bearerAuth": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT", "description": "JWT Authorization header using the Bearer scheme" }, "apiKey": { "type": "apiKey", "in": "header", "name": "X-API-Key", "description": "API Key for service-to-service authentication" } } # Add global security openapi_schema["security"] = [ {"bearerAuth": []}, {"apiKey": []} ] # Enhance paths with examples and metadata if "paths" in openapi_schema: for path, methods in openapi_schema["paths"].items(): for method, operation in methods.items(): if method.upper() in ["GET", "POST", "PUT", "DELETE", "PATCH"]: # Add custom examples endpoint_key = f"{method.upper()} {path}" if endpoint_key in self.custom_examples: examples = self.custom_examples[endpoint_key] if "requestBody" not in operation and "parameters" in operation: # Add query parameter examples for param in operation.get("parameters", []): param_name = param.get("name") if param_name in examples: param["example"] = examples[param_name] # Add response examples if "responses" in operation: for status_code, response in operation["responses"].items(): if status_code == "200" and "content" in response: for content_type, content in response["content"].items(): if content_type == "application/json": # Add success response examples content["example"] = self._generate_response_example(operation, status_code) # Add operation metadata operation["x-code-samples"] = self._generate_code_samples(path, method.upper(), operation) return openapi_schema def _generate_response_example(self, operation: Dict[str, Any], status_code: str) -> Dict[str, Any]: """Generate response examples for documentation""" operation_id = operation.get("operationId", "") if "case" in operation_id.lower(): if "list" in operation_id.lower(): return { "cases": [ { "id": "case_12345", "title": "Suspicious Transaction Pattern", "status": "investigating", "priority": "high", "risk_score": 85.5, "created_at": "2024-01-15T10:30:00Z", "assignee": "investigator@example.com" } ], "total": 1, "page": 1, "page_size": 20 } elif "create" in operation_id.lower(): return { "id": "case_12345", "title": "New Suspicious Activity", "status": "open", "priority": "medium", "created_at": "2024-01-15T10:30:00Z", "message": "Case created successfully" } elif "auth" in operation_id.lower(): if "login" in operation_id.lower(): return { "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", "token_type": "bearer", "expires_in": 3600, "user": { "id": "user_123", "email": "user@example.com", "role": "investigator" } } # Default example return {"message": "Operation completed successfully"} def _generate_code_samples(self, path: str, method: str, operation: Dict[str, Any]) -> List[Dict[str, Any]]: """Generate code samples for different languages""" samples = [] # Python sample python_sample = f'''import requests url = "https://api.zenith-fraud.com{path}" headers = {{ "Authorization": "Bearer YOUR_JWT_TOKEN", "Content-Type": "application/json" }} response = requests.{method.lower()}(url, headers=headers) print(response.json())''' samples.append({ "lang": "python", "source": python_sample }) # JavaScript sample js_sample = f'''const response = await fetch('https://api.zenith-fraud.com{path}', {{ method: '{method}', headers: {{ 'Authorization': 'Bearer YOUR_JWT_TOKEN', 'Content-Type': 'application/json' }} }}); const data = await response.json(); console.log(data);''' samples.append({ "lang": "javascript", "source": js_sample }) # cURL sample curl_sample = f'''curl -X {method} \\ https://api.zenith-fraud.com{path} \\ -H "Authorization: Bearer YOUR_JWT_TOKEN" \\ -H "Content-Type: application/json"''' samples.append({ "lang": "curl", "source": curl_sample }) return samples class InteractiveDocumentation: """Interactive documentation with live API testing""" def __init__(self, app: FastAPI): self.app = app self.enhanced_docs = EnhancedAPIDocumentation(app) def get_enhanced_swagger_ui_html(self) -> HTMLResponse: """Get enhanced Swagger UI with custom features""" html_content = f"""
Version: {self.app.version}
Environment: Development
Enterprise API Reference Documentation