api-mocker 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
api_mocker/recorder.py ADDED
@@ -0,0 +1,266 @@
1
+ import json
2
+ import time
3
+ from typing import Dict, List, Any, Optional, Callable
4
+ from dataclasses import dataclass, asdict
5
+ from datetime import datetime
6
+ import re
7
+
8
+ @dataclass
9
+ class RecordedRequest:
10
+ """Represents a recorded HTTP request."""
11
+ timestamp: str
12
+ method: str
13
+ path: str
14
+ headers: Dict[str, str]
15
+ body: Optional[Any]
16
+ response_status: int
17
+ response_headers: Dict[str, str]
18
+ response_body: Any
19
+ session_id: Optional[str] = None
20
+
21
+ class RequestRecorder:
22
+ """Records real API interactions for later replay as mocks."""
23
+
24
+ def __init__(self):
25
+ self.recorded_requests: List[RecordedRequest] = []
26
+ self.filters: List[Callable] = []
27
+ self.sensitive_patterns: List[str] = [
28
+ r'password',
29
+ r'token',
30
+ r'key',
31
+ r'secret',
32
+ r'auth'
33
+ ]
34
+
35
+ def add_filter(self, filter_func: Callable):
36
+ """Add a custom filter function."""
37
+ self.filters.append(filter_func)
38
+
39
+ def add_sensitive_pattern(self, pattern: str):
40
+ """Add a regex pattern for sensitive data."""
41
+ self.sensitive_patterns.append(pattern)
42
+
43
+ def record_request(self, request: RecordedRequest) -> bool:
44
+ """Record a request if it passes all filters."""
45
+ if self._should_record(request):
46
+ self._sanitize_request(request)
47
+ self.recorded_requests.append(request)
48
+ return True
49
+ return False
50
+
51
+ def _should_record(self, request: RecordedRequest) -> bool:
52
+ """Check if request should be recorded based on filters."""
53
+ for filter_func in self.filters:
54
+ if not filter_func(request):
55
+ return False
56
+ return True
57
+
58
+ def _sanitize_request(self, request: RecordedRequest):
59
+ """Remove sensitive information from request."""
60
+ # Sanitize headers
61
+ sanitized_headers = {}
62
+ for key, value in request.headers.items():
63
+ if not self._is_sensitive(key):
64
+ sanitized_headers[key] = value
65
+ else:
66
+ sanitized_headers[key] = "[REDACTED]"
67
+ request.headers = sanitized_headers
68
+
69
+ # Sanitize body if it's a string
70
+ if isinstance(request.body, str):
71
+ request.body = self._sanitize_string(request.body)
72
+ elif isinstance(request.body, dict):
73
+ request.body = self._sanitize_dict(request.body)
74
+
75
+ def _is_sensitive(self, key: str) -> bool:
76
+ """Check if a key contains sensitive information."""
77
+ key_lower = key.lower()
78
+ return any(re.search(pattern, key_lower) for pattern in self.sensitive_patterns)
79
+
80
+ def _sanitize_string(self, text: str) -> str:
81
+ """Sanitize sensitive data in a string."""
82
+ for pattern in self.sensitive_patterns:
83
+ text = re.sub(pattern, '[REDACTED]', text, flags=re.IGNORECASE)
84
+ return text
85
+
86
+ def _sanitize_dict(self, data: Dict) -> Dict:
87
+ """Sanitize sensitive data in a dictionary."""
88
+ sanitized = {}
89
+ for key, value in data.items():
90
+ if self._is_sensitive(key):
91
+ sanitized[key] = '[REDACTED]'
92
+ elif isinstance(value, dict):
93
+ sanitized[key] = self._sanitize_dict(value)
94
+ elif isinstance(value, str):
95
+ sanitized[key] = self._sanitize_string(value)
96
+ else:
97
+ sanitized[key] = value
98
+ return sanitized
99
+
100
+ def export_recording(self, file_path: str, format: str = 'json'):
101
+ """Export recorded requests to file."""
102
+ data = {
103
+ 'recorded_at': datetime.now().isoformat(),
104
+ 'requests': [asdict(req) for req in self.recorded_requests]
105
+ }
106
+
107
+ with open(file_path, 'w') as f:
108
+ if format.lower() == 'json':
109
+ json.dump(data, f, indent=2)
110
+ else:
111
+ # Could add other formats like YAML, CSV, etc.
112
+ json.dump(data, f, indent=2)
113
+
114
+ def load_recording(self, file_path: str):
115
+ """Load recorded requests from file."""
116
+ with open(file_path, 'r') as f:
117
+ data = json.load(f)
118
+
119
+ self.recorded_requests = [
120
+ RecordedRequest(**req_data) for req_data in data.get('requests', [])
121
+ ]
122
+
123
+ def get_requests_by_path(self, path: str) -> List[RecordedRequest]:
124
+ """Get all recorded requests for a specific path."""
125
+ return [req for req in self.recorded_requests if req.path == path]
126
+
127
+ def get_requests_by_method(self, method: str) -> List[RecordedRequest]:
128
+ """Get all recorded requests for a specific HTTP method."""
129
+ return [req for req in self.recorded_requests if req.method.upper() == method.upper()]
130
+
131
+ class ProxyRecorder:
132
+ """Records requests by proxying them to real APIs."""
133
+
134
+ def __init__(self, target_url: str):
135
+ self.target_url = target_url
136
+ self.recorder = RequestRecorder()
137
+ self.session_requests: Dict[str, List[RecordedRequest]] = {}
138
+
139
+ def start_proxy_session(self, session_id: str):
140
+ """Start a new proxy recording session."""
141
+ self.session_requests[session_id] = []
142
+
143
+ def record_proxy_request(self, session_id: str, request: RecordedRequest):
144
+ """Record a request during proxy session."""
145
+ if session_id in self.session_requests:
146
+ if self.recorder.record_request(request):
147
+ self.session_requests[session_id].append(request)
148
+
149
+ def end_proxy_session(self, session_id: str) -> List[RecordedRequest]:
150
+ """End a proxy session and return recorded requests."""
151
+ return self.session_requests.get(session_id, [])
152
+
153
+ def get_session_summary(self, session_id: str) -> Dict[str, Any]:
154
+ """Get summary statistics for a proxy session."""
155
+ requests = self.session_requests.get(session_id, [])
156
+ if not requests:
157
+ return {}
158
+
159
+ methods = {}
160
+ paths = {}
161
+ status_codes = {}
162
+
163
+ for req in requests:
164
+ methods[req.method] = methods.get(req.method, 0) + 1
165
+ paths[req.path] = paths.get(req.path, 0) + 1
166
+ status_codes[req.response_status] = status_codes.get(req.response_status, 0) + 1
167
+
168
+ return {
169
+ 'total_requests': len(requests),
170
+ 'methods': methods,
171
+ 'paths': paths,
172
+ 'status_codes': status_codes,
173
+ 'duration': self._calculate_session_duration(requests)
174
+ }
175
+
176
+ def _calculate_session_duration(self, requests: List[RecordedRequest]) -> float:
177
+ """Calculate the duration of a proxy session."""
178
+ if len(requests) < 2:
179
+ return 0.0
180
+
181
+ start_time = datetime.fromisoformat(requests[0].timestamp)
182
+ end_time = datetime.fromisoformat(requests[-1].timestamp)
183
+ return (end_time - start_time).total_seconds()
184
+
185
+ class ReplayEngine:
186
+ """Replays recorded requests as mock responses."""
187
+
188
+ def __init__(self):
189
+ self.recorded_responses: Dict[str, List[RecordedRequest]] = {}
190
+ self.response_variations: Dict[str, List[Any]] = {}
191
+
192
+ def load_recorded_requests(self, requests: List[RecordedRequest]):
193
+ """Load recorded requests for replay."""
194
+ for request in requests:
195
+ key = f"{request.method}:{request.path}"
196
+ if key not in self.recorded_responses:
197
+ self.recorded_responses[key] = []
198
+ self.recorded_responses[key].append(request)
199
+
200
+ def get_response(self, method: str, path: str) -> Optional[Dict[str, Any]]:
201
+ """Get a recorded response for the given method and path."""
202
+ key = f"{method}:{path}"
203
+ responses = self.recorded_responses.get(key, [])
204
+
205
+ if not responses:
206
+ return None
207
+
208
+ # Return the most recent response by default
209
+ response = responses[-1]
210
+
211
+ return {
212
+ 'status_code': response.response_status,
213
+ 'headers': response.response_headers,
214
+ 'body': response.response_body
215
+ }
216
+
217
+ def get_response_variation(self, method: str, path: str) -> Optional[Dict[str, Any]]:
218
+ """Get a random variation of recorded responses."""
219
+ key = f"{method}:{path}"
220
+ responses = self.recorded_responses.get(key, [])
221
+
222
+ if not responses:
223
+ return None
224
+
225
+ # Return a random response
226
+ import random
227
+ response = random.choice(responses)
228
+
229
+ return {
230
+ 'status_code': response.response_status,
231
+ 'headers': response.response_headers,
232
+ 'body': response.response_body
233
+ }
234
+
235
+ def generate_variations(self, method: str, path: str, count: int = 5):
236
+ """Generate variations of recorded responses for more realistic testing."""
237
+ key = f"{method}:{path}"
238
+ responses = self.recorded_responses.get(key, [])
239
+
240
+ if not responses:
241
+ return
242
+
243
+ variations = []
244
+ for _ in range(count):
245
+ # Create variations by modifying the response
246
+ base_response = responses[0]
247
+ variation = self._create_variation(base_response)
248
+ variations.append(variation)
249
+
250
+ self.response_variations[key] = variations
251
+
252
+ def _create_variation(self, base_response: RecordedRequest) -> Dict[str, Any]:
253
+ """Create a variation of a recorded response."""
254
+ # This is a simple variation - could be made more sophisticated
255
+ variation = {
256
+ 'status_code': base_response.response_status,
257
+ 'headers': base_response.response_headers.copy(),
258
+ 'body': base_response.response_body
259
+ }
260
+
261
+ # Add some random variation to the response
262
+ if isinstance(variation['body'], dict):
263
+ variation['body'] = variation['body'].copy()
264
+ # Could add random variations here
265
+
266
+ return variation
api_mocker/server.py ADDED
@@ -0,0 +1,96 @@
1
+ from fastapi import FastAPI, Request, Response
2
+ from fastapi.responses import JSONResponse
3
+ import uvicorn
4
+ from typing import Optional, Dict, Any
5
+ from .core import CoreEngine, RouteConfig
6
+ from .config import ConfigLoader
7
+
8
+ class MockServer:
9
+ def __init__(self, config_path: Optional[str] = None):
10
+ self.app = FastAPI(title="api-mocker")
11
+ self.config_path = config_path
12
+ self.engine = CoreEngine()
13
+ self.config = {}
14
+
15
+ if config_path:
16
+ self.load_config(config_path)
17
+
18
+ self._setup_routes()
19
+
20
+ def load_config(self, config_path: str):
21
+ """Load configuration from file."""
22
+ try:
23
+ self.config = ConfigLoader.load(config_path)
24
+ self._apply_config()
25
+ except Exception as e:
26
+ print(f"Warning: Failed to load config {config_path}: {e}")
27
+
28
+ def _apply_config(self):
29
+ """Apply configuration to the engine."""
30
+ routes_config = self.config.get("routes", [])
31
+ print(f"Loading {len(routes_config)} routes from config")
32
+
33
+ for route_data in routes_config:
34
+ print(f"Adding route: {route_data['method']} {route_data['path']}")
35
+ # Create a response function from the config
36
+ response_config = route_data.get("response", {})
37
+
38
+ def create_response_func(config):
39
+ def response_func(path: str, method: str, headers: Dict, body: Any, engine):
40
+ return {
41
+ "status_code": config.get("status_code", 200),
42
+ "body": config.get("body", {}),
43
+ "headers": config.get("headers", {})
44
+ }
45
+ return response_func
46
+
47
+ route = RouteConfig(
48
+ path=route_data["path"],
49
+ method=route_data["method"],
50
+ response=create_response_func(response_config),
51
+ status_code=response_config.get("status_code", 200),
52
+ headers=response_config.get("headers"),
53
+ delay=route_data.get("delay", 0),
54
+ dynamic=route_data.get("dynamic", False)
55
+ )
56
+ self.engine.router.add_route(route)
57
+
58
+ print(f"Total routes loaded: {len(self.engine.router.routes)}")
59
+
60
+ def _setup_routes(self):
61
+ """Set up FastAPI routes using the core engine."""
62
+
63
+ @self.app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"])
64
+ async def handle_request(request: Request, path: str):
65
+ # Get request details
66
+ method = request.method
67
+ headers = dict(request.headers)
68
+ body = None
69
+
70
+ print(f"Received request: {method} /{path}")
71
+
72
+ if method in ["POST", "PUT", "PATCH"]:
73
+ try:
74
+ body = await request.json()
75
+ except:
76
+ body = await request.body()
77
+
78
+ # Process request through core engine
79
+ response = self.engine.process_request(path, method, headers, body)
80
+
81
+ # Return response
82
+ status_code = response.get("status_code", 200)
83
+ response_body = response.get("body", {})
84
+ response_headers = response.get("headers", {})
85
+
86
+ return JSONResponse(
87
+ content=response_body,
88
+ status_code=status_code,
89
+ headers=response_headers
90
+ )
91
+
92
+ def start(self, host: str = "127.0.0.1", port: int = 8000):
93
+ """Start the mock server."""
94
+ print(f"Starting api-mocker server on http://{host}:{port}")
95
+ print(f"Loaded {len(self.engine.router.routes)} routes")
96
+ uvicorn.run(self.app, host=host, port=port)
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: api-mocker
3
+ Version: 0.1.0
4
+ Summary: The industry-standard, production-ready, free API mocking and development acceleration tool.
5
+ Author-email: sherin joseph roy <sherin.joseph2217@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024 sherin joseph roy
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: Homepage, https://github.com/Sherin-SEF-AI/api-mocker
28
+ Project-URL: Repository, https://github.com/Sherin-SEF-AI/api-mocker.git
29
+ Keywords: api,mock,mocking,development,testing,openapi,swagger,cli,devops
30
+ Classifier: Programming Language :: Python :: 3
31
+ Classifier: License :: OSI Approved :: MIT License
32
+ Classifier: Operating System :: OS Independent
33
+ Classifier: Development Status :: 3 - Alpha
34
+ Classifier: Intended Audience :: Developers
35
+ Classifier: Topic :: Software Development :: Testing
36
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
37
+ Requires-Python: >=3.8
38
+ Description-Content-Type: text/markdown
39
+ License-File: LICENSE
40
+ Requires-Dist: typer>=0.9.0
41
+ Requires-Dist: fastapi>=0.100.0
42
+ Requires-Dist: uvicorn>=0.23.0
43
+ Requires-Dist: PyYAML>=6.0
44
+ Requires-Dist: toml>=0.10.2
45
+ Requires-Dist: pytest>=7.0.0
46
+ Requires-Dist: httpx>=0.24.0
47
+ Requires-Dist: rich>=13.0.0
48
+ Dynamic: license-file
49
+
50
+ # api-mocker
51
+
52
+ The industry-standard, production-ready, free API mocking and development acceleration tool.
53
+
54
+ ## Project Mission
55
+ Create the most comprehensive, user-friendly, and feature-rich API mocking solution to eliminate API dependency bottlenecks and accelerate development workflows for all developers.
56
+
57
+ ## Features
58
+ - Robust HTTP mock server supporting all HTTP methods
59
+ - Dynamic and static response generation
60
+ - OpenAPI/Swagger/Postman import/export
61
+ - CLI and Python API interfaces
62
+ - Hot-reloading, config file support (JSON/YAML/TOML)
63
+ - Request recording, replay, and proxy mode
64
+ - Schema-based data generation and validation
65
+ - Advanced routing, middleware, and authentication simulation
66
+ - Data persistence, state management, and in-memory DB
67
+ - Performance, monitoring, and analytics tools
68
+ - Framework integrations (Django, Flask, FastAPI, Node.js, etc.)
69
+ - Docker, CI/CD, and cloud deployment support
70
+ - Team collaboration and plugin architecture
71
+
72
+ ## Installation
73
+ ```bash
74
+ pip install api-mocker
75
+ ```
76
+
77
+ ## Quick Start
78
+ ```bash
79
+ api-mocker start --config api-mock.yaml
80
+ ```
81
+ Or use as a Python library:
82
+ ```python
83
+ from api_mocker import MockServer
84
+ server = MockServer(config_path="api-mock.yaml")
85
+ server.start()
86
+ ```
87
+
88
+ ## Documentation
89
+ See [Full Documentation](https://github.com/Sherin-SEF-AI/api-mocker#documentation) for guides, API reference, and examples.
90
+
91
+ ## Contributing
92
+ Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
93
+
94
+ ## License
95
+ MIT License
96
+
97
+ ---
98
+ © 2024 sherin joseph roy
@@ -0,0 +1,14 @@
1
+ api_mocker/__init__.py,sha256=CFC641XJCw_2RbFocNHCTwfr3EEdOQmICFGG_Xlny3Y,168
2
+ api_mocker/cli.py,sha256=LktBFt7V7c1Y00zwZuZzjD5ktAJsm31S7BAaiiGkg5g,19485
3
+ api_mocker/config.py,sha256=zNlJCk1Bs0BrGU-92wiFv2ZTBRu9dJQ6sF8Dh6kIhLQ,913
4
+ api_mocker/core.py,sha256=G04vhIcVzuoynZ4GVM6e222bnemMdXN4pOQuvalWY6c,8480
5
+ api_mocker/openapi.py,sha256=Pb1gKbBWosEV5i739rW0Nb3ArNq62lgMN0ecyvigNKY,7403
6
+ api_mocker/plugins.py,sha256=OK3OVHJszDky46JHntMVsZUH1ajBjBhAKq3TCDYuxWI,8178
7
+ api_mocker/recorder.py,sha256=7tiT2Krxy3nLDxFAE7rpZSimuD-rKeiwdU72cp0dg6E,9984
8
+ api_mocker/server.py,sha256=xfczRj4xFXGVaGn2pVPgGvYyv3IHUlYTEz3Hop1KQu0,3812
9
+ api_mocker-0.1.0.dist-info/licenses/LICENSE,sha256=FzyeLcPe623lrwpFx3xQ3W0Hb_S2sbHqLzhSXaTmcGg,1074
10
+ api_mocker-0.1.0.dist-info/METADATA,sha256=yrcm8uNXwtVs6jH8Tb9kj2VgW5EuekIopGZ4S7BkRxI,3901
11
+ api_mocker-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
12
+ api_mocker-0.1.0.dist-info/entry_points.txt,sha256=dj0UIkQ36Uq3oeSjGzmRRUQKFriq4WMCzg7TCor7wkM,51
13
+ api_mocker-0.1.0.dist-info/top_level.txt,sha256=ZcowEudKsJ6xbvOXIno2zZcPhjB-gGO1w7uzoUKRKDM,11
14
+ api_mocker-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ api-mocker = api_mocker.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 sherin joseph roy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ api_mocker