|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Schema generation script for The Companies API Python SDK. |
| 4 | +""" |
| 5 | + |
| 6 | +import json |
| 7 | +import os |
| 8 | +import sys |
| 9 | +import subprocess |
| 10 | +from pathlib import Path |
| 11 | +import requests |
| 12 | + |
| 13 | + |
| 14 | +def fetch_openapi_schema() -> dict: |
| 15 | + """Fetch the OpenAPI schema from the API.""" |
| 16 | + version = os.getenv('TCA_API_VERSION', 'v2') |
| 17 | + api_url = os.getenv('TCA_API_URL', 'https://api.thecompaniesapi.com') |
| 18 | + schema_url = f"{api_url}/{version}/openapi" |
| 19 | + |
| 20 | + print(f"Pulling schema from: {schema_url}") |
| 21 | + |
| 22 | + try: |
| 23 | + response = requests.get(schema_url, timeout=30) |
| 24 | + response.raise_for_status() |
| 25 | + return response.json() |
| 26 | + except requests.RequestException as e: |
| 27 | + print(f"Error fetching schema: {e}") |
| 28 | + sys.exit(1) |
| 29 | + |
| 30 | + |
| 31 | +def extract_operations_map(schema: dict) -> dict: |
| 32 | + """Extract operations map from OpenAPI schema.""" |
| 33 | + operations = {} |
| 34 | + |
| 35 | + paths = schema.get('paths', {}) |
| 36 | + for path, path_operations in paths.items(): |
| 37 | + for method, operation in path_operations.items(): |
| 38 | + if method.lower() in ['get', 'post', 'put', 'patch', 'delete']: |
| 39 | + operation_id = operation.get('operationId') |
| 40 | + if operation_id: |
| 41 | + # Extract path parameters |
| 42 | + path_params = [] |
| 43 | + for param in operation.get('parameters', []): |
| 44 | + if param.get('in') == 'path': |
| 45 | + path_params.append(param.get('name')) |
| 46 | + |
| 47 | + operations[operation_id] = { |
| 48 | + 'path': path, |
| 49 | + 'method': method.lower(), |
| 50 | + 'pathParams': path_params |
| 51 | + } |
| 52 | + |
| 53 | + return operations |
| 54 | + |
| 55 | + |
| 56 | +def generate_pydantic_types(schema: dict, output_file: Path) -> None: |
| 57 | + """Generate Pydantic models from OpenAPI schema.""" |
| 58 | + print(f"Generating Pydantic types...") |
| 59 | + |
| 60 | + # Save schema to temporary file |
| 61 | + temp_schema_file = output_file.parent / 'temp_schema.json' |
| 62 | + with open(temp_schema_file, 'w', encoding='utf-8') as f: |
| 63 | + json.dump(schema, f, indent=2) |
| 64 | + |
| 65 | + try: |
| 66 | + # Use command line interface which is more stable |
| 67 | + cmd = [ |
| 68 | + 'datamodel-codegen', |
| 69 | + '--input', str(temp_schema_file), |
| 70 | + '--input-file-type', 'openapi', |
| 71 | + '--output', str(output_file), |
| 72 | + '--output-model-type', 'pydantic_v2.BaseModel', |
| 73 | + '--target-python-version', '3.9', |
| 74 | + '--use-title-as-name', |
| 75 | + ] |
| 76 | + |
| 77 | + result = subprocess.run(cmd, capture_output=True, text=True, check=True) |
| 78 | + print(f"Pydantic types written to: {output_file}") |
| 79 | + |
| 80 | + except subprocess.CalledProcessError as e: |
| 81 | + print(f"Error generating types: {e}") |
| 82 | + print(f"stdout: {e.stdout}") |
| 83 | + print(f"stderr: {e.stderr}") |
| 84 | + raise |
| 85 | + finally: |
| 86 | + # Clean up temporary file |
| 87 | + if temp_schema_file.exists(): |
| 88 | + temp_schema_file.unlink() |
| 89 | + |
| 90 | + |
| 91 | +def generate_operations_map_file(operations: dict, output_file: Path) -> None: |
| 92 | + """Generate operations map Python file.""" |
| 93 | + content = f'''""" |
| 94 | +Auto-generated operations map for The Companies API. |
| 95 | +This file is generated by scripts/generate_schema.py - do not edit manually. |
| 96 | +""" |
| 97 | +
|
| 98 | +from typing import Dict, List |
| 99 | +
|
| 100 | +# Operations map extracted from OpenAPI schema |
| 101 | +operations_map = {json.dumps(operations, indent=4)} |
| 102 | +
|
| 103 | +# Type alias for operations map |
| 104 | +OperationsMap = Dict[str, Dict[str, any]] |
| 105 | +''' |
| 106 | + |
| 107 | + with open(output_file, 'w', encoding='utf-8') as f: |
| 108 | + f.write(content) |
| 109 | + |
| 110 | + print(f"Operations map written to: {output_file}") |
| 111 | + |
| 112 | + |
| 113 | +def update_generated_init(generated_dir: Path) -> None: |
| 114 | + """Update __init__.py in generated directory to export main types.""" |
| 115 | + init_file = generated_dir / '__init__.py' |
| 116 | + |
| 117 | + content = '''""" |
| 118 | +Generated types and operations for The Companies API. |
| 119 | +""" |
| 120 | +
|
| 121 | +from .operations_map import operations_map, OperationsMap |
| 122 | +
|
| 123 | +try: |
| 124 | + # Import commonly used types - adjust as needed |
| 125 | + from .models import * |
| 126 | +except ImportError: |
| 127 | + # Handle case where models haven't been generated yet |
| 128 | + pass |
| 129 | +
|
| 130 | +__all__ = ['operations_map', 'OperationsMap'] |
| 131 | +''' |
| 132 | + |
| 133 | + with open(init_file, 'w', encoding='utf-8') as f: |
| 134 | + f.write(content) |
| 135 | + |
| 136 | + |
| 137 | +def main(): |
| 138 | + """Main function to update schema and generate types.""" |
| 139 | + # Get project root directory |
| 140 | + script_dir = Path(__file__).parent |
| 141 | + project_root = script_dir.parent |
| 142 | + generated_dir = project_root / 'src' / 'thecompaniesapi' / 'generated' |
| 143 | + |
| 144 | + # Create generated directory if it doesn't exist |
| 145 | + generated_dir.mkdir(exist_ok=True) |
| 146 | + |
| 147 | + # Fetch OpenAPI schema |
| 148 | + schema = fetch_openapi_schema() |
| 149 | + |
| 150 | + # Extract operations map |
| 151 | + operations = extract_operations_map(schema) |
| 152 | + print(f"Found {len(operations)} operations") |
| 153 | + |
| 154 | + # Generate Pydantic types |
| 155 | + types_file = generated_dir / 'models.py' |
| 156 | + generate_pydantic_types(schema, types_file) |
| 157 | + |
| 158 | + # Generate operations map |
| 159 | + operations_file = generated_dir / 'operations_map.py' |
| 160 | + generate_operations_map_file(operations, operations_file) |
| 161 | + |
| 162 | + # Update __init__.py |
| 163 | + update_generated_init(generated_dir) |
| 164 | + |
| 165 | + print("\n✨ Schema generation completed successfully!") |
| 166 | + print(f" 📁 Generated files in: {generated_dir}") |
| 167 | + print(f" 🔧 Operations: {len(operations)}") |
| 168 | + print("\n🚀 You can now use the generated types in your SDK!") |
| 169 | + |
| 170 | + |
| 171 | +if __name__ == '__main__': |
| 172 | + main() |
0 commit comments