PHPackages                             taoshan98/laravel-api-watcher - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. taoshan98/laravel-api-watcher

ActiveLibrary[API Development](/categories/api)

taoshan98/laravel-api-watcher
=============================

A modern Laravel package to intercept, analyze, and visualize API requests.

v2.0.2(3w ago)287MITPHPPHP ^8.2CI passing

Since Feb 19Pushed 3w agoCompare

[ Source](https://github.com/Taoshan98/laravel-api-watcher)[ Packagist](https://packagist.org/packages/taoshan98/laravel-api-watcher)[ RSS](/packages/taoshan98-laravel-api-watcher/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (4)Dependencies (16)Versions (5)Used By (0)

Laravel API Watcher 🦅 (V2.0.0 - Full Observability Suite)
=========================================================

[](#laravel-api-watcher--v200---full-observability-suite)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c0a3a71a63b890b8c68b0c98332e074ab80d00cb8a510740a5f25ac33029b290/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74616f7368616e39382f6c61726176656c2d6170692d776174636865722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/taoshan98/laravel-api-watcher)[![Total Downloads](https://camo.githubusercontent.com/669e2fdeba12aae3eb5caf6a48bb8500c5484df1d0334738a8d501ab9e0b71c7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f74616f7368616e39382f6c61726176656c2d6170692d776174636865722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/taoshan98/laravel-api-watcher)[![License](https://camo.githubusercontent.com/ea5f3f3baa2bdb864f6932816691b48914f931d57d1cae3f712d4f10688ab330/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f74616f7368616e39382f6c61726176656c2d6170692d776174636865722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/taoshan98/laravel-api-watcher)[![PHPStan Level 5](https://camo.githubusercontent.com/049009b90579d95dddbea996abca7b1f3100ae85981e32d81c50863f5fbf67aa/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d4c6576656c253230352532305061737365642d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://phpstan.org/)

**Laravel API Watcher** is a zero-latency, production-ready **360° API Observability Suite** for Laravel applications. It monitors both **Ingress** (incoming API requests from users/clients) and **Egress** (outgoing HTTP requests to third-party services like Stripe, OpenAI, or Twilio) without impacting application response times.

[![Dashboard Preview](./screenshots/dashboard.png)](./screenshots/dashboard.png)

---

🔬 System Architecture &amp; Technical Features
----------------------------------------------

[](#-system-architecture--technical-features)

### 1. ⚡ Zero-Latency Ingress Logging

[](#1--zero-latency-ingress-logging)

- **Lifecycle Hook**: Capture logic executes strictly after HTTP responses are dispatched to clients via Laravel's `terminating` middleware callback (`dispatch()->afterResponse()`). The client never waits for DB logging operations.
- **Fail-Safe Mechanism**: All capture routines operate inside isolated `try-catch` blocks. Logging or database failures are swallowed silently, ensuring 100% uptime for core application routes.

### 2. 🌐 Egress Observability (Outgoing HTTP Interception)

[](#2--egress-observability-outgoing-http-interception)

- **Automatic Event Interception**: Listens natively to `Illuminate\Http\Client\Events\ResponseReceived` and `Illuminate\Http\Client\Events\ConnectionFailed`.
- **Parent-Child Request Correlation**: Automatically attaches a unique UUID (`api_watcher_request_id`) to the incoming request context, linking all outgoing HTTP calls triggered during that request execution.
- **Dedicated Egress Dashboard**: View latencies, status codes, payload samples, and error rates per third-party domain (e.g. `api.stripe.com`, `api.openai.com`).

### 3. 🎯 Intelligent Sampling Engine

[](#3--intelligent-sampling-engine)

To optimize storage in high-volume production environments, the sampling algorithm evaluates every request against configured rules:

```
public function shouldSample(int $statusCode, float $durationMs): bool
{
    // Always sample 4xx/5xx errors
    if ($this->alwaysSampleErrors && $statusCode >= 400) {
        return true;
    }
    // Always sample slow requests exceeding configured threshold
    if ($this->alwaysSampleSlow && $durationMs >= $this->slowThresholdMs) {
        return true;
    }
    // Apply probabilistic sampling for 2xx OK requests
    return (mt_rand(1, 100) / 100.0) samplingRate;
}
```

### 4. 🚀 High-Throughput Redis List Buffering

[](#4--high-throughput-redis-list-buffering)

For high-traffic APIs (thousands of req/sec), bypass direct SQL writes during request handling:

```
Incoming Request -> Redis List Buffer (rpush) -> Background Worker (api-watcher:flush) -> Database Batch Insert

```

- **Memory Efficient**: Buffers raw payload data into Redis lists using `rpush`.
- **Artisan Worker**: `php artisan api-watcher:flush` pops buffered items via `lpop` and executes `DatabaseDriver::storeBatch()` using bulk `insert()`.

### 5. 🛡️ Multilevel Data Redaction &amp; Privacy (GDPR / PCI-DSS)

[](#5-️-multilevel-data-redaction--privacy-gdpr--pci-dss)

- **Recursive Array &amp; String Sanitization**: `SensitiveDataRedactor` recursively inspects arrays, JSON strings, and `application/x-www-form-urlencoded` query strings.
- **Custom Callbacks**: Developers can register custom closures to redact application-specific sensitive fields:

```
'redaction' => [
    'fields' => ['password', 'secret', 'credit_card', 'authorization', 'token'],
    'replacement' => '[REDACTED]',
    'callback' => function (array $data) {
        unset($data['ssn']);
        return $data;
    },
]
```

### 6. 🧠 Diagnostic &amp; Analytics Algorithmic Engine

[](#6--diagnostic--analytics-algorithmic-engine)

- **Visual Waterfall Execution Timeline**: Correlates DB query execution time (`DB::listen`) with outgoing HTTP calls.
- **Side-by-Side Request Diffing**: `RequestDiff::compare($req1, $req2)` computes structural JSON deltas, duration deltas, and header variations between any two requests.
- **Schema Drift Detector**: `SchemaDriftDetector` computes a structural type-mapping hash (`describeArraySchema`) for JSON responses across time to notify developers of breaking payload changes.
- **Predictive Latency Trend Analyzer**: `TrendAnalyzer` compares the 24-hour moving average against a 7-day baseline: $$\\Delta% = \\frac{\\bar{T}*{24h} - \\bar{T}*{baseline}}{\\bar{T}\_{baseline}} \\times 100$$ Triggers a degradation warning when latency increases by $\\ge 25%$.
- **Bot &amp; Abuse Detector**: `AbuseDetector` analyzes IP address distributions over a 60-minute window, flagging IPs with high request volumes or error rates ($\\ge 30%$ 401/429/403 errors).

### 7. 📦 Memory-Efficient Streaming Exporters

[](#7--memory-efficient-streaming-exporters)

- **Chunked Exporters**: Exporting logs via `php artisan api-watcher:export --format=json` uses `cursor()` / `chunk(500)` with direct file stream pointers (`fwrite`), maintaining flat RAM usage even on multi-million row tables.
- **Postman Collection v2.1 Exporter**: `php artisan api-watcher:export-postman` builds a ready-to-import Postman Collection v2.1 JSON file.
- **SLA &amp; Uptime Report Generator**: `php artisan api-watcher:report` compiles SLA Uptime percentages, P95/P99 latency calculations, and status code distributions into a structured report.

### 8. 🚨 Multichannel Proactive Alerting

[](#8--multichannel-proactive-alerting)

Alerts trigger when error rates or average latencies breach configured thresholds. Supports:

- **Mail Notifications** (Laravel Mail)
- **Slack Webhooks**
- **Generic HTTP Webhooks** (Teams, Discord, Custom Endpoints)

---

📸 Dashboard Preview
-------------------

[](#-dashboard-preview)

### Request Inspector

[](#request-inspector)

Deep dive into request details with payload formatting, headers, DB queries, and timeline execution. [![Request Details](./screenshots/request_details.png)](./screenshots/request_details.png)

### Egress &amp; Outgoing Requests

[](#egress--outgoing-requests)

Monitor third-party API call latencies, status codes, and error distributions. [![Analytics](./screenshots/analytics.png)](./screenshots/analytics.png)

---

🚀 Installation &amp; Setup
--------------------------

[](#-installation--setup)

### 1. Require Package

[](#1-require-package)

```
composer require taoshan98/laravel-api-watcher
```

### 2. Publish Assets &amp; Configuration

[](#2-publish-assets--configuration)

```
php artisan vendor:publish --tag=api-watcher-config
php artisan vendor:publish --tag=api-watcher-assets
```

### 3. Run Migrations

[](#3-run-migrations)

```
php artisan migrate
```

### 4. Register Middleware

[](#4-register-middleware)

In Laravel 11 (`bootstrap/app.php`):

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->api(prepend: [
        \Taoshan98\LaravelApiWatcher\Http\Middleware\CaptureApiRequest::class,
    ]);
})
```

In Laravel 10 (`app/Http/Kernel.php`):

```
protected $middlewareGroups = [
    'api' => [
        \Taoshan98\LaravelApiWatcher\Http\Middleware\CaptureApiRequest::class,
        // ...
    ],
];
```

### 5. Schedule Automated Maintenance &amp; Monitoring

[](#5-schedule-automated-maintenance--monitoring)

In `routes/console.php`:

```
use Illuminate\Support\Facades\Schedule;

// Monitor API health every 5 minutes
Schedule::command('api-watcher:monitor')->everyFiveMinutes();

// Flush Redis buffer every minute (if using Redis driver)
Schedule::command('api-watcher:flush')->everyMinute();

// Prune old logs daily
Schedule::command('api-watcher:prune --days=30')->daily();
```

---

🛠️ Artisan Command Reference
----------------------------

[](#️-artisan-command-reference)

CommandDescriptionOptions / Arguments`api-watcher:export`Export API logs to JSON or CSV`--format=json|csv`, `--path=/path/to/file``api-watcher:export-postman`Generate Postman Collection v2.1`--path=/path/to/collection.json``api-watcher:report`Generate SLA &amp; Uptime performance report`--days=30`, `--path=/path/to/report.json``api-watcher:flush`Flush Redis list buffer to Database`--limit=500``api-watcher:monitor`Check API health &amp; dispatch alert notificationsNone`api-watcher:prune`Prune logs older than retention period`--days=30``api-watcher:clear`Clear all recorded request logs`--force``api-watcher:fake`Generate synthetic mock API requests`count` (default: 10)`api-watcher:create-key`Create a new Public API access key`name`, `--scopes=read:stats,read:requests``api-watcher:list-keys`List all registered API keysNone`api-watcher:rename-key`Rename an existing API key`id`, `name``api-watcher:regenerate-key`Regenerate token for an API key`id``api-watcher:delete-key`Delete an API key`id`---

🔌 Public REST API
-----------------

[](#-public-rest-api)

Laravel API Watcher exposes a secure REST API protected by SHA-256 hashed keys and scope permissions.

### Enable API

[](#enable-api)

In `.env`:

```
API_WATCHER_API_ENABLED=true
```

### Authentication Header

[](#authentication-header)

Pass your API key token in the request header:

```
X-API-WATCHER-KEY: your-plain-text-token
```

### Available Endpoints &amp; Scopes

[](#available-endpoints--scopes)

MethodEndpointRequired ScopeDescription`GET``/api-watcher/api/v1/stats``read:stats`Aggregated request volume, error rate, P95/P99 latency`GET``/api-watcher/api/v1/requests``read:requests`Paginated request logs with filters (`status_code`, `method`, etc.)`GET``/api-watcher/api/v1/requests/{id}``read:requests`Single request details with DB query metrics`GET``/api-watcher/api/outgoing-requests``read:requests`List captured third-party egress HTTP requests`POST``/api-watcher/api/requests/diff``read:requests`Side-by-side JSON diff comparison of 2 requests`GET``/api-watcher/api/diagnostics``read:stats`Latency trend analysis &amp; suspicious IP abuse detection---

🔒 Production Security Best Practices
------------------------------------

[](#-production-security-best-practices)

1. **Dashboard Gate Authorization**: Restrict dashboard access in production (`AppServiceProvider.php`): ```
    use Illuminate\Support\Facades\Gate;

    public function boot(): void
    {
        Gate::define('viewApiWatcher', function ($user) {
            return in_array($user->email, ['admin@company.com']);
        });
    }
    ```
2. **Data Encryption at Rest**: Enable AES-256 payload encryption in `.env`: ```
    API_WATCHER_ENCRYPT_BODY=true
    ```

---

🧪 Automated Testing &amp; Code Quality Standards
------------------------------------------------

[](#-automated-testing--code-quality-standards)

```
# Run PHPStan Level 5 Static Analysis
./vendor/bin/phpstan analyse src --level=5

# Run Laravel Pint Code Formatter
./vendor/bin/pint --test

# Run Pest Feature & Unit Test Suite
./vendor/bin/pest
```

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request or open an Issue.

---

📄 License
---------

[](#-license)

Laravel API Watcher is open-sourced software licensed under the [MIT license](LICENSE.md).

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance95

Actively maintained with recent releases

Popularity15

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~79 days

Total

3

Last Release

21d ago

Major Versions

v1.0.0 → v2.0.12026-07-27

### Community

Maintainers

![](https://www.gravatar.com/avatar/ec8deb2b4139351fe8bc873ec640aada2a457949d3bbaf04d920ac703bd9c12e?d=identicon)[Taoshan98](/maintainers/Taoshan98)

---

Top Contributors

[![Taoshan98](https://avatars.githubusercontent.com/u/15851056?v=4)](https://github.com/Taoshan98 "Taoshan98 (9 commits)")

---

Tags

analyticsapilaravelrequestswatcherapilaraveldebuggingdashboardmonitorwatcherrequests

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/taoshan98-laravel-api-watcher/health.svg)

```
[![Health](https://phpackages.com/badges/taoshan98-laravel-api-watcher/health.svg)](https://phpackages.com/packages/taoshan98-laravel-api-watcher)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.4M354](/packages/psalm-plugin-laravel)[api-platform/laravel

API Platform support for Laravel

58190.1k21](/packages/api-platform-laravel)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5226.7k](/packages/simplestats-io-laravel-client)[mike-bronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k161.4k2](/packages/mike-bronner-laravel-model-caching)[forjedio/inertia-table

Backend-driven dynamic tables for Laravel + Inertia.js

272.0k](/packages/forjedio-inertia-table)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45844.8k1](/packages/pressbooks-pressbooks)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
