mock_api_assets: JSON Mock Backend for Flutter

Zusammenfassung

Pixel shares mock_api_assets, a fake backend for Dart and Flutter that serves JSON fixtures through real HTTP clients. Features include route matching, templating, simulated latency, error injection, switchable scenarios, pagination, and stateful CRUD—helping developers test loading, failure, and create-then-list flows before a live API is ready.

DEV Community

mock_api_assets: a fake backend from JSON fixtures for Dart and Flutter

Front-end work often starts before the backend is ready. The API is still being designed, or it exists but you are on a train, or you have to demo the app and cannot depend on a server. The usual answer is a few hard-coded lists scattered through the code, which then have to be found and removed later. A fake backend is a cleaner answer: the app keeps making real HTTP calls through its real client, and something answers them from local JSON files. But a good fake has to do more than return a file. Real APIs are slow, they fail, and they remember what you posted. If the fake does none of that, the loading states, the error screens and the "create then list" flows are never exercised. mock_api_assets is a fake backend made of JSON fixtures. It has route matching, templated fixtures, simulated latency, error injection, a stateful CRUD store, switchable scenarios, and adapters for Dio and package:http. What it does A router. MockRouter matches on the method and a path pattern. :id captures one segment, * matches one segment, and ** (last segment only) matches the rest of the path. Query-string constraints are optional. The first match wins, and priority: moves a route ahead of routes registered earlier. A trailing slash is ignored, and a basePath such as /api/v1 can be stripped before matching. Handlers. MockHandler.fixture(path) serves a fixture file. MockHandler.json(value) serves an inline JSON value. MockHandler.callback(...) gets the path params, query, headers and parsed body, and returns a response. MockHandler.paginated(...) and MockHandler.paginatedList(...) slice a list by page and limit. Templating. Placeholders in fixtures and inline JSON are filled from the request: {{params.id}}, {{query.q}}, {{headers.x-token}}, {{body.items.0.sku}}, {{method}}, {{path}} and {{now}}. A string that is exactly one placeholder keeps the value's type, and the filters | int, | num and | bool convert it. Pluggable fixture loaders. MapFixtureLoader keeps fixtures in memory. CallbackFixtureLoader calls a function you give it, for example Flutter's rootBundle.loadString. FileFixtureLoader reads from disk and lives in package:mock_api_assets/io.dart. Latency. MockLatency.fixed, .uniform or .normal. Random values come from an injectable Random, and the delay function is injectable too, so tests can run on a fake clock. Error injection. A global failure rate, errors for specific routes with an optional hit count, and "fail the next N calls". Faults are HTTP statuses or network faults: timeout, connection refused, connection reset and host lookup. Stateful CRUD. router.resource('/todos', seed: [...]) registers list, create, read, replace, update and delete routes over an in-memory collection. POST, then GET, returns what was posted. router.store.reset() restores the seed. Scenarios. Named sets of overrides you switch at runtime: route overrides, a latency, a fault for every request, or a failure rate. Think "empty-state", "server-down" and "slow-3g". Several can be active at once. Request log. Assert on router.calls, router.callsTo('POST', '/todos') and router.wasCalled(...). Helpful 404s. An unmatched request gets a 404 JSON body that lists the nearest registered routes. Adapters. MockDioAdapter from package:mock_api_assets/dio.dart and MockHttpClient from package:mock_api_assets/http.dart. The core library imports neither. How to use it Add it from GitHub: dependencies:
mock_api_assets:
git: https://github.com/AbdeldjalilChougui/mock_api_assets
With Dio: import 'package:dio/dio.dart';
import 'package:mock_api_assets/dio.dart';
import 'package:mock_api_assets/mock_api_assets.dart';

Future main() async {
final router = MockRouter(
loader: MapFixtureLoader({
'users/detail.json': {'id': '{{params.id | int}}', 'name': 'User'},
}),
latency: const MockLatency.uniform(
Duration(milliseconds: 200),
Duration(milliseconds: 800),
),
)
..get('/users/:id', MockHandler.fixture('users/detail.json'))
...
mock_api_assets: JSON Mock Backend for Flutter
Powered by Readybot.io

Das Neueste von Pixel

Incident Response: Look Beyond the Red Alert

Pixel’s DEV Community announcement explores how teams can fixate on one failing service while overlooking the real cause of an outage, such as a full …

Sach: AI Fact-Checks WhatsApp Forwards in India

Pixel’s announcement introduces Sach, a tool that checks forwarded messages in English, Hindi, Telugu, and 14 other Indian languages against official sources. It gives cited …

Java 25 Removes SecurityManager: What to Fix

Pixel’s announcement explains how Java 24’s JEP 486 permanently disabled the SecurityManager, breaking test workarounds that intercept System.exit. It recommends returning exit codes or throwing …