Admin API Reference
The Admin API provides runtime management of the mockd server.
Overview
Section titled “Overview”mockd uses a three-port architecture separating the control plane from the data plane:
| Port | Default | Purpose |
|---|---|---|
| Mock Server | 4280 | Data plane - serves your mock endpoints |
| Admin API | 4290 | Control plane - management and configuration |
| Engine Control | 4281 | Internal - Admin-to-Engine communication |
mockd start --port 4280 --admin-port 4290# Admin at: http://localhost:4290/mocksThe 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)
Authentication
Section titled “Authentication”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.
Using the API Key
Section titled “Using the API Key”# Get your API keycat ~/.local/share/mockd/admin-api-key
# Use with X-API-Key headercurl -H "X-API-Key: YOUR_KEY" http://localhost:4290/mocks
# Or use Bearer tokencurl -H "Authorization: Bearer YOUR_KEY" http://localhost:4290/mocks
# Or use query parametercurl "http://localhost:4290/mocks?api_key=YOUR_KEY"Disabling Authentication
Section titled “Disabling Authentication”For local development or CI, you can disable authentication:
mockd serve --no-authUnauthenticated Endpoints
Section titled “Unauthenticated Endpoints”These endpoints work without authentication:
GET /health- Health checkGET /metrics- Prometheus metrics
Production Recommendations
Section titled “Production Recommendations”- Keep authentication enabled
- Bind to localhost only (
--host localhost) - Use a firewall to restrict access
- Run admin port on internal network only
Endpoints
Section titled “Endpoints”Health
Section titled “Health”GET /health
Section titled “GET /health”Check server health.
Response:
{ "status": "ok", "uptime": 3600}Metrics
Section titled “Metrics”GET /metrics
Section titled “GET /metrics”Prometheus-compatible metrics endpoint. No authentication required.
Response: Prometheus text format
# HELP mockd_uptime_seconds Server uptime in seconds# TYPE mockd_uptime_seconds gaugemockd_uptime_seconds 3600
# HELP mockd_http_requests_total Total HTTP requests processed# TYPE mockd_http_requests_total countermockd_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 histogrammockd_http_request_duration_seconds_bucket{le="0.01"} 100mockd_http_request_duration_seconds_bucket{le="0.1"} 150mockd_http_request_duration_seconds_bucket{le="+Inf"} 155
# Go runtime metricsgo_goroutines 12go_memstats_heap_alloc_bytes 4194304Prometheus Configuration:
scrape_configs: - job_name: 'mockd' static_configs: - targets: ['localhost:4290'] metrics_path: /metricsGET /ports
Section titled “GET /ports”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.
Mock Management
Section titled “Mock Management”GET /mocks
Section titled “GET /mocks”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 /mocks/{id}
Section titled “GET /mocks/{id}”Get a specific mock by ID.
POST /mocks
Section titled “POST /mocks”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
PUT /mocks/{id}
Section titled “PUT /mocks/{id}”Update an existing mock.
DELETE /mocks/{id}
Section titled “DELETE /mocks/{id}”Remove a mock.
POST /mocks/{id}/toggle
Section titled “POST /mocks/{id}/toggle”Toggle a mock’s enabled state.
Mock Verification
Section titled “Mock Verification”GET /mocks/{id}/verify
Section titled “GET /mocks/{id}/verify”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"}POST /mocks/{id}/verify
Section titled “POST /mocks/{id}/verify”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"}GET /mocks/{id}/invocations
Section titled “GET /mocks/{id}/invocations”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}DELETE /mocks/{id}/invocations
Section titled “DELETE /mocks/{id}/invocations”Reset verification data for a specific mock.
DELETE /verify
Section titled “DELETE /verify”Reset all verification data for all mocks.
State Management (Stateful Resources)
Section titled “State Management (Stateful Resources)”GET /state
Section titled “GET /state”Get stateful resource overview.
Response:
{ "resources": 2, "totalItems": 15, "resourceList": [ {"name": "users", "itemCount": 10}, {"name": "posts", "itemCount": 5} ]}POST /state/reset
Section titled “POST /state/reset”Reset all stateful resources to seed data.
GET /state/resources
Section titled “GET /state/resources”List all stateful resources.
GET /state/resources/{name}
Section titled “GET /state/resources/{name}”Get all items in a specific resource.
DELETE /state/resources/{name}
Section titled “DELETE /state/resources/{name}”Clear a specific resource (reset to seed data).
Request History
Section titled “Request History”GET /requests
Section titled “GET /requests”Get recent request history.
Query Parameters:
| Parameter | Description | Default |
|---|---|---|
limit | Max requests to return | 100 |
offset | Pagination offset | 0 |
path | Filter by path pattern | |
method | Filter by HTTP method | |
matched | Filter 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 /requests/{id}
Section titled “GET /requests/{id}”Get details of a specific request including headers, body, and response.
DELETE /requests
Section titled “DELETE /requests”Clear request history.
GET /requests/stream
Section titled “GET /requests/stream”Server-Sent Events (SSE) endpoint for streaming new requests in real-time.
Headers:
Content-Type: text/event-streamCache-Control: no-cacheConnection: keep-aliveEvents:
event: connecteddata: {"message": "Connected to request stream"}
event: requestdata: {"id": "req-123", "method": "GET", "path": "/api/users", ...}Usage with curl:
curl -N http://localhost:4290/requests/streamUsage 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
Proxy Management
Section titled “Proxy Management”GET /proxy/status
Section titled “GET /proxy/status”Get current proxy status.
Response:
{ "running": true, "port": 8888, "mode": "record", "sessionId": "session-123"}POST /proxy/start
Section titled “POST /proxy/start”Start the MITM proxy.
Request:
{ "port": 8888, "mode": "record", "sessionName": "my-session"}POST /proxy/stop
Section titled “POST /proxy/stop”Stop the proxy.
PUT /proxy/mode
Section titled “PUT /proxy/mode”Change proxy mode.
Request:
{ "mode": "passthrough"}Modes: record, passthrough, playback
GET /proxy/filters
Section titled “GET /proxy/filters”Get current recording filters.
PUT /proxy/filters
Section titled “PUT /proxy/filters”Update recording filters.
CA Certificate (HTTPS Interception)
Section titled “CA Certificate (HTTPS Interception)”GET /proxy/ca
Section titled “GET /proxy/ca”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"}POST /proxy/ca
Section titled “POST /proxy/ca”Generate a new CA certificate.
Request:
{ "caPath": "/path/to/store/ca"}GET /proxy/ca/download
Section titled “GET /proxy/ca/download”Download the CA certificate (PEM format).
Recording Sessions
Section titled “Recording Sessions”GET /sessions
Section titled “GET /sessions”List all recording sessions.
POST /sessions
Section titled “POST /sessions”Create a new recording session.
GET /sessions/{id}
Section titled “GET /sessions/{id}”Get session details.
DELETE /sessions/{id}
Section titled “DELETE /sessions/{id}”Delete a session.
Recordings
Section titled “Recordings”GET /recordings
Section titled “GET /recordings”List all HTTP recordings.
Query Parameters:
| Parameter | Description |
|---|---|
sessionId | Filter by session |
method | Filter by HTTP method |
path | Filter by path pattern |
GET /recordings/{id}
Section titled “GET /recordings/{id}”Get a specific recording.
DELETE /recordings/{id}
Section titled “DELETE /recordings/{id}”Delete a recording.
DELETE /recordings
Section titled “DELETE /recordings”Clear all recordings.
POST /recordings/convert
Section titled “POST /recordings/convert”Convert recordings to mocks.
Request:
{ "sessionId": "session-123", "deduplicate": true, "includeHeaders": false}Response:
{ "mockIds": ["mock-1", "mock-2"], "count": 2}POST /recordings/export
Section titled “POST /recordings/export”Export recordings to JSON or YAML.
Request:
{ "format": "json", "sessionId": "session-123"}| Field | Type | Description |
|---|---|---|
format | string | Output format: "json" (default) or "yaml" |
sessionId | string | Optional: filter by session |
recordingIds | string[] | Optional: export specific recordings |
YAML Export Example:
{ "format": "yaml", "sessionId": "session-123"}Returns Content-Type: application/x-yaml for YAML format.
Configuration
Section titled “Configuration”GET /config
Section titled “GET /config”Export current mock configuration.
POST /config
Section titled “POST /config”Import mock configuration.
Request:
{ "config": { "version": "1.0", "mocks": [...] }, "replace": false}Export Formats
Section titled “Export Formats”GET /insomnia.yaml
Section titled “GET /insomnia.yaml”Export mocks as Insomnia v5 collection (YAML format, recommended).
Response: Content-Type: application/x-yaml
type: collection.insomnia.rest/5.0name: mockd Mocksmeta: id: mockd_export created: 1705315800000 modified: 1705315800000resources: - _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:
# Download and import into Insomniacurl -o mockd-collection.yaml http://localhost:4290/insomnia.yaml# Then: File > Import > From File in InsomniaGET /insomnia.json
Section titled “GET /insomnia.json”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:
| Parameter | Description |
|---|---|
format=yaml or format=v5 | Force 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-streamheader) - Supports SOAP mocks (adds SOAPAction headers)
SSE Management
Section titled “SSE Management”GET /sse/connections
Section titled “GET /sse/connections”List active SSE connections.
GET /sse/connections/{id}
Section titled “GET /sse/connections/{id}”Get SSE connection details.
DELETE /sse/connections/{id}
Section titled “DELETE /sse/connections/{id}”Close an SSE connection.
GET /sse/stats
Section titled “GET /sse/stats”Get SSE statistics.
WebSocket Management
Section titled “WebSocket Management”GET /admin/ws/connections
Section titled “GET /admin/ws/connections”List active WebSocket connections.
GET /admin/ws/connections/{id}
Section titled “GET /admin/ws/connections/{id}”Get connection details.
DELETE /admin/ws/connections/{id}
Section titled “DELETE /admin/ws/connections/{id}”Close a WebSocket connection.
POST /admin/ws/connections/{id}/send
Section titled “POST /admin/ws/connections/{id}/send”Send a message to a specific connection.
Request:
{ "type": "text", "data": "Hello from server"}POST /admin/ws/broadcast
Section titled “POST /admin/ws/broadcast”Broadcast message to all connections.
GET /admin/ws/endpoints
Section titled “GET /admin/ws/endpoints”List configured WebSocket endpoints.
GET /admin/ws/stats
Section titled “GET /admin/ws/stats”Get WebSocket statistics.
Stream Recordings (WebSocket/SSE)
Section titled “Stream Recordings (WebSocket/SSE)”GET /stream-recordings
Section titled “GET /stream-recordings”List stream recordings.
GET /stream-recordings/{id}
Section titled “GET /stream-recordings/{id}”Get stream recording details.
DELETE /stream-recordings/{id}
Section titled “DELETE /stream-recordings/{id}”Delete a stream recording.
POST /stream-recordings/{id}/export
Section titled “POST /stream-recordings/{id}/export”Export stream recording.
POST /stream-recordings/{id}/convert
Section titled “POST /stream-recordings/{id}/convert”Convert stream recording to mock.
POST /stream-recordings/{id}/replay
Section titled “POST /stream-recordings/{id}/replay”Start replaying a stream recording.
GET /replay
Section titled “GET /replay”List active replay sessions.
GET /replay/{id}
Section titled “GET /replay/{id}”Get replay session status.
DELETE /replay/{id}
Section titled “DELETE /replay/{id}”Stop a replay session.
gRPC Management
Section titled “gRPC Management”GET /grpc
Section titled “GET /grpc”List all registered gRPC servers.
Response:
{ "servers": [ { "id": "grpc-server-1", "address": ":50051", "running": true } ], "count": 1}GET /grpc/{id}/status
Section titled “GET /grpc/{id}/status”Get gRPC server status.
MQTT Recording
Section titled “MQTT Recording”GET /mqtt
Section titled “GET /mqtt”List all registered MQTT brokers.
Response:
{ "brokers": [ { "id": "mqtt-broker-1", "port": 1883, "running": true, "recordingEnabled": false } ], "count": 1}GET /mqtt/{id}/status
Section titled “GET /mqtt/{id}/status”Get MQTT broker status.
POST /mqtt/{id}/record/start
Section titled “POST /mqtt/{id}/record/start”Start recording MQTT messages.
POST /mqtt/{id}/record/stop
Section titled “POST /mqtt/{id}/record/stop”Stop recording MQTT messages.
GET /mqtt-recordings
Section titled “GET /mqtt-recordings”List MQTT recordings.
Query Parameters:
| Parameter | Description |
|---|---|
topicPattern | Filter by topic (supports MQTT wildcards + and #) |
clientId | Filter by client ID |
direction | Filter by direction (publish/subscribe) |
limit | Max recordings to return |
offset | Pagination offset |
GET /mqtt-recordings/{id}
Section titled “GET /mqtt-recordings/{id}”Get a specific MQTT recording.
DELETE /mqtt-recordings/{id}
Section titled “DELETE /mqtt-recordings/{id}”Delete an MQTT recording.
DELETE /mqtt-recordings
Section titled “DELETE /mqtt-recordings”Clear all MQTT recordings.
GET /mqtt-recordings/stats
Section titled “GET /mqtt-recordings/stats”Get MQTT recording statistics.
POST /mqtt-recordings/convert
Section titled “POST /mqtt-recordings/convert”Convert MQTT recordings to mock config.
Request:
{ "recordingIds": ["mqtt-abc123"], "topicPattern": "sensors/#", "deduplicate": true, "includeQoS": true, "includeRetain": true}POST /mqtt-recordings/{id}/convert
Section titled “POST /mqtt-recordings/{id}/convert”Convert a single MQTT recording to mock config.
POST /mqtt-recordings/export
Section titled “POST /mqtt-recordings/export”Export all MQTT recordings as JSON.
SOAP Recording
Section titled “SOAP Recording”GET /soap
Section titled “GET /soap”List all registered SOAP handlers.
Response:
{ "handlers": [ { "id": "soap-handler-1", "path": "/soap/service", "recordingEnabled": false } ], "count": 1}GET /soap/{id}/status
Section titled “GET /soap/{id}/status”Get SOAP handler status.
POST /soap/{id}/record/start
Section titled “POST /soap/{id}/record/start”Start recording SOAP requests.
POST /soap/{id}/record/stop
Section titled “POST /soap/{id}/record/stop”Stop recording SOAP requests.
GET /soap-recordings
Section titled “GET /soap-recordings”List SOAP recordings.
Query Parameters:
| Parameter | Description |
|---|---|
endpoint | Filter by endpoint path |
operation | Filter by operation name |
soapAction | Filter by SOAPAction header |
hasFault | Filter by fault presence (true/false) |
limit | Max recordings to return |
offset | Pagination offset |
GET /soap-recordings/{id}
Section titled “GET /soap-recordings/{id}”Get a specific SOAP recording.
DELETE /soap-recordings/{id}
Section titled “DELETE /soap-recordings/{id}”Delete a SOAP recording.
DELETE /soap-recordings
Section titled “DELETE /soap-recordings”Clear all SOAP recordings.
GET /soap-recordings/stats
Section titled “GET /soap-recordings/stats”Get SOAP recording statistics.
POST /soap-recordings/convert
Section titled “POST /soap-recordings/convert”Convert SOAP recordings to mock config.
Request:
{ "recordingIds": ["soap-abc123"], "endpoint": "/soap/service", "operation": "GetUser", "deduplicate": true, "includeDelay": false, "preserveFaults": true}POST /soap-recordings/{id}/convert
Section titled “POST /soap-recordings/{id}/convert”Convert a single SOAP recording to mock config.
POST /soap-recordings/export
Section titled “POST /soap-recordings/export”Export all SOAP recordings as JSON.
Chaos Injection
Section titled “Chaos Injection”GET /chaos
Section titled “GET /chaos”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 }}PUT /chaos
Section titled “PUT /chaos”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:
| Field | Type | Description |
|---|---|---|
min | string | Minimum latency (Go duration, e.g., “50ms”, “1s”) |
max | string | Maximum latency (Go duration, e.g., “200ms”, “2s”) |
probability | float | Probability of applying latency (0.0 to 1.0) |
Error Rate Config Fields:
| Field | Type | Description |
|---|---|---|
probability | float | Probability of returning an error (0.0 to 1.0) |
statusCodes | int[] | List of HTTP status codes to randomly choose from |
defaultCode | int | Default status code if statusCodes is empty (e.g., 500) |
Error Responses
Section titled “Error Responses”All errors return a consistent format:
{ "error": "error_code", "message": "Human readable message"}Common Error Codes
Section titled “Common Error Codes”| Code | HTTP Status | Description |
|---|---|---|
not_found | 404 | Resource not found |
invalid_json | 400 | Invalid JSON in request |
validation_error | 400 | Validation failed |
missing_field | 400 | Required field missing |
Examples
Section titled “Examples”Reset State Before Tests
Section titled “Reset State Before Tests”curl -X POST http://localhost:4290/state/resetAdd Mock at Runtime
Section titled “Add Mock at Runtime”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}"} }'Check Request History
Section titled “Check Request History”curl "http://localhost:4290/requests?limit=10&path=/api/users"Start Proxy Recording
Section titled “Start Proxy Recording”curl -X POST http://localhost:4290/proxy/start \ -H "Content-Type: application/json" \ -d '{"port": 8888, "mode": "record", "sessionName": "test-session"}'Convert Recordings to Mocks
Section titled “Convert Recordings to Mocks”curl -X POST http://localhost:4290/recordings/convert \ -H "Content-Type: application/json" \ -d '{"deduplicate": true}'See Also
Section titled “See Also”- CLI Reference - Command-line options
- Configuration Reference - Config file format
- Stateful Mocking - State management