Skip to main content

api-mock-ai

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

CI PyPI Python License: MIT

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
pip install api-mock-ai
api-mock-ai serve openapi.yaml
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

Full documentation lives in docs/ and can be served with mkdocs serve.

Installation

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:

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 or uv:

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:

api-mock-ai serve examples/ecommerce.yaml --locale pk
+------------------------------- 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:

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:

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.
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:

{ "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:

{
  "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:

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

Or per request, with headers:

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

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

A sample account generated with --locale pk:

{
  "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.

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

See docs/documentation-page.md.

CLI reference

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.

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 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

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

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

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 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.
  • $refs 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 $refs, 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

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 and CHANGELOG.md.

License

MIT

Metadata

Release files for api-mock-ai 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for api-mock-ai 0.1.0
File Size Uploaded Provenance Actions
api_mock_ai-0.1.0.tar.gz 189.4 kB With provenance Details for api_mock_ai-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for api-mock-ai 0.1.0
File Interpreter ABI Platform Actions
api_mock_ai-0.1.0-py3-none-any.whl Python 3 none any Details for api_mock_ai-0.1.0-py3-none-any.whl

Total release size: 258.4 kB

Release files / api_mock_ai-0.1.0.tar.gz

Download URL api_mock_ai-0.1.0.tar.gz
Size 189.4 kB
Tags Source
SHA-256 checksum
How to use checksums
109fcd398dc12ca7fe7409cd2082ebe0d7ba8612383ae5cda76514d9aa518309
BLAKE2b-256 checksum
How to use checksums
da06c2562836edec90d7e4d5ee4568c08b9ce393918e9edf9e31a4716fc6bb37
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / api_mock_ai-0.1.0-py3-none-any.whl

Download URL api_mock_ai-0.1.0-py3-none-any.whl
Size 69.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3d11c155a45057cd00646d075463d34931cbce00a30d201588aa5bc7ec1e010e
BLAKE2b-256 checksum
How to use checksums
fc246f07366c9f32f1b83fc57bf250147c530ea7a04223ccefafcf5f0a3d54f2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for api-mock-ai 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for api_mock_ai-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page