Metadata-Version: 2.5
Name: api-mock-ai
Version: 0.1.0
Summary: Realistic, stateful mock APIs from any OpenAPI spec, powered by Faker or LLMs.
Project-URL: Homepage, https://github.com/kashy96/api-mock-ai
Project-URL: Documentation, https://kashy96.github.io/api-mock-ai
Project-URL: Repository, https://github.com/kashy96/api-mock-ai
Project-URL: Issues, https://github.com/kashy96/api-mock-ai/issues
Project-URL: Changelog, https://github.com/kashy96/api-mock-ai/blob/main/CHANGELOG.md
Author-email: Muhammad Kashif <engrmuhammadkashif96@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: api,faker,fastapi,frontend,llm,mock,mock-server,openapi,swagger,synthetic-data,testing
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Software Development :: Testing :: Mocking
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: faker>=24.0
Requires-Dist: fastapi>=0.110
Requires-Dist: httpx>=0.27
Requires-Dist: jsonschema>=4.21
Requires-Dist: pyyaml>=6.0
Requires-Dist: rich>=13.0
Requires-Dist: typer>=0.12
Requires-Dist: uvicorn>=0.29
Provides-Extra: ai
Requires-Dist: litellm>=1.40; extra == 'ai'
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
Description-Content-Type: text/markdown

# api-mock-ai

**Realistic, stateful mock APIs from any OpenAPI spec, powered by Faker or LLMs.**

[![CI](https://github.com/kashy96/api-mock-ai/actions/workflows/ci.yml/badge.svg)](https://github.com/kashy96/api-mock-ai/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/api-mock-ai.svg)](https://pypi.org/project/api-mock-ai/)
[![Python](https://img.shields.io/pypi/pyversions/api-mock-ai.svg)](https://pypi.org/project/api-mock-ai/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/kashy96/api-mock-ai/blob/main/LICENSE)

Frontend developers often wait for the backend. Mock servers help, but most of them
return placeholder data like `"name": "string"` and forget everything between requests.

`api-mock-ai` reads your OpenAPI spec and starts a mock server that:

- returns **realistic data**: real-looking names, emails, prices, addresses and dates,
  chosen from field names and formats
- is **stateful**: `POST` creates a record, `GET` returns it, `DELETE` removes it
- keeps **relations consistent**: `GET /users/42/orders` only returns user 42's orders,
  and `order.items[].productId` points to products that exist
- can generate data with **any LLM** (OpenAI, Anthropic, Gemini, or a local model through
  Ollama), cached so the model is called only once
- speaks your users' **country**: `--locale pk`, `in`, `eu`, `uk`, `us`... with local phone
  formats, cities, currency, price levels and **banking data** (banks, IBAN, BIC, IFSC)
- serves **interactive API documentation** at `/docs`, with live examples and a "Try it" console
- validates requests against the spec, supports pagination, filtering, sorting and search,
  and can **simulate latency and errors**

```bash
pip install api-mock-ai
api-mock-ai serve openapi.yaml
```

```http
GET /api/users/96da1dac-72ff-4d2a-b86e-cbe06b65a6a4

{
  "id": "96da1dac-72ff-4d2a-b86e-cbe06b65a6a4",
  "firstName": "Yaman",
  "lastName": "Ayyubi",
  "email": "yaman.ayyubi18@gmail.com",
  "phone": "+92 308 5918715",
  "role": "customer",
  "address": { "street": "386 Qamar Radial", "city": "Lahore", "postalCode": "92007", "country": "Pakistan" },
  "createdAt": "2026-05-01T16:28:22Z",
  "isVerified": true
}
```

---

## Contents

- [Installation](#installation)
- [Quick start](#quick-start)
- [Features](#features)
- [Countries, regions and banking data](#countries-regions-and-banking-data)
- [Interactive documentation](#interactive-documentation)
- [CLI reference](#cli-reference)
- [AI-generated data](#ai-generated-data)
- [Use it from Python and pytest](#use-it-from-python-and-pytest)
- [Docker](#docker)
- [How it works](#how-it-works)
- [Comparison](#comparison)
- [Limitations and roadmap](#limitations-and-roadmap)
- [Development](#development)

Full documentation lives in [`docs/`](https://github.com/kashy96/api-mock-ai/blob/main/docs/index.md) and can be served with `mkdocs serve`.

## Installation

```bash
pip install api-mock-ai            # Faker-based data, no API key needed
pip install "api-mock-ai[ai]"      # adds LLM support through LiteLLM
```

Or install the latest version straight from GitHub:

```bash
pip install "git+https://github.com/kashy96/api-mock-ai.git"
pip install "api-mock-ai[ai] @ git+https://github.com/kashy96/api-mock-ai.git"
```

To run it without installing it into a project, use [pipx](https://pipx.pypa.io) or
[uv](https://docs.astral.sh/uv/):

```bash
pipx run api-mock-ai serve openapi.yaml
uvx api-mock-ai serve openapi.yaml
```

Requires Python 3.10 or newer.

## Quick start

Try it with the bundled example, a small e-commerce API:

```bash
api-mock-ai serve examples/ecommerce.yaml --locale pk
```

```text
+------------------------------- api-mock-ai -------------------------------+
| ShopSphere Commerce API 2.3.0  |  mocked by api-mock-ai 0.1.0             |
|                                                                           |
| API     http://localhost:8000/api                                         |
| Docs    http://localhost:8000/docs                                        |
| Admin   http://localhost:8000/__mock__/resources                          |
|                                                                           |
| Data    Faker  |  10 per resource  |  seed 42                            |
| Locale  pk: Pakistan (en_PK, currency PKR)                                |
|                                                                           |
| Resources: /api/users, /api/products, /api/categories,                    |
|            /api/users/{userId}/orders                                     |
+---------------------------------------------------------------------------+
```

Then:

```bash
curl "http://localhost:8000/api/users?page=1&per_page=5"
curl "http://localhost:8000/api/products?sort=-price&limit=3"
curl -X POST http://localhost:8000/api/users \
     -H "Content-Type: application/json" \
     -d '{"firstName": "Ali", "lastName": "Raza", "email": "ali@example.com"}'
```

Open **http://localhost:8000/docs** for interactive documentation of *your* API, where
"Try it" sends real requests to the mock.

To check how a spec will be mocked without starting a server:

```bash
api-mock-ai validate examples/ecommerce.yaml
```

## Features

### Realistic data from field names, formats and context

| Field | Example value |
|---|---|
| `email` (or `format: email`) | `ayesha.khan42@gmail.com`, matching the name in the same object |
| `firstName`, `lastName`, `fullName`, `username` | one consistent person per object |
| `name` on a *user* / *product* / *pet* / *category* / *company* | `Ayesha Khan` / `Wireless Headphones` / `Biscuit` / `Electronics` / `Acme Ltd` |
| `price`, `amount`, `total` | `315.18` |
| `createdAt`, `updated_at`, `format: date-time` | `2026-05-01T16:28:22Z` |
| `avatarUrl`, `imageUrl` | `https://picsum.photos/seed/1680/400/300` (a real image) |
| `phone`, `city`, `country`, `postalCode` | country-aware (`--locale pk`, `in`, `eu`, `de_DE`, ...) |
| `iban`, `bic`, `bankName`, `accountNumber` | real-format bank details for the country |
| `status` | `active` / `pending`, or `shipped` / `delivered` on orders |

Schema constraints always win: `enum`, `const`, `minimum`/`maximum`, `minLength`/`maxLength`,
`minItems`/`maxItems`, `allOf`/`oneOf`/`anyOf` and `nullable` are respected, and every
generated record is valid against its schema (this is tested).

### Server-side fields

When a request can't contain a field the stored record has (for example
`POST /transfers` takes only an amount and a payee), the mock fills it in like a real
server would: ids, timestamps, `readOnly` fields, a reference number, a status. Order
totals are computed from their line items.

### Stateful CRUD

Collections are detected automatically from your paths:

| Request | Behaviour |
|---|---|
| `GET /pets` | list (with filtering, search, sorting, pagination) |
| `POST /pets` | validate the body, assign an id, add timestamps, store it, `201` |
| `GET /pets/{petId}` | the stored record, or `404` |
| `PUT /pets/{petId}` | replace (keeps `id` and `createdAt`) |
| `PATCH /pets/{petId}` | merge |
| `DELETE /pets/{petId}` | remove (and its nested children), `204` |

Nested collections get several records per parent: every account has its own statement,
every user has a few orders.

Changes live in memory until you restart or call `POST /__mock__/reset`.

### Relations

- **Nested resources:** `/users/{userId}/orders` only lists that user's orders, returns `404`
  for unknown users, and other users' orders are not reachable through it.
- **Foreign keys:** fields like `categoryId` or `items[].productId` point to existing records.
- **Embedded objects:** `product.category` is a copy of a real category.
- **Custom routes reuse real data:** `GET /users/me` returns one of the generated users.

### Lists: pagination, filtering, sorting, search

| Query | Effect |
|---|---|
| `?status=active` | exact match on any field |
| `?q=khan` (or `search`, `query`) | case-insensitive search in all text fields |
| `?sort=price`, `?sort=-price`, `?sort_by=price&order=desc` | sorting |
| `?limit=10&offset=20`, `?page=3&per_page=10` | pagination (`size`, `pageSize`, `skip`, `take` also work) |

If your spec wraps lists in an envelope, it is filled in correctly:

```json
{ "data": [ ... ], "meta": { "total": 57, "page": 3, "per_page": 10, "total_pages": 6 } }
{ "items": [ ... ], "total": 57, "limit": 10, "offset": 20, "hasMore": true }
```

### Request validation

Bodies are checked against the spec; mistakes get a clear `422`:

```json
{
  "error": "Request body does not match the API spec",
  "status": 422,
  "details": ["species: 'dragon' is not one of ['dog', 'cat', 'rabbit', 'parrot', 'hamster']"]
}
```

`readOnly` fields are not required in requests, `PATCH` bodies may be partial, and
`--no-validate` turns validation off.

### Chaos testing

Test loading spinners and error states in your frontend:

```bash
api-mock-ai serve openapi.yaml --latency 200-1500 --error-rate 0.1
```

Or per request, with headers:

```bash
curl -H "X-Mock-Delay: 3000" http://localhost:8000/api/users   # wait 3 s
curl -H "X-Mock-Status: 503" http://localhost:8000/api/users   # force an error
```

### Admin endpoints

| Endpoint | Purpose |
|---|---|
| `GET /docs` | interactive documentation |
| `GET /openapi.json` | the original spec, pointed at the mock |
| `GET /__mock__/health` | health check |
| `GET /__mock__/resources` | detected resources and record counts |
| `GET /__mock__/data` | every record currently stored |
| `POST /__mock__/reset` | throw away changes and restore the generated data |

## Countries, regions and banking data

```bash
api-mock-ai serve examples/banking.yaml --locale pk   # Pakistan: PKR, +92, HBL/Meezan, PK IBANs
api-mock-ai serve examples/banking.yaml --locale in   # India: INR, +91, SBI/HDFC, IFSC, PAN, UPI
api-mock-ai serve examples/banking.yaml --locale eu   # euro area: each record from another country
```

| `--locale` | Data |
|---|---|
| `pk`, `in`, `us`, `uk`, `de`, `fr`, `es`, `it`, `nl` | one country, with its phone format, cities, currency, price level and banks |
| `eu`, `south_asia` | a region: each record comes from one of its countries |
| `de_DE`, `ja_JP`, ... | any [Faker locale](https://faker.readthedocs.io/en/master/locales.html) |

A sample account generated with `--locale pk`:

```json
{
  "accountTitle": "Wafa Wadood",
  "bankName": "Allied Bank",
  "iban": "PK46ABPA6426212997220033",
  "bic": "ABPAPKAN",
  "accountNumber": "5807302157368193",
  "currency": "PKR",
  "balance": 390420.1
}
```

The IBAN has valid check digits, and the bank name, BIC and IBAN bank code all describe the
same bank. Transactions get a type, a matching narration ("Salary credit", "ATM cash
withdrawal"), a reference and a channel. See [docs/data-packs.md](https://github.com/kashy96/api-mock-ai/blob/main/docs/data-packs.md).

## Interactive documentation

Every mock serves API documentation at **`/docs`**: endpoints grouped by tag, schemas,
live examples from the mock, and a "Try it" console with pre-filled ids that exist, error
simulation and cURL export. It works offline, in light and dark mode, and on phones.

![api-mock-ai documentation page](https://raw.githubusercontent.com/kashy96/api-mock-ai/main/docs/images/docs-page.jpg)

See [docs/documentation-page.md](https://github.com/kashy96/api-mock-ai/blob/main/docs/documentation-page.md).

## CLI reference

```text
api-mock-ai serve SPEC [options]      start a mock server
api-mock-ai generate SPEC [options]   print or save mock data as JSON
api-mock-ai validate SPEC             check a spec and show how routes are mocked
api-mock-ai --version
```

`SPEC` is a path or an `http(s)` URL to an OpenAPI 3.0 or 3.1 document (YAML or JSON).

| Option | Default | Description |
|---|---|---|
| `--host` | `127.0.0.1` | interface to bind (use `0.0.0.0` in Docker) |
| `--port`, `-p` | `8000` | port |
| `--count`, `-n` | `10` | records per resource |
| `--seed` | `42` | same seed, same data |
| `--locale`, `-l` | `en_US` | country (`pk`, `in`, `us`, `uk`, `de`...), region (`eu`) or Faker locale |
| `--ai` | off | generate data with an LLM |
| `--model`, `-m` | `$API_MOCK_AI_MODEL` | LiteLLM model for `--ai` |
| `--latency` | `0` | delay in ms: `300` or `100-500` |
| `--error-rate` | `0` | share of requests (0-1) that fail with 500/502/503 |
| `--cors / --no-cors` | on | allow requests from other origins |
| `--validate / --no-validate` | on | validate request bodies |
| `--base-path` | from `servers` | route prefix, e.g. `/v1`; `/` for none |
| `--cache-dir` | `.api-mock-ai` | AI data cache |
| `--refresh` | off | regenerate AI data instead of using the cache |
| `--output`, `-o` | stdout | (`generate`) file to write |

## AI-generated data

Faker is fast and free. An LLM understands *meaning*: product descriptions that match
product names, reviews that match ratings, bios that match job titles.

```bash
pip install "api-mock-ai[ai]"

# Local and free, with Ollama
api-mock-ai serve openapi.yaml --ai --model ollama/llama3.1

# Hosted models (LiteLLM reads the usual API key variables)
export ANTHROPIC_API_KEY=...
api-mock-ai serve openapi.yaml --ai --model anthropic/claude-haiku-5-5
```

Any [LiteLLM model string](https://docs.litellm.ai/docs/providers) works.

How it stays reliable:

1. The LLM is called **once per resource at startup**, in batches, never per request.
2. Every value it returns is **validated against the schema**; missing or invalid values are
   replaced with Faker values. A bad model answer can't break your mock.
3. If the model is unreachable, generation **falls back to Faker** with a warning.
4. Results are **cached** in `.api-mock-ai/`, keyed by the spec, model, count, seed and locale.
   Restarts are instant and free; use `--refresh` to regenerate.

## Use it from Python and pytest

```python
from fastapi.testclient import TestClient
from api_mock_ai import MockConfig, create_app

app = create_app("openapi.yaml", MockConfig(count=20, locale="uk", seed=7))
client = TestClient(app)


def test_checkout_flow():
    product = client.get("/api/products").json()["items"][0]
    ...
```

`create_app` returns a normal FastAPI app, so you can also serve it with any ASGI server.

Pre-generated data (`api-mock-ai generate spec.yaml -o data.json`) is useful as test
fixtures or for seeding a development database.

## Docker

```bash
docker build -t api-mock-ai .
docker run --rm -p 8000:8000 -v "$PWD/openapi.yaml:/spec/openapi.yaml" api-mock-ai
```

## How it works

```text
openapi.yaml
     |
     v
+-------------+   +---------------------+   +-----------------+
| Spec loader |-->| Resource detection  |-->| Seed generator  |
| YAML / JSON |   | collections, items, |   | Faker or LLM,   |
| $ref resolve|   | parents, id fields  |   | linked + cached |
+-------------+   +---------------------+   +--------+--------+
                                                     v
                         +-----------------------------------------------+
                         | FastAPI server                                |
                         | routing -> validation -> store (CRUD) -> shape|
                         | + CORS, chaos middleware, admin API, docs     |
                         +-----------------------------------------------+
```

See [docs/how-it-works.md](https://github.com/kashy96/api-mock-ai/blob/main/docs/how-it-works.md) for the design decisions.

## Comparison

| | Static examples | Random schema values | **api-mock-ai** |
|---|---|---|---|
| Looks like real data | only where examples exist | no (`"string"`, `"abc123"`) | yes |
| Remembers `POST`/`DELETE` | no | no | yes |
| Consistent relations | no | no | yes |
| Optional LLM generation | no | no | yes, cached |

## Limitations and roadmap

Current limitations (contributions welcome):

- Swagger 2.0 must be converted to OpenAPI 3 first.
- `$ref`s to *other files* are not resolved yet (local `#/...` refs are).
- `pattern` constraints on strings are not used for generation.
- Data lives in memory; it resets on restart.
- Non-JSON bodies (XML, form data, file uploads) are accepted but not validated.

Planned: external `$ref`s, persisting data to a file, response examples as hints, webhooks,
a GitHub Action, and a small benchmark of data realism against other mock tools.

## Development

```bash
git clone https://github.com/kashy96/api-mock-ai
cd api-mock-ai
python -m venv .venv && source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -e ".[dev,ai]"
pytest --cov
ruff check . && ruff format --check .
```

See [CONTRIBUTING.md](https://github.com/kashy96/api-mock-ai/blob/main/CONTRIBUTING.md) and [CHANGELOG.md](https://github.com/kashy96/api-mock-ai/blob/main/CHANGELOG.md).

## License

[MIT](https://github.com/kashy96/api-mock-ai/blob/main/LICENSE)
