svyas113 commited on
Commit
cd9f831
·
1 Parent(s): c617332

Update project with API client and documentation

Browse files
Files changed (2) hide show
  1. README.md +118 -1
  2. dynamic_api_client.py +428 -0
README.md CHANGED
@@ -1,3 +1,120 @@
1
  ---
2
  sdk: gradio
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  sdk: gradio
3
+ ---
4
+
5
+ # API Data Connector and Client
6
+
7
+ This project contains two main Python scripts:
8
+ 1. `app.py`: A Gradio-based web application for selecting API endpoints from a specification and generating schema files (`_datasource_plugin_meta.json` and `_default_schema.orx`).
9
+ 2. `dynamic_api_client.py`: A command-line tool to interactively call API endpoints based on an OpenAPI specification.
10
+
11
+ ## `dynamic_api_client.py` - Standalone API Client
12
+
13
+ This script allows you to dynamically connect to and call APIs defined by an OpenAPI (Swagger) specification.
14
+
15
+ ### Features
16
+
17
+ * Parses local or remote OpenAPI (JSON or YAML) specification files.
18
+ * Automatically detects server URLs.
19
+ * Determines API security requirements (API Key, HTTP Basic/Bearer, OAuth2 Client Credentials).
20
+ * Prompts the user for necessary credentials.
21
+ * Lists available API endpoints for user selection.
22
+ * Prompts for required parameters (path, query, header, request body).
23
+ * Makes API calls using the `requests` library.
24
+ * Displays API responses.
25
+ * Includes a fallback minimal parser if `api_schema_generatorV5.py` is not found (for basic functionality).
26
+
27
+ ### Prerequisites
28
+
29
+ * Python 3.7+
30
+ * `requests` library (`pip install requests`)
31
+ * `PyYAML` library (`pip install pyyaml`)
32
+ * (Optional but recommended) `api_schema_generatorV5.py` in the same directory or Python path for full parsing capabilities.
33
+
34
+ ### Usage
35
+
36
+ 1. **Run from the command line:**
37
+ ```bash
38
+ python dynamic_api_client.py <path_or_url_to_api_spec>
39
+ ```
40
+ Replace `<path_or_url_to_api_spec>` with the actual file path or URL to your OpenAPI specification file (e.g., `openapi.json`, `swagger.yaml`, `https://api.example.com/openapi.json`).
41
+
42
+ 2. **Follow the prompts:**
43
+ * If the base URL cannot be determined, you'll be asked to enter it.
44
+ * The script will identify the required authentication method. Enter your credentials when prompted.
45
+ * A list of available endpoints will be displayed. Enter the numbers of the endpoints you wish to call, separated by commas.
46
+ * For each selected endpoint, provide values for any required parameters.
47
+ * The script will then make the API calls and display the responses.
48
+
49
+ ### Example
50
+
51
+ ```bash
52
+ python dynamic_api_client.py ./my_api_spec.yaml
53
+ ```
54
+
55
+ ### Notes
56
+
57
+ * **OAuth2 Support:** Currently, only the Client Credentials flow is implemented for OAuth2. The script will attempt to fetch the token automatically.
58
+ * **Parameter Handling:** The script prompts for path, query, and header parameters. For request bodies, it currently supports raw JSON input and URL-encoded form data.
59
+ * **$ref Resolution:**
60
+ * If `api_schema_generatorV5.py` is available and the spec is a local file, it will be used for more robust parsing, including some `$ref` resolutions within its capabilities.
61
+ * The built-in minimal parser has limited `$ref` resolution (primarily for top-level components like security schemes). Complex nested `$ref`s, especially within parameters or request bodies, might not be fully resolved by the minimal parser.
62
+ * **Security:** Be cautious when entering sensitive credentials. The script uses `input()` for passwords, which might be visible on screen or in shell history depending on your terminal configuration.
63
+
64
+ ## `app.py` - API Schema Generator UI
65
+
66
+ This Gradio application provides a user interface to:
67
+ * Load API specifications (Okta, SailPoint IdentityNow, SailPoint IIQ, or custom URLs).
68
+ * Browse and select API endpoints (GET, POST, or ALL).
69
+ * Generate `_datasource_plugin_meta.json` and `_default_schema.orx` files based on selected endpoints.
70
+ * Download the generated files as a ZIP archive.
71
+
72
+ Refer to the comments and structure within `app.py` for details on its operation with Gradio.
73
+
74
+ ### Running `app.py`
75
+
76
+ ```bash
77
+ python app.py
78
+ ```
79
+ This will typically launch a web server, and you can access the UI in your browser (usually at `http://127.0.0.1:7860`).
80
+
81
+ ## Potential Integration of `dynamic_api_client.py` with `app.py`
82
+
83
+ While `dynamic_api_client.py` is currently a standalone CLI tool, its core logic for parsing API specifications, handling authentication, and making API calls could be integrated into `app.py` or a similar Gradio application to provide a UI for direct API interaction.
84
+
85
+ Here are some conceptual ideas for integration:
86
+
87
+ 1. **Add an "API Call" Tab/Section to `app.py`:**
88
+ * After loading an API specification and selecting endpoints (as `app.py` already does for schema generation), a new section could allow the user to trigger calls to these selected endpoints.
89
+ * The UI would need to:
90
+ * Dynamically generate input fields for required authentication details based on the parsed `securitySchemes` (similar to how `dynamic_api_client.py` prompts for them).
91
+ * For each selected endpoint, dynamically generate input fields for its parameters (path, query, header, body).
92
+ * A "Call API" button would trigger the request.
93
+ * Display the API response (status code, headers, body) in the UI.
94
+
95
+ 2. **Refactor Core Logic into Reusable Functions/Classes:**
96
+ * The API parsing, authentication handling, parameter collection, and request-making logic from `dynamic_api_client.py` could be refactored into functions or classes within a utility module (e.g., `api_interaction_utils.py`).
97
+ * Both `dynamic_api_client.py` (for CLI use) and `app.py` (for UI use) could then import and use this shared module. This promotes code reuse and consistency.
98
+
99
+ 3. **State Management in Gradio:**
100
+ * Gradio's `gr.State` would be crucial for managing API specification data, authentication credentials (securely, if possible, though browser-based storage has limitations), selected endpoints, and parameter values across interactions.
101
+
102
+ 4. **Workflow:**
103
+ * User loads API spec in `app.py`.
104
+ * `app.py` parses the spec (potentially using `ApiSchemaGeneratorV5` or the refactored utility module).
105
+ * User navigates to an "API Interaction" or "Test Endpoint" section.
106
+ * UI prompts for authentication based on the spec.
107
+ * User selects an endpoint.
108
+ * UI prompts for parameters for that endpoint.
109
+ * User clicks "Send Request".
110
+ * The backend (Gradio event handler) uses the refactored logic to construct and send the API request.
111
+ * The response is displayed in the UI.
112
+
113
+ ### Challenges and Considerations for Integration:
114
+
115
+ * **Security of Credentials:** Handling API keys, passwords, and tokens in a web UI requires careful consideration. Storing them in `gr.State` might be acceptable for local development, but for a deployed application, more secure methods would be needed (e.g., backend secrets management, temporary session storage).
116
+ * **Asynchronous Operations:** API calls can take time. Gradio's handling of long-running operations and providing feedback (loading indicators) would be important.
117
+ * **Complex Request Bodies:** Building a UI to dynamically construct complex JSON or XML request bodies based on a schema can be challenging but powerful.
118
+ * **Error Handling:** Robust error handling and clear feedback to the user in the UI are essential.
119
+
120
+ This integration would transform `app.py` from just a schema generator into a more comprehensive API development and testing tool.
dynamic_api_client.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import yaml
4
+ import argparse
5
+ import os
6
+ from urllib.parse import urljoin, urlparse
7
+
8
+ # Attempt to import ApiSchemaGeneratorV5, or define a minimal version if not found
9
+ try:
10
+ from api_schema_generatorV5 import ApiSchemaGeneratorV5
11
+ except ImportError:
12
+ print("Warning: api_schema_generatorV5.py not found. Using minimal local parser.")
13
+ # Define a minimal parser if ApiSchemaGeneratorV5 is not available
14
+ # This is a simplified version for basic functionality
15
+ class MinimalApiParser:
16
+ def __init__(self, api_spec_url: str):
17
+ self.api_spec_url = api_spec_url
18
+ self.api_spec = None
19
+ self.servers = []
20
+ self.security_schemes = {}
21
+ self.global_security = []
22
+ self.paths = {}
23
+
24
+ def fetch_api_spec(self):
25
+ try:
26
+ if self.api_spec_url.startswith(('http://', 'https://')):
27
+ response = requests.get(self.api_spec_url)
28
+ response.raise_for_status()
29
+ content = response.text
30
+ else:
31
+ with open(self.api_spec_url, 'r', encoding='utf-8') as f:
32
+ content = f.read()
33
+
34
+ try:
35
+ self.api_spec = json.loads(content)
36
+ except json.JSONDecodeError:
37
+ self.api_spec = yaml.safe_load(content)
38
+ return True
39
+ except Exception as e:
40
+ print(f"Error fetching/parsing API specification: {e}")
41
+ return False
42
+
43
+ def extract_data(self):
44
+ if not self.api_spec:
45
+ if not self.fetch_api_spec():
46
+ return False
47
+
48
+ self.servers = self.api_spec.get('servers', [])
49
+ self.security_schemes = self.api_spec.get('components', {}).get('securitySchemes', {})
50
+ self.global_security = self.api_spec.get('security', [])
51
+ self.paths = self.api_spec.get('paths', {})
52
+ return True
53
+
54
+ ApiSchemaGeneratorV5 = MinimalApiParser # Use the minimal parser
55
+
56
+ def get_input(prompt_message, default_value=None):
57
+ if default_value:
58
+ return input(f"{prompt_message} [{default_value}]: ") or default_value
59
+ return input(f"{prompt_message}: ")
60
+
61
+ def get_base_url(servers, api_spec_path):
62
+ suggested_url = None
63
+ if servers:
64
+ # Prefer HTTPS if available
65
+ https_server = next((s['url'] for s in servers if s['url'].startswith('https://')), None)
66
+ if https_server:
67
+ suggested_url = https_server.rstrip('/')
68
+ elif servers[0].get('url'):
69
+ suggested_url = servers[0]['url'].rstrip('/')
70
+
71
+ if suggested_url:
72
+ print(f"A server URL was found in the API specification: {suggested_url}")
73
+ return get_input("Please enter the base API URL (e.g., https://api.example.com/v1)", default_value=suggested_url)
74
+ else:
75
+ if os.path.exists(api_spec_path): # Check if it's a local file to provide context for the warning
76
+ print("Warning: No 'servers' block found in the API specification.")
77
+ return get_input("Please enter the base API URL (e.g., https://api.example.com/v1)")
78
+
79
+ def get_auth_details(security_schemes, active_security_requirements):
80
+ """
81
+ Determines the authentication method and prompts user for credentials.
82
+ Uses the first active security requirement.
83
+ """
84
+ auth_config = {}
85
+ if not active_security_requirements:
86
+ print("No active security requirements found for this endpoint/API. Proceeding without authentication.")
87
+ return auth_config
88
+
89
+ # Use the first security requirement listed
90
+ first_req_name = list(active_security_requirements[0].keys())[0]
91
+
92
+ if first_req_name not in security_schemes:
93
+ print(f"Warning: Security scheme '{first_req_name}' not defined in components.securitySchemes.")
94
+ return auth_config
95
+
96
+ scheme = security_schemes[first_req_name]
97
+ auth_type = scheme.get('type')
98
+ print(f"\n--- Authentication Required: {first_req_name} ({auth_type}) ---")
99
+
100
+ if auth_type == 'apiKey':
101
+ auth_config['type'] = 'apiKey'
102
+ auth_config['name'] = scheme.get('name')
103
+ auth_config['in'] = scheme.get('in')
104
+ auth_config['value'] = get_input(f"Enter API Key for '{auth_config['name']}' (in {auth_config['in']})")
105
+ elif auth_type == 'http':
106
+ http_scheme = scheme.get('scheme', '').lower()
107
+ auth_config['type'] = 'http'
108
+ auth_config['scheme'] = http_scheme
109
+ if http_scheme == 'basic':
110
+ username = get_input("Enter Basic Auth Username")
111
+ password = get_input("Enter Basic Auth Password", "") # nosec B105
112
+ auth_config['username'] = username
113
+ auth_config['password'] = password
114
+ elif http_scheme == 'bearer':
115
+ auth_config['token'] = get_input("Enter Bearer Token")
116
+ else:
117
+ print(f"Unsupported HTTP scheme: {http_scheme}")
118
+ elif auth_type == 'oauth2':
119
+ auth_config['type'] = 'oauth2'
120
+ # Simplified: For clientCredentials flow
121
+ flows = scheme.get('flows', {})
122
+ if 'clientCredentials' in flows:
123
+ auth_config['flow'] = 'clientCredentials'
124
+ cc_flow = flows['clientCredentials']
125
+ auth_config['token_url'] = get_input("Enter OAuth2 Token URL", cc_flow.get('tokenUrl'))
126
+ auth_config['client_id'] = get_input("Enter OAuth2 Client ID")
127
+ auth_config['client_secret'] = get_input("Enter OAuth2 Client Secret", "") # nosec B105
128
+ # Optionally, handle scopes
129
+ # scopes_available = cc_flow.get('scopes', {})
130
+ # if scopes_available:
131
+ # print("Available scopes:", scopes_available)
132
+ # auth_config['scope'] = get_input("Enter scopes (space-separated)", "")
133
+
134
+ # Fetch token
135
+ token_data = {
136
+ 'grant_type': 'client_credentials',
137
+ 'client_id': auth_config['client_id'],
138
+ 'client_secret': auth_config['client_secret'],
139
+ }
140
+ # if auth_config.get('scope'):
141
+ # token_data['scope'] = auth_config['scope']
142
+
143
+ try:
144
+ print(f"Attempting to fetch OAuth2 token from {auth_config['token_url']}...")
145
+ token_res = requests.post(auth_config['token_url'], data=token_data, timeout=10)
146
+ token_res.raise_for_status()
147
+ auth_config['token'] = token_res.json().get('access_token')
148
+ if auth_config['token']:
149
+ print("OAuth2 token obtained successfully.")
150
+ else:
151
+ print("Failed to obtain OAuth2 token. Check credentials and token URL.")
152
+ print("Response:", token_res.text)
153
+ except requests.exceptions.RequestException as e:
154
+ print(f"Error obtaining OAuth2 token: {e}")
155
+ else:
156
+ print(f"Unsupported OAuth2 flow. Only clientCredentials supported in this script.")
157
+ else:
158
+ print(f"Unsupported security scheme type: {auth_type}")
159
+
160
+ return auth_config
161
+
162
+ def select_endpoints(paths):
163
+ print("\n--- Available Endpoints ---")
164
+ endpoint_options = []
165
+ for path, methods in paths.items():
166
+ for method, details in methods.items():
167
+ # We are interested in callable methods like get, post, put, delete, patch
168
+ if method.lower() not in ['get', 'post', 'put', 'delete', 'patch', 'options', 'head', 'trace']:
169
+ continue # Skip parameters, $ref etc. at this level
170
+
171
+ summary = details.get('summary', 'No summary')
172
+ endpoint_options.append({
173
+ 'path': path,
174
+ 'method': method.upper(),
175
+ 'details': details
176
+ })
177
+ print(f"{len(endpoint_options)}. {method.upper()} {path} - {summary}")
178
+
179
+ if not endpoint_options:
180
+ print("No callable endpoints found in the specification.")
181
+ return []
182
+
183
+ selected_indices_str = get_input("Enter numbers of endpoints to call (comma-separated, e.g., 1,3): ")
184
+ selected_endpoints = []
185
+ try:
186
+ selected_indices = [int(i.strip()) - 1 for i in selected_indices_str.split(',')]
187
+ for index in selected_indices:
188
+ if 0 <= index < len(endpoint_options):
189
+ selected_endpoints.append(endpoint_options[index])
190
+ else:
191
+ print(f"Warning: Invalid endpoint number {index + 1} skipped.")
192
+ except ValueError:
193
+ print("Invalid input for endpoint selection.")
194
+ return selected_endpoints
195
+
196
+ def make_api_call(base_url, endpoint_info, auth_details, security_schemes):
197
+ path = endpoint_info['path']
198
+ method = endpoint_info['method']
199
+ details = endpoint_info['details']
200
+
201
+ print(f"\n--- Calling: {method} {path} ---")
202
+
203
+ # Determine active security for this endpoint
204
+ endpoint_security = details.get('security') # Endpoint specific
205
+ # If not defined at endpoint, it might fall back to global, handled by `auth_details` already if it was based on global.
206
+ # For simplicity, if endpoint_security is defined, we re-evaluate auth.
207
+ # This part could be more sophisticated to merge/override global.
208
+ # For now, if endpoint has `security`, we assume `auth_details` should be re-evaluated or specific.
209
+ # However, `get_auth_details` is called once globally. A more robust system would check per endpoint.
210
+ # Current `auth_details` is based on the *first* global or first scheme if no global.
211
+
212
+ headers = {'Accept': 'application/json'}
213
+ params = {}
214
+ data = None
215
+ json_payload = None
216
+
217
+ # Apply authentication
218
+ if auth_details:
219
+ if auth_details.get('type') == 'apiKey':
220
+ if auth_details.get('in') == 'header':
221
+ headers[auth_details['name']] = auth_details['value']
222
+ elif auth_details.get('in') == 'query':
223
+ params[auth_details['name']] = auth_details['value']
224
+ elif auth_details.get('type') == 'http':
225
+ if auth_details.get('scheme') == 'basic' and auth_details.get('username') is not None:
226
+ # Basic auth is handled by requests' `auth` parameter
227
+ pass
228
+ elif auth_details.get('scheme') == 'bearer' and auth_details.get('token'):
229
+ headers['Authorization'] = f"Bearer {auth_details['token']}"
230
+ elif auth_details.get('type') == 'oauth2' and auth_details.get('token'):
231
+ headers['Authorization'] = f"Bearer {auth_details['token']}"
232
+
233
+
234
+ # Collect parameters
235
+ path_params = {}
236
+ if 'parameters' in details:
237
+ for param_spec in details['parameters']:
238
+ # Resolve $ref if it's a reference to a component parameter
239
+ if '$ref' in param_spec:
240
+ ref_path = param_spec['$ref'].split('/')
241
+ if ref_path[0] == '#' and ref_path[1] == 'components' and ref_path[2] == 'parameters':
242
+ param_name_ref = ref_path[3]
243
+ # This requires having the full spec parsed, including components.parameters
244
+ # The minimal parser doesn't do this deeply. ApiSchemaGeneratorV5 would.
245
+ # For now, assume direct definition or skip complex $refs for parameters.
246
+ print(f"Skipping parameter with $ref: {param_spec['$ref']} (full $ref resolution for params not in minimal script)")
247
+ continue # Simplified handling
248
+ else: # Unrecognized $ref
249
+ print(f"Skipping parameter with unrecognized $ref: {param_spec['$ref']}")
250
+ continue
251
+
252
+ param_name = param_spec.get('name')
253
+ param_in = param_spec.get('in')
254
+ param_required = param_spec.get('required', False)
255
+ param_schema = param_spec.get('schema', {})
256
+ param_type = param_schema.get('type', 'string')
257
+ param_description = param_spec.get('description', '')
258
+
259
+ prompt_msg = f"Enter value for {param_in} parameter '{param_name}' ({param_type})"
260
+ if param_description:
261
+ prompt_msg += f" ({param_description})"
262
+ if param_required:
263
+ prompt_msg += " (required)"
264
+
265
+ user_value = get_input(prompt_msg, param_schema.get('default'))
266
+
267
+ if user_value or (param_required and not user_value): # Process if value given, or if required and no value (let API validate)
268
+ if not user_value and param_required:
269
+ print(f"Warning: Required parameter '{param_name}' not provided.")
270
+
271
+ if param_in == 'path':
272
+ path_params[param_name] = user_value
273
+ elif param_in == 'query':
274
+ params[param_name] = user_value
275
+ elif param_in == 'header':
276
+ headers[param_name] = user_value
277
+ # Other 'in' types (e.g., cookie) are less common for basic clients
278
+
279
+ # Substitute path parameters
280
+ request_path = path
281
+ for p_name, p_val in path_params.items():
282
+ request_path = request_path.replace(f"{{{p_name}}}", str(p_val))
283
+
284
+ full_url = urljoin(base_url.rstrip('/') + '/', request_path.lstrip('/'))
285
+
286
+
287
+ # Handle request body for POST, PUT, PATCH
288
+ if method in ['POST', 'PUT', 'PATCH']:
289
+ request_body_spec = details.get('requestBody')
290
+ if request_body_spec:
291
+ # Resolve $ref for requestBody
292
+ if '$ref' in request_body_spec:
293
+ ref_path = request_body_spec['$ref'].split('/')
294
+ if ref_path[0] == '#' and ref_path[1] == 'components' and ref_path[2] == 'requestBodies':
295
+ # This requires full spec parsing. Minimal script won't resolve this.
296
+ print(f"Skipping requestBody with $ref: {request_body_spec['$ref']} (full $ref resolution not in minimal script)")
297
+ request_body_spec = None # Cannot proceed with this $ref
298
+ else:
299
+ print(f"Skipping requestBody with unrecognized $ref: {request_body_spec['$ref']}")
300
+ request_body_spec = None
301
+
302
+
303
+ if request_body_spec and 'content' in request_body_spec:
304
+ content_types = request_body_spec['content']
305
+ if 'application/json' in content_types:
306
+ headers['Content-Type'] = 'application/json'
307
+ # Potentially build JSON based on schema, for now, raw JSON input
308
+ print("This endpoint expects a JSON request body.")
309
+ print(f"Schema hint: {json.dumps(content_types['application/json'].get('schema', {}), indent=2)}")
310
+ body_str = get_input("Enter JSON body as a single line string (or leave empty):")
311
+ if body_str:
312
+ try:
313
+ json_payload = json.loads(body_str)
314
+ except json.JSONDecodeError:
315
+ print("Invalid JSON provided for request body. Sending as raw string if possible or failing.")
316
+ data = body_str # Fallback for malformed JSON, might fail
317
+ elif 'application/x-www-form-urlencoded' in content_types:
318
+ headers['Content-Type'] = 'application/x-www-form-urlencoded'
319
+ print("This endpoint expects form data. Enter key=value pairs, one per line. End with an empty line.")
320
+ form_data = {}
321
+ while True:
322
+ line = get_input("key=value (or empty to finish): ")
323
+ if not line:
324
+ break
325
+ if '=' in line:
326
+ key, value = line.split('=', 1)
327
+ form_data[key.strip()] = value.strip()
328
+ else:
329
+ print("Invalid format. Use key=value.")
330
+ if form_data:
331
+ data = form_data
332
+ else:
333
+ print(f"Unsupported request body content type: {list(content_types.keys())[0]}. Please handle manually.")
334
+
335
+ # Make the request
336
+ try:
337
+ print(f"Requesting: {method} {full_url}")
338
+ print(f"Headers: {headers}")
339
+ if params: print(f"Query Params: {params}")
340
+ if json_payload: print(f"JSON Payload: {json.dumps(json_payload)}")
341
+ if data: print(f"Form Data: {data}")
342
+
343
+ current_auth = None
344
+ if auth_details.get('type') == 'http' and auth_details.get('scheme') == 'basic':
345
+ current_auth = (auth_details['username'], auth_details['password'])
346
+
347
+ response = requests.request(
348
+ method,
349
+ full_url,
350
+ headers=headers,
351
+ params=params,
352
+ json=json_payload,
353
+ data=data,
354
+ auth=current_auth,
355
+ timeout=30
356
+ )
357
+ print(f"\nResponse Status: {response.status_code}")
358
+
359
+ content_type = response.headers.get('Content-Type', '')
360
+ if 'application/json' in content_type:
361
+ try:
362
+ print("Response JSON:")
363
+ print(json.dumps(response.json(), indent=2))
364
+ except json.JSONDecodeError:
365
+ print("Response Content (not valid JSON):")
366
+ print(response.text)
367
+ else:
368
+ print("Response Content:")
369
+ print(response.text[:500] + "..." if len(response.text) > 500 else response.text)
370
+
371
+ except requests.exceptions.RequestException as e:
372
+ print(f"API call failed: {e}")
373
+
374
+ def main():
375
+ parser = argparse.ArgumentParser(description="Dynamic API client based on OpenAPI specification.")
376
+ parser.add_argument("spec_file", help="Path or URL to the OpenAPI (JSON or YAML) specification file.")
377
+ args = parser.parse_args()
378
+
379
+ # Use ApiSchemaGeneratorV5 if available and spec_file is a path, otherwise minimal parser
380
+ if os.path.exists(args.spec_file) and 'MinimalApiParser' not in str(ApiSchemaGeneratorV5):
381
+ # This assumes ApiSchemaGeneratorV5 takes api_spec_url and selected_endpoints
382
+ # We are not using selected_endpoints here for the initial parsing.
383
+ # The constructor of ApiSchemaGeneratorV5 is:
384
+ # __init__(self, api_spec_url: str, api_name: str = None, selected_endpoints: List[str] = None)
385
+ # We'll pass api_name=None and selected_endpoints=None for its internal use if any.
386
+ api_parser = ApiSchemaGeneratorV5(api_spec_url=args.spec_file)
387
+ api_parser.extract_api_info() # This populates self.api_spec, self.auth_info, self.endpoints etc.
388
+
389
+ # Adapt ApiSchemaGeneratorV5's attributes to what this script expects
390
+ spec_servers = api_parser.api_spec.get('servers', []) if api_parser.api_spec else []
391
+ spec_security_schemes = api_parser.auth_info if api_parser.auth_info else {}
392
+ # ApiSchemaGeneratorV5 doesn't directly expose global_security in a simple attribute after extract_api_info
393
+ # It's in api_parser.api_spec.get('security', [])
394
+ spec_global_security = api_parser.api_spec.get('security', []) if api_parser.api_spec else []
395
+ spec_paths = api_parser.endpoints if api_parser.endpoints else {}
396
+ else: # Minimal parser or URL
397
+ api_parser = MinimalApiParser(args.spec_file)
398
+ if not api_parser.extract_data():
399
+ return
400
+ spec_servers = api_parser.servers
401
+ spec_security_schemes = api_parser.security_schemes
402
+ spec_global_security = api_parser.global_security
403
+ spec_paths = api_parser.paths
404
+
405
+ base_api_url = get_base_url(spec_servers, args.spec_file)
406
+
407
+ # Determine active security requirements (global first)
408
+ # A more complex app would check endpoint-specific security overrides
409
+ active_sec_reqs = spec_global_security
410
+ if not active_sec_reqs and spec_security_schemes: # If no global, but schemes exist, pick first scheme
411
+ first_scheme_name = list(spec_security_schemes.keys())[0]
412
+ active_sec_reqs = [{first_scheme_name: []}] # Mimic structure of security requirements list
413
+ print(f"No global security requirements in spec. Using first defined scheme: {first_scheme_name}")
414
+
415
+ auth = get_auth_details(spec_security_schemes, active_sec_reqs)
416
+
417
+ selected = select_endpoints(spec_paths)
418
+ if not selected:
419
+ print("No endpoints selected. Exiting.")
420
+ return
421
+
422
+ for endpoint_data in selected:
423
+ # Note: make_api_call currently doesn't re-evaluate auth per endpoint.
424
+ # It uses the globally determined `auth`.
425
+ make_api_call(base_api_url, endpoint_data, auth, spec_security_schemes)
426
+
427
+ if __name__ == "__main__":
428
+ main()