Skip to content

Admin API Reference

The Admin API provides runtime management of the mockd server.

mockd uses a three-port architecture separating the control plane from the data plane:

PortDefaultPurpose
Mock Server4280Data plane - serves your mock endpoints
Admin API4290Control plane - management and configuration
Engine Control4281Internal - Admin-to-Engine communication
4280/api/users
mockd start --port 4280 --admin-port 4290
# Admin at: http://localhost:4290/mocks

The Engine Control port (4281) is used internally for communication between the Admin API and the mock engine. In most cases, you don’t need to interact with it directly.

Base URL: http://localhost:4290 (or your configured --admin-port)

The admin API requires API key authentication by default. The API key is auto-generated on first start and stored at ~/.local/share/mockd/admin-api-key.

Terminal window
# Get your API key
cat ~/.local/share/mockd/admin-api-key
# Use with X-API-Key header
curl -H "X-API-Key: YOUR_KEY" http://localhost:4290/mocks
# Or use Bearer token
curl -H "Authorization: Bearer YOUR_KEY" http://localhost:4290/mocks
# Or use query parameter
curl "http://localhost:4290/mocks?api_key=YOUR_KEY"

For local development or CI, you can disable authentication:

Terminal window
mockd serve --no-auth

These endpoints work without authentication:

  • GET /health - Health check
  • GET /metrics - Prometheus metrics
  • Keep authentication enabled
  • Bind to localhost only (--host localhost)
  • Use a firewall to restrict access
  • Run admin port on internal network only

Check server health.

Response:

{
"status": "ok",
"uptime": 3600
}

Prometheus-compatible metrics endpoint. No authentication required.

Response: Prometheus text format

# HELP mockd_uptime_seconds Server uptime in seconds
# TYPE mockd_uptime_seconds gauge
mockd_uptime_seconds 3600
# HELP mockd_http_requests_total Total HTTP requests processed
# TYPE mockd_http_requests_total counter
mockd_http_requests_total{method="GET",path="/api/users",status="200"} 42
# HELP mockd_http_request_duration_seconds HTTP request latency
# TYPE mockd_http_request_duration_seconds histogram
mockd_http_request_duration_seconds_bucket{le="0.01"} 100
mockd_http_request_duration_seconds_bucket{le="0.1"} 150
mockd_http_request_duration_seconds_bucket{le="+Inf"} 155
# Go runtime metrics
go_goroutines 12
go_memstats_heap_alloc_bytes 4194304

Prometheus Configuration:

scrape_configs:
- job_name: 'mockd'
static_configs:
- targets: ['localhost:4290']
metrics_path: /metrics

List all ports in use by mockd, grouped by component.

Response:

{
"ports": [
{
"port": 4290,
"protocol": "HTTP",
"component": "Admin API",
"status": "running"
},
{
"port": 4280,
"protocol": "HTTP",
"component": "Mock Engine",
"status": "running"
},
{
"port": 1883,
"protocol": "MQTT",
"component": "MQTT Broker",
"status": "running"
},
{
"port": 50051,
"protocol": "gRPC",
"component": "gRPC Server",
"status": "running"
}
]
}

The response includes ports for:

  • Admin API (HTTP)
  • Mock Engine (HTTP/HTTPS)
  • Protocol handlers (gRPC, MQTT, WebSocket, SSE, GraphQL, SOAP)

Note: Ports with TLS enabled will include "tls": true in the response.


List all configured mocks.

Response:

{
"mocks": [
{
"id": "abc123",
"name": "Get users",
"matcher": {
"method": "GET",
"path": "/api/users"
},
"response": {
"statusCode": 200,
"body": "[]"
},
"enabled": true,
"priority": 0,
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:30:00Z"
}
],
"count": 1
}

Get a specific mock by ID.

Add a new mock at runtime.

Request:

{
"name": "Get users",
"matcher": {
"method": "GET",
"path": "/api/users"
},
"response": {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": "[{\"id\": 1, \"name\": \"Alice\"}]"
}
}

Response: Returns the created mock with generated ID (HTTP 201).

Port Sharing for gRPC and MQTT:

When creating a gRPC or MQTT mock on a port that’s already in use by another mock of the same protocol in the same workspace, the new services/topics are merged into the existing mock instead of creating a new one. This mirrors real-world behavior where a single gRPC server serves multiple services and a single MQTT broker handles multiple topics.

Merge Response (HTTP 200):

{
"action": "merged",
"message": "Merged into existing gRPC server on port 50051",
"targetMockId": "grpc_abc123",
"addedServices": ["myapp.HealthService/Check"],
"totalServices": ["myapp.UserService/GetUser", "myapp.HealthService/Check"],
"mock": { ... }
}

Conflict cases (HTTP 409):

  • Different protocols on the same port (e.g., gRPC on an MQTT port)
  • Service/method already exists (gRPC) or topic already exists (MQTT)
  • Different workspaces trying to use the same port

Update an existing mock.

Remove a mock.

Toggle a mock’s enabled state.


Get verification status for a mock (call count, timestamps).

Response:

{
"mockId": "abc123",
"callCount": 5,
"firstCalledAt": "2024-01-15T10:30:00Z",
"lastCalledAt": "2024-01-15T10:35:00Z"
}

Verify mock was called expected number of times.

Request:

{
"atLeast": 1,
"atMost": 10,
"exactly": null
}

Response:

{
"success": true,
"message": "Mock called 5 times, expected at least 1"
}

List all invocations of a mock.

Response:

{
"invocations": [
{
"timestamp": "2024-01-15T10:30:00Z",
"method": "GET",
"path": "/api/users",
"headers": {"User-Agent": "curl/7.68.0"},
"body": ""
}
],
"count": 5
}

Reset verification data for a specific mock.

Reset all verification data for all mocks.


Get stateful resource overview.

Response:

{
"resources": 2,
"totalItems": 15,
"resourceList": [
{"name": "users", "itemCount": 10},
{"name": "posts", "itemCount": 5}
]
}

Reset all stateful resources to seed data.

List all stateful resources.

Get all items in a specific resource.

Clear a specific resource (reset to seed data).


Get recent request history.

Query Parameters:

ParameterDescriptionDefault
limitMax requests to return100
offsetPagination offset0
pathFilter by path pattern
methodFilter by HTTP method
matchedFilter by matched mock ID

Response:

{
"requests": [
{
"id": "req-123",
"timestamp": "2024-01-15T10:30:00Z",
"method": "GET",
"path": "/api/users",
"matchedMockID": "abc123",
"responseStatus": 200,
"durationMs": 5
}
],
"total": 150
}

Get details of a specific request including headers, body, and response.

Clear request history.

Server-Sent Events (SSE) endpoint for streaming new requests in real-time.

Headers:

Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive

Events:

event: connected
data: {"message": "Connected to request stream"}
event: request
data: {"id": "req-123", "method": "GET", "path": "/api/users", ...}

Usage with curl:

Terminal window
curl -N http://localhost:4290/requests/stream

Usage with JavaScript:

const eventSource = new EventSource('http://localhost:4290/requests/stream');
eventSource.addEventListener('connected', (e) => {
console.log('Connected to request stream');
});
eventSource.addEventListener('request', (e) => {
const request = JSON.parse(e.data);
console.log('New request:', request.method, request.path);
});

This endpoint is useful for:

  • Real-time request monitoring dashboards
  • Live debugging during development
  • Integration with external logging systems

Get current proxy status.

Response:

{
"running": true,
"port": 8888,
"mode": "record",
"sessionId": "session-123"
}

Start the MITM proxy.

Request:

{
"port": 8888,
"mode": "record",
"sessionName": "my-session"
}

Stop the proxy.

Change proxy mode.

Request:

{
"mode": "passthrough"
}

Modes: record, passthrough, playback

Get current recording filters.

Update recording filters.


Check if CA certificate exists.

Response:

{
"exists": true,
"path": "/path/to/ca.crt",
"fingerprint": "AB:CD:EF:...",
"expiresAt": "2034-01-15T00:00:00Z",
"organization": "mockd Local CA"
}

Generate a new CA certificate.

Request:

{
"caPath": "/path/to/store/ca"
}

Download the CA certificate (PEM format).


List all recording sessions.

Create a new recording session.

Get session details.

Delete a session.


List all HTTP recordings.

Query Parameters:

ParameterDescription
sessionIdFilter by session
methodFilter by HTTP method
pathFilter by path pattern

Get a specific recording.

Delete a recording.

Clear all recordings.

Convert recordings to mocks.

Request:

{
"sessionId": "session-123",
"deduplicate": true,
"includeHeaders": false
}

Response:

{
"mockIds": ["mock-1", "mock-2"],
"count": 2
}

Export recordings to JSON or YAML.

Request:

{
"format": "json",
"sessionId": "session-123"
}
FieldTypeDescription
formatstringOutput format: "json" (default) or "yaml"
sessionIdstringOptional: filter by session
recordingIdsstring[]Optional: export specific recordings

YAML Export Example:

{
"format": "yaml",
"sessionId": "session-123"
}

Returns Content-Type: application/x-yaml for YAML format.


Export current mock configuration.

Import mock configuration.

Request:

{
"config": {
"version": "1.0",
"mocks": [...]
},
"replace": false
}

Export mocks as Insomnia v5 collection (YAML format, recommended).

Response: Content-Type: application/x-yaml

type: collection.insomnia.rest/5.0
name: mockd Mocks
meta:
id: mockd_export
created: 1705315800000
modified: 1705315800000
resources:
- _id: wrk_mockd
_type: workspace
name: mockd Mocks
- _id: req_get_users
_type: request
parentId: wrk_mockd
name: Get Users
method: GET
url: http://localhost:4280/api/users
headers: []
parameters: []

Usage:

Terminal window
# Download and import into Insomnia
curl -o mockd-collection.yaml http://localhost:4290/insomnia.yaml
# Then: File > Import > From File in Insomnia

Export mocks as Insomnia v4 collection (JSON format, legacy).

Response: Content-Type: application/json

{
"_type": "export",
"__export_format": 4,
"__export_source": "mockd",
"resources": [
{
"_id": "wrk_mockd",
"_type": "workspace",
"name": "mockd Mocks"
},
{
"_id": "req_get_users",
"_type": "request",
"parentId": "wrk_mockd",
"name": "Get Users",
"method": "GET",
"url": "http://localhost:4280/api/users"
}
]
}

Query Parameters:

ParameterDescription
format=yaml or format=v5Force v5 YAML format on /insomnia.json

Features:

  • Exports all HTTP mocks as Insomnia requests
  • Includes request headers and query parameters
  • Creates appropriate Content-Type headers for JSON/XML bodies
  • Organizes mocks in a workspace structure
  • Supports SSE mocks (adds Accept: text/event-stream header)
  • Supports SOAP mocks (adds SOAPAction headers)

List active SSE connections.

Get SSE connection details.

Close an SSE connection.

Get SSE statistics.


List active WebSocket connections.

Get connection details.

Close a WebSocket connection.

Send a message to a specific connection.

Request:

{
"type": "text",
"data": "Hello from server"
}

Broadcast message to all connections.

List configured WebSocket endpoints.

Get WebSocket statistics.


List stream recordings.

Get stream recording details.

Delete a stream recording.

Export stream recording.

Convert stream recording to mock.

Start replaying a stream recording.

List active replay sessions.

Get replay session status.

Stop a replay session.


List all registered gRPC servers.

Response:

{
"servers": [
{
"id": "grpc-server-1",
"address": ":50051",
"running": true
}
],
"count": 1
}

Get gRPC server status.


List all registered MQTT brokers.

Response:

{
"brokers": [
{
"id": "mqtt-broker-1",
"port": 1883,
"running": true,
"recordingEnabled": false
}
],
"count": 1
}

Get MQTT broker status.

Start recording MQTT messages.

Stop recording MQTT messages.

List MQTT recordings.

Query Parameters:

ParameterDescription
topicPatternFilter by topic (supports MQTT wildcards + and #)
clientIdFilter by client ID
directionFilter by direction (publish/subscribe)
limitMax recordings to return
offsetPagination offset

Get a specific MQTT recording.

Delete an MQTT recording.

Clear all MQTT recordings.

Get MQTT recording statistics.

Convert MQTT recordings to mock config.

Request:

{
"recordingIds": ["mqtt-abc123"],
"topicPattern": "sensors/#",
"deduplicate": true,
"includeQoS": true,
"includeRetain": true
}

Convert a single MQTT recording to mock config.

Export all MQTT recordings as JSON.


List all registered SOAP handlers.

Response:

{
"handlers": [
{
"id": "soap-handler-1",
"path": "/soap/service",
"recordingEnabled": false
}
],
"count": 1
}

Get SOAP handler status.

Start recording SOAP requests.

Stop recording SOAP requests.

List SOAP recordings.

Query Parameters:

ParameterDescription
endpointFilter by endpoint path
operationFilter by operation name
soapActionFilter by SOAPAction header
hasFaultFilter by fault presence (true/false)
limitMax recordings to return
offsetPagination offset

Get a specific SOAP recording.

Delete a SOAP recording.

Clear all SOAP recordings.

Get SOAP recording statistics.

Convert SOAP recordings to mock config.

Request:

{
"recordingIds": ["soap-abc123"],
"endpoint": "/soap/service",
"operation": "GetUser",
"deduplicate": true,
"includeDelay": false,
"preserveFaults": true
}

Convert a single SOAP recording to mock config.

Export all SOAP recordings as JSON.


Get current chaos configuration.

Response:

{
"enabled": true,
"latency": {
"min": "100ms",
"max": "500ms",
"probability": 1.0
},
"errorRate": {
"probability": 0.1,
"statusCodes": [500, 502, 503],
"defaultCode": 500
}
}

Update chaos configuration.

Request:

{
"enabled": true,
"latency": {
"min": "50ms",
"max": "200ms",
"probability": 1.0
},
"errorRate": {
"probability": 0.1,
"statusCodes": [500, 503],
"defaultCode": 503
}
}

Latency Config Fields:

FieldTypeDescription
minstringMinimum latency (Go duration, e.g., “50ms”, “1s”)
maxstringMaximum latency (Go duration, e.g., “200ms”, “2s”)
probabilityfloatProbability of applying latency (0.0 to 1.0)

Error Rate Config Fields:

FieldTypeDescription
probabilityfloatProbability of returning an error (0.0 to 1.0)
statusCodesint[]List of HTTP status codes to randomly choose from
defaultCodeintDefault status code if statusCodes is empty (e.g., 500)

All errors return a consistent format:

{
"error": "error_code",
"message": "Human readable message"
}
CodeHTTP StatusDescription
not_found404Resource not found
invalid_json400Invalid JSON in request
validation_error400Validation failed
missing_field400Required field missing

Terminal window
curl -X POST http://localhost:4290/state/reset
Terminal window
curl -X POST http://localhost:4290/mocks \
-H "Content-Type: application/json" \
-d '{
"name": "Test endpoint",
"matcher": {"method": "GET", "path": "/api/test"},
"response": {"statusCode": 200, "body": "{\"test\": true}"}
}'
Terminal window
curl "http://localhost:4290/requests?limit=10&path=/api/users"
Terminal window
curl -X POST http://localhost:4290/proxy/start \
-H "Content-Type: application/json" \
-d '{"port": 8888, "mode": "record", "sessionName": "test-session"}'
Terminal window
curl -X POST http://localhost:4290/recordings/convert \
-H "Content-Type: application/json" \
-d '{"deduplicate": true}'