api-mock-ai 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_mock_ai/__init__.py +8 -0
- api_mock_ai/__main__.py +4 -0
- api_mock_ai/chaos.py +84 -0
- api_mock_ai/cli.py +303 -0
- api_mock_ai/config.py +52 -0
- api_mock_ai/docs.py +198 -0
- api_mock_ai/errors.py +13 -0
- api_mock_ai/generate/__init__.py +292 -0
- api_mock_ai/generate/cache.py +47 -0
- api_mock_ai/generate/faker_gen.py +726 -0
- api_mock_ai/generate/llm_gen.py +184 -0
- api_mock_ai/generate/locales.py +380 -0
- api_mock_ai/py.typed +0 -0
- api_mock_ai/server.py +494 -0
- api_mock_ai/spec/__init__.py +6 -0
- api_mock_ai/spec/loader.py +111 -0
- api_mock_ai/spec/model.py +472 -0
- api_mock_ai/spec/schema.py +42 -0
- api_mock_ai/static/docs.html +669 -0
- api_mock_ai/store.py +178 -0
- api_mock_ai/validation.py +58 -0
- api_mock_ai-0.1.0.dist-info/METADATA +476 -0
- api_mock_ai-0.1.0.dist-info/RECORD +26 -0
- api_mock_ai-0.1.0.dist-info/WHEEL +4 -0
- api_mock_ai-0.1.0.dist-info/entry_points.txt +2 -0
- api_mock_ai-0.1.0.dist-info/licenses/LICENSE +21 -0
api_mock_ai/__init__.py
ADDED
api_mock_ai/__main__.py
ADDED
api_mock_ai/chaos.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Latency and failure injection, for testing how frontends handle slow or broken APIs.
|
|
2
|
+
|
|
3
|
+
Global settings come from the CLI (``--latency``, ``--error-rate``). Any single
|
|
4
|
+
request can also ask for a delay or a status code with headers:
|
|
5
|
+
|
|
6
|
+
* ``X-Mock-Delay: 1500`` -> wait 1.5 seconds before answering
|
|
7
|
+
* ``X-Mock-Status: 503`` -> answer with that error (4xx/5xx) instead of the real response
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import random
|
|
14
|
+
|
|
15
|
+
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
|
16
|
+
from starlette.requests import Request
|
|
17
|
+
from starlette.responses import JSONResponse, Response
|
|
18
|
+
from starlette.types import ASGIApp
|
|
19
|
+
|
|
20
|
+
ERROR_MESSAGES = {
|
|
21
|
+
400: "Bad request",
|
|
22
|
+
401: "Unauthorized",
|
|
23
|
+
403: "Forbidden",
|
|
24
|
+
404: "Not found",
|
|
25
|
+
408: "Request timeout",
|
|
26
|
+
409: "Conflict",
|
|
27
|
+
422: "Unprocessable entity",
|
|
28
|
+
429: "Too many requests",
|
|
29
|
+
500: "Internal server error",
|
|
30
|
+
502: "Bad gateway",
|
|
31
|
+
503: "Service unavailable",
|
|
32
|
+
504: "Gateway timeout",
|
|
33
|
+
}
|
|
34
|
+
MAX_DELAY_MS = 60_000
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ChaosMiddleware(BaseHTTPMiddleware):
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
app: ASGIApp,
|
|
41
|
+
*,
|
|
42
|
+
latency_ms: tuple[int, int] = (0, 0),
|
|
43
|
+
error_rate: float = 0.0,
|
|
44
|
+
exclude_prefixes: tuple[str, ...] = (),
|
|
45
|
+
seed: int | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
super().__init__(app)
|
|
48
|
+
self.latency_ms = latency_ms
|
|
49
|
+
self.error_rate = error_rate
|
|
50
|
+
self.exclude_prefixes = exclude_prefixes
|
|
51
|
+
self.random = random.Random(seed)
|
|
52
|
+
|
|
53
|
+
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
|
|
54
|
+
if request.method == "OPTIONS" or request.url.path.startswith(self.exclude_prefixes):
|
|
55
|
+
return await call_next(request)
|
|
56
|
+
|
|
57
|
+
delay = _int_header(request, "x-mock-delay")
|
|
58
|
+
if delay is None and self.latency_ms[1] > 0:
|
|
59
|
+
delay = self.random.randint(*self.latency_ms)
|
|
60
|
+
if delay:
|
|
61
|
+
await asyncio.sleep(min(delay, MAX_DELAY_MS) / 1000)
|
|
62
|
+
|
|
63
|
+
status = _int_header(request, "x-mock-status")
|
|
64
|
+
if status is None and self.error_rate and self.random.random() < self.error_rate:
|
|
65
|
+
status = self.random.choice([500, 502, 503])
|
|
66
|
+
if status is not None and 400 <= status <= 599:
|
|
67
|
+
return error_response(status, simulated=True)
|
|
68
|
+
|
|
69
|
+
return await call_next(request)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def error_response(status: int, message: str | None = None, **extra: object) -> Response:
|
|
73
|
+
body = {"error": message or ERROR_MESSAGES.get(status, "Error"), "status": status, **extra}
|
|
74
|
+
return JSONResponse(body, status_code=status)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _int_header(request: Request, name: str) -> int | None:
|
|
78
|
+
value = request.headers.get(name)
|
|
79
|
+
if value is None:
|
|
80
|
+
return None
|
|
81
|
+
try:
|
|
82
|
+
return int(value.strip().removesuffix("ms"))
|
|
83
|
+
except ValueError:
|
|
84
|
+
return None
|
api_mock_ai/cli.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Command-line interface: ``api-mock-ai serve | generate | validate``."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import socket
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.panel import Panel
|
|
13
|
+
from rich.table import Table
|
|
14
|
+
|
|
15
|
+
from api_mock_ai import __version__
|
|
16
|
+
from api_mock_ai.config import MockConfig
|
|
17
|
+
from api_mock_ai.errors import ApiMockError
|
|
18
|
+
from api_mock_ai.generate import load_or_build_seed
|
|
19
|
+
from api_mock_ai.generate.locales import describe_locale
|
|
20
|
+
from api_mock_ai.spec.loader import load_spec, resolve_refs
|
|
21
|
+
from api_mock_ai.spec.model import ApiModel, build_model
|
|
22
|
+
|
|
23
|
+
app = typer.Typer(
|
|
24
|
+
name="api-mock-ai",
|
|
25
|
+
help="Realistic, stateful mock APIs from any OpenAPI spec.",
|
|
26
|
+
no_args_is_help=True,
|
|
27
|
+
add_completion=False,
|
|
28
|
+
rich_markup_mode="rich",
|
|
29
|
+
)
|
|
30
|
+
console = Console()
|
|
31
|
+
err_console = Console(stderr=True)
|
|
32
|
+
|
|
33
|
+
SpecArg = typer.Argument(..., help="Path or URL of an OpenAPI 3.x spec (YAML or JSON).")
|
|
34
|
+
CountOpt = typer.Option(10, "--count", "-n", min=0, help="Records generated per resource.")
|
|
35
|
+
SeedOpt = typer.Option(42, "--seed", help="Random seed. Same seed = same data.")
|
|
36
|
+
LocaleOpt = typer.Option(
|
|
37
|
+
"en_US",
|
|
38
|
+
"--locale",
|
|
39
|
+
"-l",
|
|
40
|
+
help="Country or region for names, phones, banks and currency: a Faker locale (de_DE), "
|
|
41
|
+
"a country (pk, in, us, uk, de, fr) or a region (eu, south_asia).",
|
|
42
|
+
)
|
|
43
|
+
AiOpt = typer.Option(False, "--ai", help="Generate data with an LLM instead of Faker.")
|
|
44
|
+
ModelOpt = typer.Option(
|
|
45
|
+
None,
|
|
46
|
+
"--model",
|
|
47
|
+
"-m",
|
|
48
|
+
envvar="API_MOCK_AI_MODEL",
|
|
49
|
+
help="LiteLLM model for --ai, e.g. ollama/llama3.1 or anthropic/claude-haiku-5-5.",
|
|
50
|
+
)
|
|
51
|
+
CacheOpt = typer.Option(
|
|
52
|
+
Path(".api-mock-ai"), "--cache-dir", help="Where AI-generated data is cached."
|
|
53
|
+
)
|
|
54
|
+
RefreshOpt = typer.Option(False, "--refresh", help="Ignore the cache and regenerate AI data.")
|
|
55
|
+
BaseOpt = typer.Option(
|
|
56
|
+
None, "--base-path", help="Route prefix, e.g. /v1. Default: taken from the spec's servers."
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _version_callback(value: bool) -> None:
|
|
61
|
+
if value:
|
|
62
|
+
console.print(f"api-mock-ai {__version__}")
|
|
63
|
+
raise typer.Exit()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@app.callback()
|
|
67
|
+
def main_callback(
|
|
68
|
+
version: bool = typer.Option(
|
|
69
|
+
False,
|
|
70
|
+
"--version",
|
|
71
|
+
"-V",
|
|
72
|
+
callback=_version_callback,
|
|
73
|
+
is_eager=True,
|
|
74
|
+
help="Show the version and exit.",
|
|
75
|
+
),
|
|
76
|
+
) -> None:
|
|
77
|
+
"""Realistic, stateful mock APIs from any OpenAPI spec."""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@app.command()
|
|
81
|
+
def serve(
|
|
82
|
+
spec: str = SpecArg,
|
|
83
|
+
host: str = typer.Option("127.0.0.1", "--host", help="Interface to bind to."),
|
|
84
|
+
port: int = typer.Option(8000, "--port", "-p", help="Port to listen on."),
|
|
85
|
+
count: int = CountOpt,
|
|
86
|
+
seed: int = SeedOpt,
|
|
87
|
+
locale: str = LocaleOpt,
|
|
88
|
+
ai: bool = AiOpt,
|
|
89
|
+
model: Optional[str] = ModelOpt,
|
|
90
|
+
latency: str = typer.Option(
|
|
91
|
+
"0", "--latency", help="Artificial delay in ms: a value (200) or a range (100-500)."
|
|
92
|
+
),
|
|
93
|
+
error_rate: float = typer.Option(
|
|
94
|
+
0.0, "--error-rate", min=0.0, max=1.0, help="Share of requests that fail with a 5xx."
|
|
95
|
+
),
|
|
96
|
+
cors: bool = typer.Option(True, "--cors/--no-cors", help="Allow cross-origin requests."),
|
|
97
|
+
validate_requests: bool = typer.Option(
|
|
98
|
+
True, "--validate/--no-validate", help="Reject request bodies that don't match the spec."
|
|
99
|
+
),
|
|
100
|
+
cache_dir: Path = CacheOpt,
|
|
101
|
+
refresh: bool = RefreshOpt,
|
|
102
|
+
base_path: Optional[str] = BaseOpt,
|
|
103
|
+
) -> None:
|
|
104
|
+
"""Start a mock server for SPEC."""
|
|
105
|
+
import uvicorn
|
|
106
|
+
|
|
107
|
+
from api_mock_ai.server import create_app
|
|
108
|
+
|
|
109
|
+
config = _config(
|
|
110
|
+
count=count,
|
|
111
|
+
seed=seed,
|
|
112
|
+
locale=locale,
|
|
113
|
+
ai=ai,
|
|
114
|
+
model=model,
|
|
115
|
+
latency=latency,
|
|
116
|
+
error_rate=error_rate,
|
|
117
|
+
cors=cors,
|
|
118
|
+
validate_requests=validate_requests,
|
|
119
|
+
cache_dir=cache_dir,
|
|
120
|
+
refresh=refresh,
|
|
121
|
+
base_path=base_path,
|
|
122
|
+
)
|
|
123
|
+
_setup_logging()
|
|
124
|
+
if not _port_free(host, port):
|
|
125
|
+
_fail(ValueError(f"Port {port} is already in use. Try another one, e.g. --port {port + 1}"))
|
|
126
|
+
try:
|
|
127
|
+
with console.status("Reading the spec and generating data..."):
|
|
128
|
+
fastapi_app = create_app(spec, config)
|
|
129
|
+
except ApiMockError as exc:
|
|
130
|
+
_fail(exc)
|
|
131
|
+
|
|
132
|
+
api: ApiModel = fastapi_app.state.api
|
|
133
|
+
url = f"http://{'localhost' if host in ('127.0.0.1', '0.0.0.0') else host}:{port}"
|
|
134
|
+
_print_banner(api, url, fastapi_app.state.docs_url, config)
|
|
135
|
+
uvicorn.run(fastapi_app, host=host, port=port, log_level="warning")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@app.command()
|
|
139
|
+
def generate(
|
|
140
|
+
spec: str = SpecArg,
|
|
141
|
+
output: Optional[Path] = typer.Option(
|
|
142
|
+
None, "--output", "-o", help="Write JSON to this file instead of printing it."
|
|
143
|
+
),
|
|
144
|
+
count: int = CountOpt,
|
|
145
|
+
seed: int = SeedOpt,
|
|
146
|
+
locale: str = LocaleOpt,
|
|
147
|
+
ai: bool = AiOpt,
|
|
148
|
+
model: Optional[str] = ModelOpt,
|
|
149
|
+
cache_dir: Path = CacheOpt,
|
|
150
|
+
refresh: bool = RefreshOpt,
|
|
151
|
+
) -> None:
|
|
152
|
+
"""Generate mock data for SPEC and output it as JSON (no server)."""
|
|
153
|
+
config = _config(
|
|
154
|
+
count=count,
|
|
155
|
+
seed=seed,
|
|
156
|
+
locale=locale,
|
|
157
|
+
ai=ai,
|
|
158
|
+
model=model,
|
|
159
|
+
cache_dir=cache_dir,
|
|
160
|
+
refresh=refresh,
|
|
161
|
+
)
|
|
162
|
+
_setup_logging()
|
|
163
|
+
try:
|
|
164
|
+
raw = resolve_refs(load_spec(spec))
|
|
165
|
+
api = build_model(raw)
|
|
166
|
+
seed_data = load_or_build_seed(api, raw, config)
|
|
167
|
+
except ApiMockError as exc:
|
|
168
|
+
_fail(exc)
|
|
169
|
+
|
|
170
|
+
# Two resources can share a name (/orders and /users/{id}/orders): keep both.
|
|
171
|
+
names = [resource.name for resource in api.resources.values()]
|
|
172
|
+
result = {
|
|
173
|
+
(resource.name if names.count(resource.name) == 1 else key): [
|
|
174
|
+
entry["data"] for entry in seed_data.get(key, [])
|
|
175
|
+
]
|
|
176
|
+
for key, resource in api.resources.items()
|
|
177
|
+
}
|
|
178
|
+
text = json.dumps(result, indent=2, ensure_ascii=False)
|
|
179
|
+
if output:
|
|
180
|
+
output.write_text(text + "\n", encoding="utf-8")
|
|
181
|
+
total = sum(len(records) for records in result.values())
|
|
182
|
+
console.print(f"[green]Wrote {total} records for {len(result)} resources to {output}")
|
|
183
|
+
else:
|
|
184
|
+
typer.echo(text)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@app.command()
|
|
188
|
+
def validate(spec: str = SpecArg) -> None:
|
|
189
|
+
"""Check SPEC and show how each route will be mocked."""
|
|
190
|
+
try:
|
|
191
|
+
raw = resolve_refs(load_spec(spec))
|
|
192
|
+
api = build_model(raw)
|
|
193
|
+
except ApiMockError as exc:
|
|
194
|
+
_fail(exc)
|
|
195
|
+
|
|
196
|
+
console.print(f"[green]OK[/] [bold]{api.title}[/] {api.version} is a valid spec.\n")
|
|
197
|
+
routes = Table(title="Routes", show_lines=False)
|
|
198
|
+
routes.add_column("Method", style="bold cyan")
|
|
199
|
+
routes.add_column("Path")
|
|
200
|
+
routes.add_column("Behaviour")
|
|
201
|
+
routes.add_column("Status", justify="right")
|
|
202
|
+
order = {"GET": 0, "POST": 1, "PUT": 2, "PATCH": 3, "DELETE": 4}
|
|
203
|
+
for op in sorted(api.operations, key=lambda o: (o.path, order.get(o.method, 9))):
|
|
204
|
+
behaviour = f"{op.kind} [dim]{op.resource.name}[/]" if op.resource else "generated"
|
|
205
|
+
routes.add_row(op.method, api.base_path + op.path, behaviour, str(op.response_status))
|
|
206
|
+
console.print(routes)
|
|
207
|
+
|
|
208
|
+
if api.resources:
|
|
209
|
+
table = Table(title="Stateful resources")
|
|
210
|
+
table.add_column("Resource", style="bold")
|
|
211
|
+
table.add_column("Collection")
|
|
212
|
+
table.add_column("Id field")
|
|
213
|
+
table.add_column("Belongs to")
|
|
214
|
+
for resource in api.resources_by_depth():
|
|
215
|
+
table.add_row(
|
|
216
|
+
resource.name,
|
|
217
|
+
api.base_path + resource.key,
|
|
218
|
+
resource.id_field,
|
|
219
|
+
resource.parent.name if resource.parent else "-",
|
|
220
|
+
)
|
|
221
|
+
console.print(table)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def main() -> None:
|
|
225
|
+
# Windows consoles default to a legacy code page; make non-ASCII data printable.
|
|
226
|
+
for stream in (sys.stdout, sys.stderr):
|
|
227
|
+
if hasattr(stream, "reconfigure") and (stream.encoding or "").lower() != "utf-8":
|
|
228
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
229
|
+
app()
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
# ---------------------------------------------------------------------- helpers
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _config(**options: object) -> MockConfig:
|
|
236
|
+
latency = _parse_latency(str(options.pop("latency", "0")))
|
|
237
|
+
ai = bool(options.pop("ai"))
|
|
238
|
+
try:
|
|
239
|
+
return MockConfig(use_ai=ai, latency_ms=latency, **options) # type: ignore[arg-type]
|
|
240
|
+
except ValueError as exc:
|
|
241
|
+
_fail(exc)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _port_free(host: str, port: int) -> bool:
|
|
245
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
|
|
246
|
+
try:
|
|
247
|
+
probe.bind((host if host != "localhost" else "127.0.0.1", port))
|
|
248
|
+
except OSError:
|
|
249
|
+
return False
|
|
250
|
+
return True
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _parse_latency(value: str) -> tuple[int, int]:
|
|
254
|
+
text = value.lower().replace("ms", "").replace(" ", "")
|
|
255
|
+
try:
|
|
256
|
+
if "-" in text:
|
|
257
|
+
low, high = (int(part) for part in text.split("-", 1))
|
|
258
|
+
else:
|
|
259
|
+
low = high = int(text)
|
|
260
|
+
except ValueError:
|
|
261
|
+
raise typer.BadParameter(
|
|
262
|
+
"Use milliseconds like 200 or a range like 100-500.", param_hint="--latency"
|
|
263
|
+
) from None
|
|
264
|
+
if low < 0 or high < low:
|
|
265
|
+
raise typer.BadParameter("Use a range like 100-500.", param_hint="--latency")
|
|
266
|
+
return low, high
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _fail(exc: Exception) -> None:
|
|
270
|
+
err_console.print(f"[bold red]Error:[/] {exc}")
|
|
271
|
+
raise typer.Exit(code=1)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _setup_logging() -> None:
|
|
275
|
+
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
|
276
|
+
for noisy in ("LiteLLM", "litellm", "httpx"):
|
|
277
|
+
logging.getLogger(noisy).setLevel(logging.WARNING)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _print_banner(api: ApiModel, url: str, docs: str, config: MockConfig) -> None:
|
|
281
|
+
lines = [
|
|
282
|
+
f"[bold]{api.title}[/] {api.version} | mocked by api-mock-ai {__version__}",
|
|
283
|
+
"",
|
|
284
|
+
f"API [cyan]{url}{api.base_path}[/]",
|
|
285
|
+
f"Docs [cyan]{url}{docs}[/] (interactive API documentation)",
|
|
286
|
+
f"Admin [cyan]{url}/__mock__/resources[/] (POST /__mock__/reset to restore data)",
|
|
287
|
+
"",
|
|
288
|
+
f"Data {'AI | ' + str(config.model) if config.use_ai else 'Faker'}"
|
|
289
|
+
f" | {config.count} per resource | seed {config.seed}",
|
|
290
|
+
f"Locale {config.locale}: {describe_locale(config.locale)}",
|
|
291
|
+
]
|
|
292
|
+
if config.latency_ms[1] or config.error_rate:
|
|
293
|
+
lines.append(
|
|
294
|
+
f"Chaos latency {config.latency_ms[0]}-{config.latency_ms[1]} ms"
|
|
295
|
+
f" | error rate {config.error_rate:.0%}"
|
|
296
|
+
)
|
|
297
|
+
if api.resources:
|
|
298
|
+
lines += [
|
|
299
|
+
"",
|
|
300
|
+
"Resources: " + ", ".join(api.base_path + r.key for r in api.resources_by_depth()),
|
|
301
|
+
]
|
|
302
|
+
console.print(Panel("\n".join(lines), title="api-mock-ai", border_style="green", expand=False))
|
|
303
|
+
console.print("[dim]Press Ctrl+C to stop.[/]")
|
api_mock_ai/config.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Runtime configuration shared by the CLI, the server and the generators."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class MockConfig:
|
|
11
|
+
"""Options that control how the mock server generates and serves data.
|
|
12
|
+
|
|
13
|
+
Attributes:
|
|
14
|
+
count: Number of records generated per resource (e.g. 10 users, 10 orders).
|
|
15
|
+
seed: Random seed. The same seed always produces the same data.
|
|
16
|
+
locale: Faker locale used for names, addresses, phone numbers, etc.
|
|
17
|
+
use_ai: Generate seed data with an LLM instead of Faker.
|
|
18
|
+
model: LiteLLM model string, e.g. ``"ollama/llama3.1"``. Required when ``use_ai``.
|
|
19
|
+
latency_ms: (min, max) artificial latency added to every API response.
|
|
20
|
+
error_rate: Probability (0..1) that a request fails with a simulated 5xx error.
|
|
21
|
+
cors: Allow cross-origin requests (needed by frontends on another port).
|
|
22
|
+
validate_requests: Reject request bodies that do not match the spec with HTTP 422.
|
|
23
|
+
cache_dir: Where AI-generated seed data is cached between runs.
|
|
24
|
+
refresh: Ignore the cache and regenerate AI data.
|
|
25
|
+
base_path: Prefix for all routes. ``None`` derives it from the spec's ``servers``.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
count: int = 10
|
|
29
|
+
seed: int = 42
|
|
30
|
+
locale: str = "en_US"
|
|
31
|
+
use_ai: bool = False
|
|
32
|
+
model: str | None = None
|
|
33
|
+
latency_ms: tuple[int, int] = (0, 0)
|
|
34
|
+
error_rate: float = 0.0
|
|
35
|
+
cors: bool = True
|
|
36
|
+
validate_requests: bool = True
|
|
37
|
+
cache_dir: Path = field(default_factory=lambda: Path(".api-mock-ai"))
|
|
38
|
+
refresh: bool = False
|
|
39
|
+
base_path: str | None = None
|
|
40
|
+
|
|
41
|
+
def __post_init__(self) -> None:
|
|
42
|
+
if self.count < 0:
|
|
43
|
+
raise ValueError("count must be >= 0")
|
|
44
|
+
if not 0.0 <= self.error_rate <= 1.0:
|
|
45
|
+
raise ValueError("error_rate must be between 0 and 1")
|
|
46
|
+
low, high = self.latency_ms
|
|
47
|
+
if low < 0 or high < low:
|
|
48
|
+
raise ValueError("latency_ms must be (min, max) with 0 <= min <= max")
|
|
49
|
+
if self.use_ai and not self.model:
|
|
50
|
+
raise ValueError(
|
|
51
|
+
"An LLM model is required for AI generation, e.g. model='ollama/llama3.1'"
|
|
52
|
+
)
|
api_mock_ai/docs.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Data for the built-in API documentation page (``/docs``).
|
|
2
|
+
|
|
3
|
+
The page itself is a static HTML file (``static/docs.html``). It loads the
|
|
4
|
+
payload built here from ``/__mock__/routes``: every operation with its
|
|
5
|
+
parameters, schemas and *live* examples taken from the running mock, so the
|
|
6
|
+
documentation always shows the data the mock really returns.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
import zlib
|
|
13
|
+
from typing import TYPE_CHECKING, Any
|
|
14
|
+
|
|
15
|
+
from api_mock_ai import __version__
|
|
16
|
+
from api_mock_ai.generate import link_record
|
|
17
|
+
from api_mock_ai.generate.locales import describe_locale
|
|
18
|
+
from api_mock_ai.spec.model import Operation
|
|
19
|
+
from api_mock_ai.spec.schema import flatten
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from api_mock_ai.server import Responder
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def build_docs_payload(responder: Responder, openapi_url: str) -> dict[str, Any]:
|
|
26
|
+
api, store, config = responder.api, responder.store, responder.config
|
|
27
|
+
samples = sample_path_params(responder)
|
|
28
|
+
in_spec_order = sorted(api.operations, key=lambda op: op.index)
|
|
29
|
+
tag_order = [str(tag.get("name")) for tag in api.tags]
|
|
30
|
+
for operation in in_spec_order:
|
|
31
|
+
for tag in operation.tags:
|
|
32
|
+
if tag not in tag_order:
|
|
33
|
+
tag_order.append(tag)
|
|
34
|
+
descriptions = {str(tag.get("name")): tag.get("description", "") for tag in api.tags}
|
|
35
|
+
|
|
36
|
+
operations = sorted(in_spec_order, key=lambda op: tag_order.index(op.tags[0]))
|
|
37
|
+
counts = {key: len(records) for key, records in store.snapshot().items()}
|
|
38
|
+
return {
|
|
39
|
+
"title": api.title,
|
|
40
|
+
"version": api.version,
|
|
41
|
+
"description": api.description,
|
|
42
|
+
"basePath": api.base_path,
|
|
43
|
+
"openapiUrl": openapi_url,
|
|
44
|
+
"tool": {"name": "api-mock-ai", "version": __version__},
|
|
45
|
+
"data": {
|
|
46
|
+
"source": f"AI ({config.model})" if config.use_ai else "Faker",
|
|
47
|
+
"locale": config.locale,
|
|
48
|
+
"localeDescription": describe_locale(config.locale),
|
|
49
|
+
"count": config.count,
|
|
50
|
+
"seed": config.seed,
|
|
51
|
+
},
|
|
52
|
+
"tags": [{"name": name, "description": descriptions.get(name, "")} for name in tag_order],
|
|
53
|
+
"resources": [
|
|
54
|
+
{
|
|
55
|
+
"name": resource.name,
|
|
56
|
+
"path": api.base_path + resource.key,
|
|
57
|
+
"idField": resource.id_field,
|
|
58
|
+
"parent": resource.parent.name if resource.parent else None,
|
|
59
|
+
"count": counts.get(resource.key, 0),
|
|
60
|
+
}
|
|
61
|
+
for resource in api.resources_by_depth()
|
|
62
|
+
],
|
|
63
|
+
"securitySchemes": api.security_schemes,
|
|
64
|
+
"schemas": api.schemas,
|
|
65
|
+
"operations": [_operation(responder, op, samples) for op in operations],
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _operation(responder: Responder, op: Operation, samples: dict[str, str]) -> dict[str, Any]:
|
|
70
|
+
api = responder.api
|
|
71
|
+
params = {
|
|
72
|
+
p["name"]: samples.get(p["name"]) or _param_example(responder, p)
|
|
73
|
+
for p in op.parameters
|
|
74
|
+
if p.get("in") == "path" and p.get("name")
|
|
75
|
+
}
|
|
76
|
+
for name in _template_params(op.path): # parameters used but not declared
|
|
77
|
+
params.setdefault(name, samples.get(name, "1"))
|
|
78
|
+
|
|
79
|
+
security = op.security if op.security is not None else api.security
|
|
80
|
+
return {
|
|
81
|
+
"id": _slug(f"{op.method} {op.path}"),
|
|
82
|
+
"method": op.method,
|
|
83
|
+
"path": op.path,
|
|
84
|
+
"fullPath": api.base_path + op.path,
|
|
85
|
+
"summary": op.summary,
|
|
86
|
+
"description": op.description,
|
|
87
|
+
"tags": op.tags,
|
|
88
|
+
"deprecated": op.deprecated,
|
|
89
|
+
"kind": op.kind,
|
|
90
|
+
"resource": op.resource.name if op.resource else None,
|
|
91
|
+
"parent": op.resource.parent.name if op.resource and op.resource.parent else None,
|
|
92
|
+
"security": sorted({name for requirement in security for name in requirement}),
|
|
93
|
+
"parameters": [
|
|
94
|
+
{
|
|
95
|
+
"name": p.get("name"),
|
|
96
|
+
"in": p.get("in"),
|
|
97
|
+
"required": bool(p.get("required")) or p.get("in") == "path",
|
|
98
|
+
"description": p.get("description", ""),
|
|
99
|
+
"schema": p.get("schema") or {},
|
|
100
|
+
"example": params.get(p.get("name")) if p.get("in") == "path" else p.get("example"),
|
|
101
|
+
}
|
|
102
|
+
for p in op.parameters
|
|
103
|
+
if p.get("in") in ("path", "query", "header")
|
|
104
|
+
],
|
|
105
|
+
"requestBody": (
|
|
106
|
+
{
|
|
107
|
+
"required": op.request_required,
|
|
108
|
+
"schema": op.request_schema,
|
|
109
|
+
"example": _request_example(responder, op),
|
|
110
|
+
}
|
|
111
|
+
if op.request_schema
|
|
112
|
+
else None
|
|
113
|
+
),
|
|
114
|
+
"responses": op.responses,
|
|
115
|
+
"successStatus": op.response_status,
|
|
116
|
+
"example": _response_example(responder, op, params),
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def sample_path_params(responder: Responder) -> dict[str, str]:
|
|
121
|
+
"""Path parameter values that point at real records.
|
|
122
|
+
|
|
123
|
+
Deepest resources go first, so ``accountId`` is the account that owns the
|
|
124
|
+
sample ``transactionId`` and both example URLs work.
|
|
125
|
+
"""
|
|
126
|
+
samples: dict[str, str] = {}
|
|
127
|
+
store = responder.store
|
|
128
|
+
for resource in sorted(responder.api.resources.values(), key=lambda r: -r.depth):
|
|
129
|
+
entry = store.first_entry(resource)
|
|
130
|
+
if entry is None:
|
|
131
|
+
continue
|
|
132
|
+
if resource.id_param:
|
|
133
|
+
samples.setdefault(resource.id_param, str(entry["data"].get(resource.id_field)))
|
|
134
|
+
if resource.parent_param and entry["parent"] is not None:
|
|
135
|
+
samples.setdefault(resource.parent_param, str(entry["parent"]))
|
|
136
|
+
return samples
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _param_example(responder: Responder, param: dict[str, Any]) -> str:
|
|
140
|
+
if "example" in param:
|
|
141
|
+
return str(param["example"])
|
|
142
|
+
value = responder.faker.generate(param.get("schema") or {}, field=param.get("name", ""))
|
|
143
|
+
return str(value)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _request_example(responder: Responder, op: Operation) -> Any:
|
|
147
|
+
schema = _without_read_only(op.request_schema or {})
|
|
148
|
+
responder.faker.reseed(
|
|
149
|
+
responder.config.seed + zlib.crc32(f"req {op.method} {op.path}".encode())
|
|
150
|
+
)
|
|
151
|
+
hint = op.resource.name if op.resource else op.path
|
|
152
|
+
example = responder.faker.generate(schema, hint=hint)
|
|
153
|
+
if isinstance(example, dict): # e.g. beneficiaryId -> a beneficiary that exists
|
|
154
|
+
link_record(responder.api, responder.store.seed_view(), responder.faker, example, schema)
|
|
155
|
+
return example
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _response_example(
|
|
159
|
+
responder: Responder, op: Operation, params: dict[str, str]
|
|
160
|
+
) -> dict[str, Any] | None:
|
|
161
|
+
"""Ask the mock itself, without changing any data."""
|
|
162
|
+
try:
|
|
163
|
+
if op.kind == "list":
|
|
164
|
+
status, body = responder.dispatch(op, params, {"limit": "2"}, None)
|
|
165
|
+
elif op.kind in ("read", "custom"):
|
|
166
|
+
status, body = responder.dispatch(op, params, {}, None)
|
|
167
|
+
elif op.kind in ("create", "update"):
|
|
168
|
+
resource = op.resource
|
|
169
|
+
assert resource is not None
|
|
170
|
+
entry = responder.store.first_entry(resource)
|
|
171
|
+
body = responder.wrap_item(entry["data"] if entry else None, op.response_schema)
|
|
172
|
+
status = op.response_status if op.kind == "update" or op.response_status != 200 else 201
|
|
173
|
+
else: # delete
|
|
174
|
+
status, body = (op.response_status if op.response_schema else 204), None
|
|
175
|
+
except Exception: # examples are best effort; the docs must always load
|
|
176
|
+
return None
|
|
177
|
+
return {"status": status, "body": body}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _without_read_only(schema: dict[str, Any]) -> dict[str, Any]:
|
|
181
|
+
schema = flatten(schema)
|
|
182
|
+
properties = schema.get("properties")
|
|
183
|
+
if not isinstance(properties, dict):
|
|
184
|
+
return schema
|
|
185
|
+
kept = {
|
|
186
|
+
name: prop
|
|
187
|
+
for name, prop in properties.items()
|
|
188
|
+
if not (isinstance(prop, dict) and prop.get("readOnly"))
|
|
189
|
+
}
|
|
190
|
+
return {**schema, "properties": kept}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _template_params(path: str) -> list[str]:
|
|
194
|
+
return re.findall(r"\{([^{}]+)\}", path)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _slug(text: str) -> str:
|
|
198
|
+
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
api_mock_ai/errors.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Exceptions raised by api-mock-ai."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ApiMockError(Exception):
|
|
5
|
+
"""Base class for all api-mock-ai errors."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SpecError(ApiMockError):
|
|
9
|
+
"""The OpenAPI document could not be loaded or is not supported."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GenerationError(ApiMockError):
|
|
13
|
+
"""Mock data could not be generated."""
|