Mock Alpha

Platform Examples

Ready-to-paste Mock Alpha integrations for Flutter, Web, iOS, and curl

Platform Examples

Mock Alpha speaks plain HTTP, so any platform can integrate. These examples implement the patterns from Client Integration. For Android/OkHttp, see the full Android Interceptor reference.

Replace https://mock-alpha.your-domain.com with your instance URL and <your-api-key> with the project API key.

Flutter (Dio)

A capture-and-mock interceptor for the Dio client:

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

class MockAlphaInterceptor extends Interceptor {
  MockAlphaInterceptor({
    this.mockAlphaUrl = 'https://mock-alpha.your-domain.com',
    required this.apiKey,
    this.serviceName = 'flutter-app',
    this.enabled = kDebugMode,
  });

  final String mockAlphaUrl;
  final String apiKey;
  final String serviceName;
  final bool enabled;

  final _reporter = Dio();

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) async {
    if (!enabled) return handler.next(response);

    // 1. Report the real response (fire-and-forget)
    _report(response);

    // 2. Fetch the mock response and hand it to the app
    try {
      final mock = await _reporter.request(
        '$mockAlphaUrl/api/mock${response.requestOptions.path}',
        data: response.requestOptions.data,
        queryParameters: response.requestOptions.queryParameters,
        options: Options(
          method: response.requestOptions.method,
          headers: {'X-Api-Key': apiKey},
        ),
      );
      handler.resolve(mock);
    } catch (_) {
      // Mock Alpha unreachable — fall back to the real response
      handler.next(response);
    }
  }

  void _report(Response response) {
    _reporter
        .post('$mockAlphaUrl/api/collect',
            data: {
              'method': response.requestOptions.method,
              'path': response.requestOptions.uri.path,
              'statusCode': response.statusCode,
              'responseBody': response.data,
              'serviceName': serviceName,
            },
            options: Options(headers: {'X-Api-Key': apiKey}))
        .catchError((_) => Response(requestOptions: response.requestOptions));
  }
}

Register it in debug builds only:

final dio = Dio(BaseOptions(baseUrl: 'https://api.your-backend.com'));
if (kDebugMode) {
  dio.interceptors.add(MockAlphaInterceptor(apiKey: mockApiKey));
}

Web (axios)

For SPAs and Node.js clients. The simplest approach is a base URL swap in dev builds:

const api = axios.create({
  baseURL: import.meta.env.DEV
    ? 'https://mock-alpha.your-domain.com/api/mock'
    : 'https://api.your-backend.com',
  headers: import.meta.env.DEV ? { 'X-Api-Key': MOCK_API_KEY } : {},
})

Or a capture-and-mock interceptor:

import axios from 'axios'

const MOCK_ALPHA_URL = 'https://mock-alpha.your-domain.com'
const reporter = axios.create()

api.interceptors.response.use(async (response) => {
  if (!import.meta.env.DEV) return response

  // 1. Report the real response (fire-and-forget)
  reporter
    .post(
      `${MOCK_ALPHA_URL}/api/collect`,
      {
        method: response.config.method?.toUpperCase(),
        path: new URL(response.config.url!, response.config.baseURL).pathname,
        statusCode: response.status,
        responseBody: response.data,
        serviceName: 'web-app',
      },
      { headers: { 'X-Api-Key': MOCK_API_KEY } },
    )
    .catch(() => {})

  // 2. Return the mock response instead
  try {
    const mock = await reporter.request({
      url: `${MOCK_ALPHA_URL}/api/mock${new URL(response.config.url!, response.config.baseURL).pathname}`,
      method: response.config.method,
      data: response.config.data,
      params: response.config.params,
      headers: { 'X-Api-Key': MOCK_API_KEY },
    })
    return mock
  } catch {
    return response // fall back to real response
  }
})

CORS note: browser clients need the Mock Alpha instance to allow your dev origin. If you hit CORS errors during local development, proxy /api/mock through your dev server (Vite/webpack server.proxy) instead of calling Mock Alpha directly.

iOS (Swift / URLSession)

Base URL swap is the most idiomatic option on iOS:

enum APIConfig {
    #if DEBUG
    static let baseURL = URL(string: "https://mock-alpha.your-domain.com/api/mock")!
    static let extraHeaders = ["X-Api-Key": mockAPIKey]
    #else
    static let baseURL = URL(string: "https://api.your-backend.com")!
    static let extraHeaders: [String: String] = [:]
    #endif
}

To capture real traffic as well, report responses from wherever your networking layer completes a request:

func reportToMockAlpha(request: URLRequest, response: HTTPURLResponse, body: Data) {
    #if DEBUG
    guard let url = URL(string: "https://mock-alpha.your-domain.com/api/collect") else { return }
    var report = URLRequest(url: url)
    report.httpMethod = "POST"
    report.setValue(mockAPIKey, forHTTPHeaderField: "X-Api-Key")
    report.setValue("application/json", forHTTPHeaderField: "Content-Type")
    report.httpBody = try? JSONSerialization.data(withJSONObject: [
        "method": request.httpMethod ?? "GET",
        "path": request.url?.path ?? "",
        "statusCode": response.statusCode,
        "responseBody": (try? JSONSerialization.jsonObject(with: body)) ?? NSNull(),
        "serviceName": "ios-app",
    ])
    URLSession.shared.dataTask(with: report).resume() // fire-and-forget
    #endif
}

For a fully transparent interceptor (equivalent to OkHttp's), register a custom URLProtocol in debug builds — the report/mock flow inside it is identical to the above.

curl / scripts

No app required — seed and test endpoints from a terminal or CI job.

Seed an endpoint:

curl -X POST https://mock-alpha.your-domain.com/api/collect \
  -H "X-Api-Key: <your-api-key>" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "GET",
    "path": "/orders/42",
    "statusCode": 200,
    "responseBody": { "orderId": "42", "status": "shipped" },
    "serviceName": "seed-script"
  }'

Fetch the active scenario:

curl https://mock-alpha.your-domain.com/api/mock/orders/42 \
  -H "X-Api-Key: <your-api-key>"

Force a specific scenario:

curl https://mock-alpha.your-domain.com/api/mock/orders/42 \
  -H "X-Api-Key: <your-api-key>" \
  -H "X-Mock-Scenario: error-500"

Other platforms

Anything that can send HTTP works the same way — React Native, Kotlin Multiplatform (Ktor client), .NET (DelegatingHandler), Go, Python (requests hooks). Implement one of the three patterns in Client Integration:

  1. Base URL swap → point dev builds at {BASE}/api/mock + X-Api-Key header
  2. Capture-and-mock interceptor → report to /api/collect, serve from /api/mock
  3. Capture only → report traffic, curate scenarios, switch later

On this page