Skip to main content

Scan frontend codebases, discover API calls, generate realistic mock responses, and launch a local mock backend server.

Project description

MockMyAPI 🚀

Automatic API discovery, intelligent mock generation, and instant local backend server for frontend developers.

PyPI Python Version License: MIT

MockMyAPI analyzes your frontend codebase (React, Vue, Angular, Next.js, Svelte, etc.), automatically discovers API endpoints called via fetch() or axios, generates realistic mock JSON responses using intelligent field inference, and launches a local FastAPI server that your frontend can immediately interact with.


⚡ Quick Start (TL;DR)

# Install package
pip install mock-my-api

# Option A: Scan & serve in a single command
mock-my-api scan ./frontend --serve

# Option B: Run via OpenAPI 3.x spec directly
mock-my-api openapi ./openapi.yaml --serve

Your frontend can now immediately send HTTP calls to http://localhost:5050!


💡 Why MockMyAPI?

Frontend development frequently stalls waiting for backend endpoints to be built, deployed, or stabilized. MockMyAPI solves this bottleneck by turning your frontend source code directly into a functional mock server:

  • Zero Manual Setup: Scans JavaScript, TypeScript, JSX, and TSX files to find API calls automatically.
  • Intelligent Data Generation: Recognizes field names (email, avatar, price, inStock, createdAt) and uses Faker to populate contextually accurate mock JSON.
  • Preserves Custom Responses: Merges newly discovered endpoints into .mock-my-api.yaml without overwriting your manually edited mock data.
  • Stateful In-Memory CRUD: Test real data mutations (POST, PUT, PATCH, DELETE) with live in-memory state persistence.
  • Failure State Simulation: Test frontend resilience with latency (slow), random HTTP error codes (errors), or service unavailability (offline).
  • OpenAPI 3.x Integration: Parse OpenAPI specifications (.yaml or .json) with full $ref resolution and example extraction.
  • Hybrid Proxy Fallback: Forward unmatched API requests to your live staging/production backend seamlessly.

🔄 Architecture & Data Flow

Frontend API Calls (fetch / axios)
                │
                ▼
      MockMyAPI AST & Regex Scanner
                │
                ▼
   Endpoint Normalization & Deduplication
     (`/api/users/${id}` → `/api/users/:id`)
                │
                ▼
      Fake Data & Type Inference Engine
   (Faker field resolution + Resource templates)
                │
                ▼
     .mock-my-api.yaml (Configuration)
                │
                ▼
      FastAPI Dynamic Server + Middleware
     (CORS + Redaction + Logging + Scenarios)
                │
                ▼
Frontend Receives Realistic Mock Responses

📦 Installation

pip install mock-my-api

Requires Python 3.9 or higher.


💻 Detected Frontend Code Patterns

MockMyAPI automatically scans .js, .ts, .jsx, .tsx, .mjs, and .cjs files, ignoring node_modules, .git, dist, build, .next, and build outputs.

1. Standard Fetch Calls

fetch("/api/users");
fetch(`/api/users/${userId}`);
fetch("/api/orders", { method: "POST", body: JSON.stringify(data) });

2. Axios Method Calls

axios.get("/api/users");
axios.post("/api/orders", data);
axios.put(`/api/users/${id}`, data);
axios.delete("/api/users/1");

3. Custom Axios Instances

const api = axios.create({
    baseURL: "/api/v1"
});

api.get("/products"); // Discovered as: /api/v1/products
api.post("/orders", data);

Common instance variable names detected automatically: api, http, client, service, httpClient, apiClient.

4. Axios Configuration Objects

axios({
    method: "POST",
    url: "/api/auth/login",
    data: { username, password }
});

📖 Detailed CLI Command Reference

mock-my-api scan <directory>

Scans the frontend source code and generates or merges .mock-my-api.yaml.

mock-my-api scan ./frontend

Options:

Flag Short Description Default
--serve -s Immediately start the mock server after scanning false
--port -p Server port 5050
--host -h Server host address 127.0.0.1
--stateful Enable stateful in-memory CRUD operations false
--scenario Activate simulation scenario (slow, errors, offline) None
--proxy Backend URL to forward unmatched requests to None
--verbose -v Enable detailed request header/query logging false

mock-my-api serve

Launches the local FastAPI mock backend server using .mock-my-api.yaml.

mock-my-api serve --port 5050

Options:

Flag Short Description Default
--port -p Server port 5050
--host -h Server host address 127.0.0.1
--stateful Maintain in-memory state across CRUD operations false
--scenario Activate simulation scenario (slow, errors, offline) None
--proxy Real backend URL for proxy fallback None
--config -c Custom path to configuration file .mock-my-api.yaml
--openapi -o Import OpenAPI spec file before launching server None
--verbose -v Enable verbose request logging in terminal false

mock-my-api openapi <spec-file>

Generates mock endpoints directly from an OpenAPI 3.x specification (.yaml or .json).

mock-my-api openapi ./openapi.yaml --serve
  • Extracts explicit example / examples from schema properties.
  • Resolves internal JSON references ($ref: '#/components/schemas/User').
  • Automatically populates missing response fields using Faker.

mock-my-api doctor

Runs interactive health checks verifying your development setup.

mock-my-api doctor

Checks performed:

  • ✅ Python version compatibility
  • .mock-my-api.yaml syntax & structure validity
  • ✅ Route collisions & duplicate path detection
  • ✅ Port 5050 availability check
  • ✅ Installed dependency health check

🛠️ Advanced Features

1. Stateful In-Memory CRUD Mode (--stateful)

When launching with --stateful, MockMyAPI maintains a live in-memory store for endpoints matching standard resource conventions (e.g., /api/users, /api/users/:id).

mock-my-api serve --stateful
  • GET /api/users: Returns initial user collection.
  • POST /api/users: Assigns auto-incrementing id and adds item to collection.
  • GET /api/users/101: Retrieves created item by ID.
  • PUT /api/users/101 / PATCH /api/users/101: Updates item attributes in-memory.
  • DELETE /api/users/101: Removes item from collection.

2. Simulation Scenarios (--scenario)

Simulate real-world network failure conditions to verify frontend resilience:

# Inject 1-3 seconds of latency into every response
mock-my-api serve --scenario slow

# Randomly return HTTP errors (400, 401, 403, 404, 429, 500, 503) on 30% of requests
mock-my-api serve --scenario errors

# Simulate service outage with 503 errors and Retry-After headers
mock-my-api serve --scenario offline

You can also specify endpoint-level delay or error rates in .mock-my-api.yaml:

endpoints:
  - method: GET
    path: /api/checkout
    delay: 1500        # 1.5 seconds delay
    error_rate: 0.2    # 20% error chance

3. Proxy Fallback Mode (--proxy)

If your frontend makes calls to endpoints not yet configured in .mock-my-api.yaml, MockMyAPI transparently forwards those requests to a real backend:

mock-my-api serve --proxy https://api.staging.example.com
  • Local mock responses take priority.
  • Unmatched endpoints are proxied to https://api.staging.example.com.
  • Hop-by-hop headers (Host, Connection, Transfer-Encoding) are filtered safely.

4. Automatic Sensitive Data Redaction

MockMyAPI terminal logs automatically redact sensitive headers and body fields to prevent leaking credentials in terminal output or video recordings:

  • Redacted Headers: Authorization, Cookie, Set-Cookie, X-API-Key, X-Auth-Token
  • Redacted Body Fields: password, secret, token, api_key, credit_card, ssn

⚙️ Configuration Reference (.mock-my-api.yaml)

version: 1
server:
  host: 127.0.0.1
  port: 5050
  cors: true
  cors_origins:
    - "*"
  verbose: false

endpoints:
  - method: GET
    path: /api/users
    status: 200
    delay: 0
    error_rate: 0.0
    response:
      - id: 1
        name: Rahul Sharma
        email: rahul@example.com
        avatar: https://dummyimage.com/300x300
        active: true
        created_at: "2026-07-21T10:30:00Z"

  - method: POST
    path: /api/orders
    status: 201
    response:
      id: 101
      status: created
      total: 1499.00

  - method: DELETE
    path: /api/users/:id
    status: 204
    response: null

🧪 Development & Testing

Clone the repository and install in editable mode:

git clone https://github.com/buntychakraborty/mock-my-api.git
cd mock-my-api
python3 -m pip install -e ".[dev]"

Run the complete test suite:

pytest -v

All 26 unit and end-to-end integration tests verify scanner accuracy, path normalization, fake data inference, FastAPI route handler generation, stateful CRUD, proxy fallback, and scenario execution.


📄 License

Distributed under the MIT License. See LICENSE for more details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mock_my_api-1.0.1.tar.gz (45.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mock_my_api-1.0.1-py3-none-any.whl (48.9 kB view details)

Uploaded Python 3

File details

Details for the file mock_my_api-1.0.1.tar.gz.

File metadata

  • Download URL: mock_my_api-1.0.1.tar.gz
  • Upload date:
  • Size: 45.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for mock_my_api-1.0.1.tar.gz
Algorithm Hash digest
SHA256 e449e539f2222ac9060d8082fb249c6fda3d778ae3d19fe4f25bdce40cc98c27
MD5 6b9a6d186221f3a293a2149c4536e137
BLAKE2b-256 2380db369da1818e3f3e607cde99a51a4967bdacfe662c47a6df6466cfe0e834

See more details on using hashes here.

File details

Details for the file mock_my_api-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: mock_my_api-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 48.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for mock_my_api-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 56ae6bb3a19096d7c51fbc897ea06b53166c2a1b7be7d8d3204e7a2c86e7863c
MD5 cae00bc42b69e254efa6f104437624fc
BLAKE2b-256 e19f70003dbf42b21ac1fb86e2268f3bc98ba641bf3409bd42e39d59c09dfa72

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page