Metadata-Version: 2.4
Name: mock-my-api
Version: 1.0.1
Summary: Scan frontend codebases, discover API calls, generate realistic mock responses, and launch a local mock backend server.
Project-URL: Homepage, https://github.com/buntychakraborty/mock-my-api
Project-URL: Repository, https://github.com/buntychakraborty/mock-my-api
Project-URL: Issues, https://github.com/buntychakraborty/mock-my-api/issues
Author: Bunty Chakraborty
License-Expression: MIT
License-File: LICENSE
Keywords: api,development,fastapi,frontend,mock,testing
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
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 :: Software Development :: Testing
Classifier: Topic :: Software Development :: Testing :: Mocking
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: eval-type-backport>=0.1.0; python_version < '3.10'
Requires-Dist: faker>=19
Requires-Dist: fastapi>=0.100
Requires-Dist: httpx>=0.24
Requires-Dist: pydantic>=2
Requires-Dist: pyyaml>=6
Requires-Dist: rich>=13
Requires-Dist: typer>=0.9
Requires-Dist: uvicorn[standard]>=0.23
Provides-Extra: dev
Requires-Dist: coverage>=7; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff>=0.1; extra == 'dev'
Description-Content-Type: text/markdown

# MockMyAPI 🚀

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

[![PyPI](https://img.shields.io/pypi/v/mock-my-api.svg)](https://pypi.org/project/mock-my-api/)
[![Python Version](https://img.shields.io/pypi/pyversions/mock-my-api.svg)](https://pypi.org/project/mock-my-api/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/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)

```bash
# 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

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

```bash
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
```typescript
fetch("/api/users");
fetch(`/api/users/${userId}`);
fetch("/api/orders", { method: "POST", body: JSON.stringify(data) });
```

### 2. Axios Method Calls
```typescript
axios.get("/api/users");
axios.post("/api/orders", data);
axios.put(`/api/users/${id}`, data);
axios.delete("/api/users/1");
```

### 3. Custom Axios Instances
```typescript
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
```typescript
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`.

```bash
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`.

```bash
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`).

```bash
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.

```bash
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`).

```bash
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:

```bash
# 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`:
```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:

```bash
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`)

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

```bash
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:

```bash
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`](file:///Users/buntychakraborty/Documents/Pentesting/mock-my-api/LICENSE) for more details.
