flutter_api_observability
A production-grade Flutter API Observability Toolkit providing real-time diagnostics, request history, endpoint performance statistics, error normalization, smart retries, sensitive data redaction, and health reporting for Flutter and Dart applications.
flutter_api_observability turns network operations into a completely observable data layer over Dio (with extensible architecture for http), protecting your app from silent network failures, credential leaks in logs, transient connectivity drops, and slow backend endpoints.
Key Features
- API Request History: Live in-memory audit log (
api.history) recording typedApiRequestRecorditems with start/end timestamps, unique Request IDs (API-0001), duration, status codes, retry counts, and redacted payloads. - Endpoint Performance Statistics: Per-endpoint metrics (
ApiEndpointStats) computing total calls, success rate %, average duration, median duration, slow request counts, and automatic detection of consistently slow endpoints. - Unified Error Normalization: Maps raw network/Dio failures into typed categories (
unauthorized,forbidden,validation,notFound,server,timeout,noInternet,badResponse,unknown). - Recursive Sensitive Data Redaction: Automatically redacts passwords, JWT tokens, API keys, cookies, and authorization headers before logging or storing in history. Case-insensitive matching across Maps, Lists, JSON strings, headers, query params, request bodies, and response bodies.
- Smart Retry System: Retries transient network drops and server errors (5xx) with linear backoff while safely skipping client errors (401, 403, 404, 422) and protecting non-idempotent HTTP POST operations by default.
- Large Payload Protection: Memory protection via
maxHistoryBodyLengthand payload truncation flags to prevent large responses (e.g. 10MB JSON) from overflowing memory. - Structured Box Logging: Beautiful visual log boxes for requests, responses, errors, and retries with custom logger abstraction.
- Diagnostics Export: Export full diagnostic snapshots (health report, endpoint stats, recent request history, error summaries) via
api.exportDiagnostics().
Installation
Add flutter_api_observability to your pubspec.yaml:
dependencies:
flutter_api_observability: ^1.1.0
Or run:
flutter pub add flutter_api_observability
Quick Start
import 'package:flutter_api_observability/flutter_api_observability.dart';
void main() async {
// Initialize ApiGuard
final api = ApiGuard(
baseUrl: 'https://api.example.com',
config: const ApiGuardConfig(
enableLogging: true,
maxRetries: 2,
maxHistoryEntries: 100,
slowRequestThreshold: Duration(seconds: 2),
),
);
try {
// Perform monitored GET request
final response = await api.get<Map<String, dynamic>>('/products');
print('Products retrieved: ${response.data}');
} on ApiGuardException catch (e) {
print('API Failure: ${e.message} [Category: ${e.type}]');
}
// Access live Observability statistics
print('Total Requests: ${api.healthReport.totalRequests}');
print('Success Rate: ${api.healthReport.successRate.toStringAsFixed(1)}%');
print('History Length: ${api.history.length}');
}
Request History & Diagnostics
ApiGuard stores typed records of request cycles up to maxHistoryEntries with FIFO eviction:
// Access all recorded history
final List<ApiRequestRecord> records = api.history;
for (final record in records) {
print('${record.id} | ${record.method} ${record.path} | ${record.statusCode} | ${record.duration.inMilliseconds}ms');
print('Retries: ${record.retryCount} | Slow: ${record.isSlow}');
}
// Built-in History Filters
final failedCalls = api.failedRequests;
final slowCalls = api.slowRequests;
Endpoint Performance Statistics
Track per-endpoint health and detect consistently slow backend APIs:
final Map<String, ApiEndpointStats> stats = api.healthReport.endpointStats;
stats.forEach((path, ep) {
print('Endpoint: $path');
print(' Calls : ${ep.totalRequests}');
print(' Success Rate: ${ep.successRate.toStringAsFixed(1)}%');
print(' Avg Duration: ${ep.averageDuration.inMilliseconds}ms');
print(' Median Time : ${ep.medianDuration.inMilliseconds}ms');
print(' Slow Endpoint: ${ep.isConsistentlySlow}');
});
// Access endpoints that are consistently slow
final slowEndpoints = api.healthReport.slowEndpoints;
Exporting Diagnostics
Export a complete JSON-safe diagnostic snapshot for analytics or support reports:
final Map<String, dynamic> diagnosticsJson = api.exportDiagnostics();
print(jsonEncode(diagnosticsJson));
Configuration Options
final api = ApiGuard(
baseUrl: 'https://api.example.com',
config: ApiGuardConfig(
enableLogging: true,
maxRetries: 3,
retryDelay: const Duration(milliseconds: 500),
slowRequestThreshold: const Duration(milliseconds: 1500),
maxHistoryEntries: 200,
maxHistoryBodyLength: 4096,
sensitiveKeys: {
'token',
'password',
'authorization',
'refresh_token',
'secret',
'api_key',
},
logger: const ConsoleApiGuardLogger(),
),
);
Interactive Example App
Explore the full Flutter API Observability Dashboard app inside example/:
- Observability Dashboard: High-level KPIs, Median response times, Endpoint stats.
- Request History View: Tap any request record to inspect redacted headers, payloads, and error details.
- Network Simulator: Trigger simulated 200 OK, 401 Unauthorized, 500 Server Error retries, and Redaction demos.
Verification & Quality
flutter analyze # 0 issues found!
flutter test # 38 unit & integration tests passing!
dart pub publish --dry-run # 0 warnings!
License
MIT License - see the LICENSE file for details.
Libraries
- flutter_api_observability
- A comprehensive API Observability Toolkit, safety, diagnostics, error normalization, retry mechanism, sensitive data redaction, and health reporting library for Flutter and Dart.