File size: 10,617 Bytes
223a8c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
from typing import List, Dict, Any
from datetime import datetime

class APIDocGenerator:
    """Auto-generate API documentation for databases"""
    
    def generate_docs(self, database: str, tables: List[Dict], user_store) -> Dict[str, Any]:
        """Generate complete API documentation for a database"""
        try:
            from app.schema_manager import schema_manager
            
            docs = {
                'database': database,
                'generated_at': datetime.utcnow().isoformat(),
                'base_url': '/api',
                'authentication': self._get_auth_docs(),
                'endpoints': []
            }
            
            # Generate endpoints for each table
            for table_info in tables:
                if table_info.get('database') == database:
                    table_name = table_info['table']
                    schema = schema_manager.get(database, table_name, user_store)
                    
                    table_docs = self._generate_table_endpoints(database, table_name, schema)
                    docs['endpoints'].extend(table_docs)
            
            # Add database-level endpoints
            docs['endpoints'].extend(self._get_database_endpoints(database))
            
            return {'ok': True, 'docs': docs}
            
        except Exception as e:
            return {'ok': False, 'error': str(e)}
    
    def _get_auth_docs(self) -> Dict[str, Any]:
        """Get authentication documentation"""
        return {
            'type': 'Bearer Token',
            'description': 'Use session token or API key for authentication',
            'methods': [
                {
                    'name': 'Session Token',
                    'header': 'Authorization: Bearer <session_token>',
                    'example': 'Authorization: Bearer abc123xyz'
                },
                {
                    'name': 'API Key',
                    'headers': {
                        'X-Api-Key': '<api_key>',
                        'X-Secret-Key': '<secret_key>'
                    },
                    'example': {
                        'X-Api-Key': 'cDb_abc123',
                        'X-Secret-Key': 'secret-xyz-789'
                    }
                }
            ]
        }
    
    def _generate_table_endpoints(self, database: str, table: str, schema: Dict) -> List[Dict]:
        """Generate CRUD endpoints for a table"""
        columns = schema.get('columns', [])
        column_names = [col['name'] for col in columns]
        
        # Sample row for examples
        sample_row = {col['name']: self._get_sample_value(col['type']) for col in columns}
        
        endpoints = [
            # List rows
            {
                'method': 'GET',
                'path': f'/rows/{database}/{table}',
                'description': f'Get rows from {table}',
                'parameters': [
                    {'name': 'limit', 'type': 'integer', 'default': 100, 'description': 'Max rows to return'},
                    {'name': 'offset', 'type': 'integer', 'default': 0, 'description': 'Offset for pagination'}
                ],
                'response': {
                    'type': 'array',
                    'example': [sample_row]
                },
                'curl_example': f'curl -H "Authorization: Bearer $TOKEN" {self._get_base_url()}/rows/{database}/{table}?limit=10'
            },
            
            # Create row
            {
                'method': 'POST',
                'path': f'/rows/{database}/{table}',
                'description': f'Insert a new row into {table}',
                'body': {
                    'type': 'object',
                    'properties': {col['name']: {'type': col['type']} for col in columns},
                    'example': sample_row
                },
                'response': {
                    'type': 'object',
                    'example': {'ok': True, 'rows': 1}
                },
                'curl_example': f'''curl -X POST -H "Authorization: Bearer $TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{self._json_example(sample_row)}' \\
  {self._get_base_url()}/rows/{database}/{table}'''
            },
            
            # Update row
            {
                'method': 'PUT',
                'path': f'/rows/{database}/{table}/{{id_field}}/{{id_value}}',
                'description': f'Update a row in {table}',
                'parameters': [
                    {'name': 'id_field', 'type': 'string', 'description': 'Column name to identify row'},
                    {'name': 'id_value', 'type': 'string', 'description': 'Value to match'}
                ],
                'body': {
                    'type': 'object',
                    'description': 'Fields to update',
                    'example': {column_names[0]: sample_row[column_names[0]]} if column_names else {}
                },
                'response': {
                    'type': 'object',
                    'example': {'ok': True, 'rows': 1}
                },
                'curl_example': f'''curl -X PUT -H "Authorization: Bearer $TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{{"name": "Updated Name"}}' \\
  {self._get_base_url()}/rows/{database}/{table}/id/123'''
            },
            
            # Delete row
            {
                'method': 'DELETE',
                'path': f'/rows/{database}/{table}/{{id_field}}/{{id_value}}',
                'description': f'Delete a row from {table}',
                'parameters': [
                    {'name': 'id_field', 'type': 'string', 'description': 'Column name to identify row'},
                    {'name': 'id_value', 'type': 'string', 'description': 'Value to match'}
                ],
                'response': {
                    'type': 'object',
                    'example': {'ok': True, 'rows': 1}
                },
                'curl_example': f'curl -X DELETE -H "Authorization: Bearer $TOKEN" {self._get_base_url()}/rows/{database}/{table}/id/123'
            }
        ]
        
        return endpoints
    
    def _get_database_endpoints(self, database: str) -> List[Dict]:
        """Get database-level endpoints"""
        return [
            {
                'method': 'POST',
                'path': '/sql',
                'description': 'Execute custom SQL query',
                'body': {
                    'type': 'object',
                    'properties': {
                        'sql': {'type': 'string', 'description': 'SQL query to execute'}
                    },
                    'example': {'sql': f'SELECT * FROM {database}.table_name LIMIT 10'}
                },
                'response': {
                    'type': 'object',
                    'example': {'ok': True, 'data': [], 'rows': 0}
                },
                'curl_example': f'''curl -X POST -H "Authorization: Bearer $TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{{"sql": "SELECT * FROM {database}.table_name LIMIT 10"}}' \\
  {self._get_base_url()}/sql'''
            }
        ]
    
    def _get_sample_value(self, col_type: str) -> Any:
        """Get sample value for column type"""
        type_upper = col_type.upper()
        
        if 'INT' in type_upper:
            return 123
        elif 'FLOAT' in type_upper or 'DOUBLE' in type_upper or 'DECIMAL' in type_upper:
            return 123.45
        elif 'BOOL' in type_upper:
            return True
        elif 'DATE' in type_upper:
            return '2024-01-15'
        elif 'TIME' in type_upper:
            return '14:30:00'
        else:
            return 'sample_value'
    
    def _json_example(self, obj: Dict) -> str:
        """Format JSON example"""
        import json
        return json.dumps(obj, indent=2)
    
    def _get_base_url(self) -> str:
        """Get base API URL"""
        return 'https://your-space.hf.space/api'
    
    def generate_sdk_examples(self, database: str, table: str) -> Dict[str, str]:
        """Generate SDK examples in multiple languages"""
        return {
            'python': f'''import requests

API_URL = "https://your-space.hf.space/api"
TOKEN = "your_token_here"

# List rows
response = requests.get(
    f"{{API_URL}}/rows/{database}/{table}",
    headers={{"Authorization": f"Bearer {{TOKEN}}"}}
)
data = response.json()
print(data)

# Insert row
new_row = {{"name": "John", "email": "john@example.com"}}
response = requests.post(
    f"{{API_URL}}/rows/{database}/{table}",
    headers={{"Authorization": f"Bearer {{TOKEN}}"}},
    json=new_row
)
print(response.json())''',
            
            'javascript': f'''const API_URL = "https://your-space.hf.space/api";
const TOKEN = "your_token_here";

// List rows
const response = await fetch(`${{API_URL}}/rows/{database}/{table}`, {{
  headers: {{ Authorization: `Bearer ${{TOKEN}}` }}
}});
const data = await response.json();
console.log(data);

// Insert row
const newRow = {{ name: "John", email: "john@example.com" }};
const insertResponse = await fetch(`${{API_URL}}/rows/{database}/{table}`, {{
  method: "POST",
  headers: {{
    Authorization: `Bearer ${{TOKEN}}`,
    "Content-Type": "application/json"
  }},
  body: JSON.stringify(newRow)
}});
console.log(await insertResponse.json());''',
            
            'php': f'''<?php
$apiUrl = "https://your-space.hf.space/api";
$token = "your_token_here";

// List rows
$ch = curl_init("$apiUrl/rows/{database}/{table}");
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
print_r($data);

// Insert row
$newRow = ["name" => "John", "email" => "john@example.com"];
$ch = curl_init("$apiUrl/rows/{database}/{table}");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $token",
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($newRow));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
print_r(json_decode($response, true));
?>''',
            
            'curl': f'''# List rows
curl -H "Authorization: Bearer $TOKEN" \\
  https://your-space.hf.space/api/rows/{database}/{table}

# Insert row
curl -X POST -H "Authorization: Bearer $TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{{"name": "John", "email": "john@example.com"}}' \\
  https://your-space.hf.space/api/rows/{database}/{table}'''
        }

api_doc_generator = APIDocGenerator()