Mocklantis Guide
Learn how to create mock servers, configure endpoints, and accelerate your development workflow
đĻInstallation
Get Mocklantis up and running on your machine
Download the application
Visit the download page and select the version for your operating system (macOS, Windows, or Linux).
Install and launch
Follow the installation instructions for your platform. Once installed, launch Mocklantis from your applications folder.
First launch
On first launch, you'll see an empty workspace. You're ready to create your first mock server!
Getting Started
Mocklantis allows you to create mock servers in two ways: Default (blank server) or Import from OpenAPI (auto-generated from spec). Both methods are accessed through the same interface.
Open Create Server Modal
In the left sidebar, locate the Mock Servers section at the top. Click the + button next to "Mock Servers" to open the create server modal.
đĄ The + button is always visible at the top of the sidebar, even when you have existing servers.
Choose Your Method
The modal has two tabs at the top. Select the method that fits your needs:
đ Default (Blank Server)
Create an empty server and manually add endpoints one by one. Perfect for:
- Building a mock API from scratch
- Small projects with few endpoints
- Custom test scenarios
- Learning and experimenting
Required Fields:
Server Name
Example: "My API", "Test Server", "Auth Service"A friendly name to identify your server.
Port
Example: 3000, 8080, 4200The port your mock server will listen on (1-65535). Must be unique.
â ī¸ Port Validation: If the port is already in use by another server, you'll see a warning and cannot proceed.
đ Import from OpenAPI
Auto-generate a complete mock server from an OpenAPI/Swagger specification. Perfect for:
- Mocking existing APIs with documentation
- Large projects with many endpoints
- Team collaboration with shared specs
- Quick prototyping from design specs
Three Import Methods:
1. URL
https://petstore.swagger.io/v2/swagger.jsonPaste a public URL to an OpenAPI spec (JSON or YAML).
2. File
Upload a local OpenAPI file (.json, .yaml, .yml) from your computer.
3. Paste
Click "Open Editor" and paste your OpenAPI spec directly (JSON or YAML format).
Optional Fields:
Server Name (Optional)
Custom name for your server. If not provided, name is extracted from OpenAPI spec.
Port (Optional)
Custom port. If not provided, an available port is automatically assigned.
⨠Auto-Generated: All endpoints, paths, methods, parameters, request/response schemas, and example responses are automatically created from the spec!
Click "New Mock Server"
After filling in the required fields, click the "New Mock Server" button at the bottom of the modal.
Default Method: The server is created instantly and appears in the sidebar. It's not started automatically - you must add at least one endpoint first, then the "Start Server" button becomes active.
OpenAPI Import: Processing may take a few seconds depending on spec size. The server is created with all endpoints and automatically starts - ready to use immediately!
Add Endpoints (Default servers only)
If you created a Default server, it starts empty. You need to add endpoints manually.
How to Add Endpoints:
- Click your server in the sidebar to select it
- In the main area, click the "+ New Endpoint" button (or the dropdown arrow next to it)
- Choose endpoint type:
- HTTP - REST API endpoints (GET, POST, PUT, DELETE, etc.)
- WebSocket - Real-time WebSocket endpoints
- gRPC - Coming soon
- GraphQL - Coming soon
- Configure your endpoint (path, method, response, etc.)
- Changes auto-save - no need to click save!
â ī¸ Important: Servers cannot be started without at least one endpoint. Add an endpoint before clicking "Start Server".
Start Your Server
Once your server has at least one endpoint, click the "Start Server" button in the top section.
â Server Running
- Status indicator turns green and pulsing
- Button changes to "Stop Server"
- Your mock API is now live and ready to receive requests!
đĄ Hot Reload: You can edit endpoints while the server is running. Changes take effect immediately without restarting!
Test Your Mock API
Your mock server is now running! Test it with any HTTP client:
Example with cURL:
curl http://localhost:3000/api/usersOther Tools:
- Postman / Insomnia - REST client applications
- Your App - Point your frontend/mobile app to localhost
- Browser - Visit URLs directly for GET requests
- HTTPie, wget, fetch - Command-line tools
đ Real-time Logging
Open the Logs panel (bottom of the screen) to see all incoming requests in real-time. You can inspect request headers, body, query params, and responses in a Postman-style accordion view!
Proxy
What is Proxy?
Proxy feature allows you to forward unmatched requests to a real backend server. This is incredibly useful when you want to:
- Mock only specific endpoints while keeping others live
- Test your app with a mix of mock and real data
- Gradually migrate from a real API to mocks (or vice versa)
- Debug specific endpoints without affecting the entire API
How Does It Work?
đ´ Proxy OFF (Default)
When a request comes to an undefined endpoint:
đĸ Proxy ON
When a request comes to an undefined endpoint:
âšī¸ If the target API also doesn't have this endpoint, it will return its own 404 error.
How to Use Proxy
Step 1: Open Proxy Settings
Click the Proxy OFF button (or Proxy ON if already enabled) in the server panel.
Step 2: Enable Proxy
Toggle the Enable Proxy switch to ON.
Step 3: Enter Target URL
Enter the URL of your real backend server. For example:
Step 4: Save & Restart
Click Save. If the server is running, it will automatically restart with the new proxy settings.
đ Real-World Example
Scenario: Testing a Login Flow
You're building a mobile app and want to test the login flow. You want to mock the /auth/login endpoint to always return success, but keep all other endpoints (like /user/profile, /products) connected to the real backend.
1. Setup Mock Server
2. Enable Proxy
3. Start Server & Test
â ī¸ Important Notes
- âĸ Defined endpoints always take priority: Mock responses are returned first, proxy is only used for undefined endpoints.
- âĸ Target URL must be accessible: Make sure the proxy target URL is reachable from your machine.
- âĸ Headers are forwarded: Request headers (except Host) are automatically forwarded to the target server.
- âĸ Response is passed through: Whatever the target server returns (including errors) is sent back to the client as-is.
- âĸ Server restart required: When you change proxy settings, the server automatically restarts to apply changes.
Endpoints
Mocklantis supports two types of endpoints, each designed for different use cases. Create as many endpoints as you need - there are no limits!
HTTP/REST Endpoints
Traditional HTTP endpoints supporting all standard methods. Perfect for mocking REST APIs, webhooks, and any HTTP-based service.
Supported HTTP Methods
Rich Features
- âPath Variables: Typed parameters like
/users/{id:number} - âQuery Parameters: Type validation and exact value matching
- âRequest Matching: Match by headers, body, and query params
- âDynamic Responses: Use
{{random.*}}variables for realistic data - âCustom Headers: Full control over request and response headers
- âResponse Delay: Simulate network latency in milliseconds
đĄ REST Conventions? Optional!
While RESTful design is recommended for clean APIs, Mocklantis doesn't enforce it. You're free to structure your endpoints however you need:
- â
RESTful:
GET /users/123 - â
RPC-style:
POST /getUserById - â
Custom:
GET /api/v1/fetch-user-data?id=123 - â Whatever works for your use case!
We're not strict - use the patterns that make sense for your project. Both REST purists and pragmatic developers are welcome here! đ¤
WebSocket Endpoints
Real-time bidirectional communication channels. Perfect for chat applications, live updates, notifications, and any real-time feature.
Four Powerful Modes
CONVERSATIONAL
Pattern-based request/response. Client sends message, server responds based on matching patterns.
STREAMING
Continuous data flow. Server sends messages at regular intervals automatically.
TRIGGERED_STREAMING
Start streaming on demand. Client sends trigger message, server starts sending stream.
Advanced Features
- âMessage Patterns: Match incoming messages by exact, contains, regex, or JSON path
- âLifecycle Events: Custom messages on connect/disconnect
- âConfigurable Intervals: Control streaming frequency and timing
- âClient Limits: Control maximum connected clients
Quick Comparison
| Feature | HTTP/REST | WebSocket |
|---|---|---|
| Connection Type | Request-Response | Bidirectional, Persistent |
| Best For | CRUD operations, APIs | Real-time updates, chat, live data |
| Server Push | No | Yes |
| Overhead | Higher (new connection each request) | Lower (single persistent connection) |
đ Want to Learn More?
The sections above provide a quick overview of both endpoint types. For detailed guides with examples and best practices, continue reading below. We'll dive deep into HTTP/REST features, request matching, status codes, and much more!
HTTP/REST Endpoints
đ HTTP Status Codes
Every HTTP endpoint can return any valid HTTP status code. Mocklantis supports all standard status codes from 200 to 599. Simply click on the status selector in the Response section to choose from popular codes like 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error, and more.
The status selector is searchable - you can type the code number or the status text to quickly find what you need. For example, search "unauthorized" to find 401, or search "403" to find Forbidden.
Tip: Use appropriate status codes to make your mocks realistic. Return 200 for successful operations, 201 for resource creation, 204 for deletions, 400 for validation errors, 404 for missing resources, and 500 for server errors.
đ Request Body Matching
By default, Mocklantis returns your configured response regardless of what's in the request body. But sometimes you want different responses based on the request payload. That's where Request Body Matching comes in.
In the Request â Body tab, you'll find a "Match Body" checkbox. When enabled, Mocklantis will only return your mock response if the incoming request body matches what you specified (as JSON). This is perfect for testing different scenarios - for example, returning success for valid login credentials and error for invalid ones.
If no endpoint matches the request body, Mocklantis returns the first endpoint with "Match Body" disabled, or a 404 if all have matching enabled.
đˇī¸ Request Header Matching
Similar to body matching, you can also match requests based on their headers. In the Request â Headers tab, enable the "Match Headers" checkbox to require specific headers in the incoming request.
This is useful for testing authentication flows (matching Authorization headers), API versioning (matching Accept headers), or any scenario where different headers should trigger different responses.
đ Query Parameter Matching
Query parameters can be validated in two ways: type validation and exact value matching. In the Request â Query Params tab, you can define expected query parameters and choose whether to match their type or exact value.
When "Match Query Params" is enabled, Mocklantis uses a scoring algorithm to find the best matching endpoint. Exact value matches score higher than type matches. If multiple endpoints match, the one with the highest score wins. This allows you to create generic fallback endpoints and specific ones for particular query parameter values.
More details about query parameter types and validation can be found in the Query Parameters section below.
đ¨ Automatic Content-Type Detection
Mocklantis automatically detects and sets the Content-Type header based on your request and response body content. When you type JSON in the body editor, it automatically adds Content-Type: application/json to the headers. The same works for XML content.
The Monaco editor (used for body editing) also provides syntax highlighting, validation, and formatting based on the detected content type. This makes it easy to work with JSON and XML responses without manually configuring everything.
âī¸ Response Configuration
Each HTTP endpoint has a comprehensive response configuration. In the Response section, you can set:
- Status Code: Any HTTP status from 200 to 599
- Response Delay: Simulate network latency in milliseconds (0-60000ms)
- Response Body: JSON, XML, plain text, or any content with syntax highlighting
- Response Headers: Custom headers returned with the response
The response body supports dynamic variables using the {{random.*}} syntax. For example, {{random.number(1,100)}} generates a random number between 1 and 100 each time the endpoint is called. More details about random variables can be found in the Random Variables section below.
⨠Best Practices
- âĸ Use realistic HTTP status codes to make your tests more reliable
- âĸ Create multiple endpoints with different matching rules to simulate various scenarios
- âĸ Use body matching sparingly - it's powerful but can make debugging harder if overused
- âĸ Add response delays to test loading states and race conditions in your app
- âĸ Leverage random variables to generate realistic dynamic data
- âĸ Document your endpoints with descriptive paths and consistent naming
Path Variables
Path variables allow you to create dynamic endpoints that accept parameters in the URL. Use the format {paramName:type} to define typed parameters.
Example:
/users/{id:number}/posts/{slug:slug}đ How to Add Path Variables:
- Select your endpoint
- In the Path input field (top section), type your path with variables
- Use the format:
/path/{variable:type} - Example:
/users/{id:number} - Path variables are automatically validated on each request
đ Express.js Style (Alternative)
You can also use the popular Express.js style :paramName format:
/users/:id/posts/:postIdNote: This format doesn't support type validation. Use {id:type} format if you need type validation.
Tip: You can mix both formats: /users/:id/posts/{slug:slug}
Type Reference
| Type | Description | Valid Examples | Invalid Examples |
|---|---|---|---|
| number | Only digits (integers) | 123, 456, 789 | 12abc, 12.5, abc |
| double | Decimal numbers | 12.5, 123, 0.99 | 12abc, abc |
| string | Only letters (a-z, A-Z) | john, abc, Hello | 123, abc123, john-doe |
| alphanumeric | Letters and digits only | abc123, 12abc, User1 | abc-123, test_1, hello! |
| slug | URL-friendly (letters, digits, hyphens, underscores) | product-123, my_item, test-slug | test slug, item@123 |
| Email address format | [email protected] | test.com, @example.com | |
| uuid | UUID format (8-4-4-4-12) | 550e8400-e29b-41d4-a716-446655440000 | 123, abc-def |
| any | Accepts any value (default) | anything works | - |
| custom regex | Any regex pattern you define | [A-Z]{2}\d{4}, \w{3,16} | depends on pattern |
Real-World Examples
User Management API
/users/{id:number}/users/123/users/abc (returns 400)Blog Posts
/posts/{slug:slug}/comments/{id:number}/posts/my-first-post/comments/42/posts/my post/comments/abcSession Verification
/sessions/{sessionId:uuid}/sessions/550e8400-e29b-41d4-a716-446655440000/sessions/123Custom Regex Patterns
Beyond built-in types, you can define custom regex patterns for advanced validation.
Simply use any regex pattern after the colon. If it's not a built-in type, it will be treated as a regex.
Country Code + Order ID
{code:[A-Z]{2}\d{4}}(2 letters + 4 digits)/orders/{code:[A-Z]{2}\d{4}}/orders/TR1234, /orders/US9999/orders/tr1234, /orders/T1234, /orders/TR12MD5 Hash
{hash:[a-f0-9]{32}}(32 hex chars)/files/{hash:[a-f0-9]{32}}/files/5d41402abc4b2a76b9719d911017c592/files/abc123 (too short)Semantic Version
{version:\d+\.\d+\.\d+}(e.g., 1.2.3)/api/{version:\d+\.\d+\.\d+}/users/api/1.0.0/users, /api/2.15.3/users/api/v1/users, /api/1.0/usersUsername with Length Constraint
{username:\w{3,16}}(3-16 alphanumeric)/profile/{username:\w{3,16}}/profile/john_doe, /profile/user123/profile/jo (too short), /profile/verylongusername123Pro Tips
If you don't specify a type, it defaults to any
Mix and match multiple path variables: /api/{v:number}/users/{name:string}
Type validation happens at runtime - invalid requests return 400 Bad Request
Use slug type for URL-friendly identifiers in your endpoints
Custom regex patterns give you ultimate flexibility - any pattern not matching built-in types is treated as regex
Remember to escape special regex characters: {version:\d+\.\d+} not {version:\d+.\d+}
Random Variables
Random variables allow you to generate dynamic, random data in your request and response bodies at runtime. Use the format {{random.type}} in your response body.
Example Request Body & Response Body:
{
"id": "{{random.uuid}}",
"email": "{{random.email}}",
"name": "{{random.name}}",
"age": {{random.number}},
"ipAddress": "{{random.ip}}",
"createdAt": "{{random.date}}"
}Actual Request & Response (Example):
{
"id": "a3d5f7b9-1234-5678-9abc-def012345678",
"email": "[email protected]",
"name": "Alice Johnson",
"age": 7845,
"ipAddress": "192.168.1.147",
"createdAt": "2024-08-15"
}â ī¸ Important: Quotes for String Types
String types (uuid, email, name, ip, url, website, date, string, alphanumeric, custom) must be wrapped in quotes in JSON. Number types (number, double) and boolean should NOT have quotes.
"ip": "{{random.ip}}""age": {{random.number}}"ip": {{random.ip}} (missing quotes)Random Variable Types
| Type | Usage | Example Output | Default Range/Limit |
|---|---|---|---|
| string | {{random.string}} {{random.string(30)}} | aBcDeFgHiJ | 10 chars (max 50) |
| uuid | {{random.uuid}} | 550e8400-e29b-41d4... | UUID v4 format |
| number | {{random.number}} {{random.number(1,100)}} | 7482 | 0-999 (max 1,000,000) |
| double | {{random.double}} {{random.double(0.0,10.0)}} | 342.78 | 0.0-100.0 (max 1,000,000, 2 decimals) |
| {{random.email}} | [email protected] | RFC 2606 domains | |
| name | {{random.name}} | John Smith | First + Last name |
| boolean | {{random.boolean}} | true | true or false |
| date | {{random.date}} | 2024-11-03 | ISO format (last year) |
| phone | {{random.phone}} | +905123456789 | TR format |
| url | {{random.url}} | https://example.com/api | HTTPS URLs |
| ip | {{random.ip}} | 192.168.1.147 | Private IP range |
| website | {{random.website}} | example.com | Domain names only |
| alphanumeric | {{random.alphanumeric}} {{random.alphanumeric(20)}} | aB3dE9fG2h | 10 chars (max 50) |
| custom | {{random.custom([A-Z]{3}\d{4})}} | ABC1234 | Regex pattern (max 100) |
Advanced Usage
Parameterized Random Types
String with custom length:
{{random.string(30)}}â 30 character stringNumber with range:
{{random.number(1,100)}}â Number between 1 and 100Double with range:
{{random.double(0.0,1.0)}}â Decimal between 0.0 and 1.0Custom Regex Patterns
⨠Supports Nested Parentheses!
Complex regex patterns with nested brackets like [A-Z]{3}\d{4} are fully supported.
Example Patterns:
{{random.custom([A-Z]{3}\d{4})}}â ABC1234 (3 uppercase + 4 digits){{random.custom([a-f0-9]{32})}}â MD5-like hash{{random.custom(\d{3}-\d{2}-\d{4})}}â 123-45-6789 (SSN format)Complete Example
Request Body & Response Body Template:
{
"userId": "{{random.uuid}}",
"username": "{{random.alphanumeric(12)}}",
"email": "{{random.email}}",
"fullName": "{{random.name}}",
"age": {{random.number(18,65)}},
"score": {{random.double(0.0,100.0)}},
"active": {{random.boolean}},
"phone": "{{random.phone}}",
"website": "{{random.website}}",
"ipAddress": "{{random.ip}}",
"registeredAt": "{{random.date}}",
"token": "{{random.custom([A-Z0-9]{16})}}"
}Real-World Use Cases
User Registration: Generate Realistic User Data
When testing user registration flows, you need unique user data for each request. Random variables make this effortless.
{
"success": true,
"user": {
"id": "{{random.uuid}}",
"username": "{{random.alphanumeric(12)}}",
"email": "{{random.email}}",
"fullName": "{{random.name}}",
"phoneNumber": "{{random.phone}}",
"createdAt": "{{random.date}}",
"verified": {{random.boolean}}
},
"token": "{{random.custom([A-Za-z0-9]{64})}}"
}{
"success": true,
"user": {
"id": "a3d5f7b9-1234-5678-9abc-def012345678",
"username": "xK8mP2vQ7nT4",
"email": "[email protected]",
"fullName": "Sarah Williams",
"phoneNumber": "+905123456789",
"createdAt": "2024-08-15",
"verified": true
},
"token": "Xy9Kp2Nm4Qr7Tv3Wz8Ys5Lt6Hu9Jn2Op1Kq4Rw7Sx8Yv3Zu6Kp9Ln2Mt5Qr8Tw1Xv4Yz"
}E-commerce: Dynamic Product Catalog
Generate realistic product catalogs with varying prices, stock levels, and ratings without hardcoding values.
{
"products": [
{
"id": "{{random.uuid}}",
"name": "Wireless Mouse",
"sku": "{{random.custom([A-Z]{3}-\d{6})}}",
"price": {{random.double(9.99,199.99)}},
"stock": {{random.number(0,500)}},
"rating": {{random.double(1.0,5.0)}},
"inStock": {{random.boolean}},
"url": "{{random.url}}"
},
{
"id": "{{random.uuid}}",
"name": "Mechanical Keyboard",
"sku": "{{random.custom([A-Z]{3}-\d{6})}}",
"price": {{random.double(49.99,299.99)}},
"stock": {{random.number(0,200)}},
"rating": {{random.double(1.0,5.0)}},
"inStock": {{random.boolean}},
"url": "{{random.url}}"
}
],
"total": {{random.number(50,500)}}
}{
"products": [
{
"id": "b7c3d8e9-5678-1234-bcde-abc123456789",
"name": "Wireless Mouse",
"sku": "ABC-582941",
"price": 34.79,
"stock": 247,
"rating": 4.37,
"inStock": true,
"url": "https://example.com/api/products/mouse"
},
{
"id": "f2a8b4c6-9012-3456-defg-xyz987654321",
"name": "Mechanical Keyboard",
"sku": "XYZ-193847",
"price": 129.99,
"stock": 87,
"rating": 3.84,
"inStock": false,
"url": "https://example.org/api/products/keyboard"
}
],
"total": 342
}Analytics Dashboard: Metrics & Statistics
Simulate analytics dashboards with dynamic metrics, visitor counts, and performance data.
{
"stats": {
"totalUsers": {{random.number(10000,100000)}},
"activeUsers": {{random.number(1000,10000)}},
"revenue": {{random.double(50000.0,500000.0)}},
"conversionRate": {{random.double(1.0,10.0)}},
"avgSessionTime": {{random.number(120,600)}},
"bounceRate": {{random.double(20.0,80.0)}}
},
"traffic": {
"visitors": {{random.number(500,5000)}},
"pageViews": {{random.number(1000,20000)}},
"uniqueVisitors": {{random.number(300,3000)}}
},
"topPages": [
{
"url": "{{random.url}}",
"views": {{random.number(100,5000)}}
},
{
"url": "{{random.url}}",
"views": {{random.number(100,5000)}}
}
],
"reportDate": "{{random.date}}"
}Tips & Best Practices
Random variables are replaced at runtime on each request
Each request gets unique random values - perfect for testing
Use parameterized types for controlled randomness
All generated values respect maximum limits to prevent overflow
Combine random variables with static data for realistic mock responses
Email domains use RFC 2606 reserved domains (example.com, example.org, example.net)
Remember: String types (ip, email, uuid, etc.) need quotes in JSON. Number/boolean types don't!
Use custom regex patterns for industry-specific formats like order IDs, tracking numbers, or license keys
Response Templating
Response templating allows you to reference incoming request data in your response body. Use the format {{request.category.key}} to include request values dynamically.
Available Variables:
| Category | Syntax | Description | Key Required |
|---|---|---|---|
| path | {{request.path.id}} | Path parameter value | Yes |
| query | {{request.query.name}} | Query parameter value | Yes |
| header | {{request.header.X-Request-Id}} | Request header (case-insensitive) | Yes |
| body | {{request.body}} {{request.body.user.name}} | Full body or field path (JSON/XML) | Optional |
| method | {{request.method}} | HTTP method (GET, POST, etc.) | No |
| url | {{request.url}} | Full request URL | No |
| timestamp | {{request.timestamp}} | ISO timestamp of request | No |
Path Parameters
GET /users/{id:number}
RESPONSE TEMPLATE
{
"userId": "{{request.path.id}}",
"message": "User {{request.path.id}} found",
"requestedAt": "{{request.timestamp}}"
}REQUEST: GET /users/42
ACTUAL RESPONSE
{
"userId": "42",
"message": "User 42 found",
"requestedAt": "2024-01-15T10:30:00.000Z"
}JSON Body & JSONPath
POST /api/users
REQUEST BODY (JSON)
{
"user": {
"name": "John Doe",
"email": "[email protected]"
},
"role": "admin"
}RESPONSE TEMPLATE
{
"status": "created",
"userName": "{{request.body.user.name}}",
"userEmail": "{{request.body.user.email}}",
"assignedRole": "{{request.body.role}}"
}ACTUAL RESPONSE
{
"status": "created",
"userName": "John Doe",
"userEmail": "[email protected]",
"assignedRole": "admin"
}JSONPath Syntax
user.name - Nested object accessitems[0] - Array index accessitems[0].product - Nested array accessXML Body & XPath
When the request body is XML (Content-Type: application/xml), you can extract fields using XPath-like dot notation.
POST /api/orders (XML)
REQUEST BODY (XML)
<order>
<customer>
<name>John Doe</name>
<email>[email protected]</email>
</customer>
<total>150.00</total>
</order>RESPONSE TEMPLATE
{
"orderId": "{{random.uuid}}",
"customerName": "{{request.body.order.customer.name}}",
"customerEmail": "{{request.body.order.customer.email}}",
"orderTotal": "{{request.body.order.total}}"
}ACTUAL RESPONSE
{
"orderId": "a1b2c3d4-5678-90ab-cdef-ghij12345678",
"customerName": "John Doe",
"customerEmail": "[email protected]",
"orderTotal": "150.00"
}XPath Syntax
order.customer.name - Nested element accessusers.user.id - Deep nested access/order/total - Full XPath also supportedContent-Type Detection
Field extraction uses the Content-Type header to determine the parser:
application/jsonâ JSONPathapplication/xmlortext/xmlâ XPathtext/plainâ No field extraction (use{{request.body}}for full body)
Pro Tips
Combine with random variables: {"id": "{{random.uuid}}", "user": "{{request.body.name}}"}
Use {{request.body}} without a path to echo the entire request body
Headers are case-insensitive: {{request.header.content-type}} works the same as {{request.header.Content-Type}}
Missing values return empty string - your response won't break if a field doesn't exist
Headers
Request Headers
Validate incoming request headers to ensure clients send the correct headers. Enable Match Request Headers toggle to activate validation.
đ How to Add Request Headers:
- Select your endpoint
- Click on the Request tab
- Click on the Headers sub-tab
- Click + Add Header button
- Enter header name and expected value
- Enable Match Request Headers toggle
Example:
â Requests with matching headers â 200 OK
â Requests with missing/incorrect headers â 400 Bad Request
đ Real World Examples: Content-Type Behavior
Mocklantis aims to provide a high-quality mocking experience by simulating real-world HTTP behavior. We automatically add Content-Type headers for your convenience, but our validation logic follows actual HTTP standards to ensure your mocks behave like production servers.
How it works: When you add a request body, Mocklantis automatically detects and sets the Content-Type (JSON, XML, HTML, or plain text). However, when validating incoming requests with Match Request Headers enabled, we follow real-world rules:
â Scenario 1: No Body â Content-Type Optional
When there's no request body (common in GET, HEAD, DELETE), Content-Type is not validated. This matches how real HTTP servers behave - no body means Content-Type doesn't matter.
â ī¸ Scenario 2: Body Present, No Content-Type â Error
{"name": "James"}
If a request includes a body but no Content-Type header, validation fails with 400 Bad Request. This protects your mock endpoints from malformed requests, just like real production APIs.
â Scenario 3: Body + Content-Type â Perfect
Content-Type: application/json
{"name": "David"}
A complete, well-formed request with proper Content-Type header passes validation successfully. This is the standard way HTTP clients (like Postman, fetch, axios) send requests.
Why this matters: By following real-world HTTP behavior, Mocklantis helps you catch integration issues early. If your client sends requests without proper headers, you'll discover it during development, not in production.
Response Headers
Add custom headers to your mock responses. Useful for CORS, caching, content-type, and more.
đ How to Add Response Headers:
- Select your endpoint
- Click on the Response tab
- Click on the Headers sub-tab
- Click + Add Header button
- Enter header name and value
Common Examples:
Real-World Use Cases
Authentication: Bearer Token & API Keys
Test protected endpoints by validating authentication headers. Create multiple endpoints to simulate authenticated vs unauthenticated scenarios.
Endpoint 1: Authenticated Access
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...GET /api/profile{
"userId": "12345",
"name": "John Doe",
"email": "[email protected]"
}Endpoint 2: Unauthenticated Access (Same Path)
GET /api/profile{
"error": "Unauthorized",
"message": "Missing or invalid authentication token"
}đĄ How it Works:
Create two endpoints with the same path /api/profile. Endpoint 1 requires the Authorization header and returns user data. Endpoint 2 doesn't match headers and returns 401. Mocklantis automatically routes requests based on header presence!
CORS: Cross-Origin Resource Sharing
Test CORS behavior by adding appropriate response headers. Essential for frontend development with different origins.
CORS-Enabled Endpoint
Access-Control-Allow-Origin: *Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONSAccess-Control-Allow-Headers: Content-Type, AuthorizationAccess-Control-Max-Age: 86400When your frontend (localhost:3000) calls your mock API (localhost:8021), browsers require CORS headers. Add these response headers to enable cross-origin requests.
â ī¸ Preflight Requests:
Browsers send OPTIONS requests before actual requests for CORS. Create a separate OPTIONS endpoint with the same path and return 204 No Content with CORS headers to handle preflight requests.
API Versioning
Test different API versions by validating version headers or using path variables.
Version-Based Routing
Accept: application/vnd.myapi.v2+jsonX-API-Version: 2.0GET /api/usersX-API-Version: 1.0GET /api/usersX-API-Version: 2.0Content Negotiation: JSON vs XML
Return different response formats based on the Accept header.
Format-Based Response
Accept: application/jsonContent-Type: application/json{"name": "John", "age": 30}Accept: application/xmlContent-Type: application/xml<user> <name>John</name> <age>30</age> </user>
Rate Limiting Headers
Simulate rate limiting by returning appropriate headers in responses.
Response Headers for Rate Limiting
X-RateLimit-Limit: 100 (max requests per hour)X-RateLimit-Remaining: 95 (remaining requests)X-RateLimit-Reset: 1699891200 (reset timestamp)Retry-After: 3600 (seconds until reset)Create an endpoint that returns 429 Too Many Requests with these headers to test how your app handles rate limiting.
Caching & Cache Control
Control caching behavior with response headers.
Common Caching Scenarios
Cache-Control: no-cache, no-store, must-revalidateCache-Control: max-age=3600Cache-Control: public, max-age=86400Cache-Control: private, max-age=3600Pro Tips
Request header validation is strict - headers must match exactly
Response headers are sent with every response automatically
Use response headers to simulate real API behavior (CORS, auth tokens, etc.)
Create multiple endpoints with the same path but different header requirements to test authenticated vs unauthenticated flows
Use header matching for API versioning - same path, different responses based on version header
Webhooks
Webhooks allow you to automatically trigger HTTP requests to external services when your mock endpoints are called. This enables you to simulate real-world integrations, test notification systems, and create realistic async workflows.
How it works:
Client Request â Mock Response Sent â Webhook Triggered (async)
â â
Immediate External Service
Response (Slack, Payment, etc.)Key Features:
- âĸ Fire-and-Forget: Webhooks execute asynchronously after the mock response is sent
- âĸ Fully Isolated: Webhook failures never affect your mock endpoint responses
- âĸ Template Variables: Extract values from the original request for your webhook payload
Creating a Webhook
đ How to Create:
- Click the dropdown arrow âŧ next to the "+ New Endpoint" button in the header
- Select "Webhook" from the dropdown menu
- Give your webhook a descriptive name
- Configure the HTTP method and target URL
- Add headers and request body as needed
- Bind the webhook to one or more endpoints
â ī¸ Important:
A webhook will only fire when it's bound to at least one endpoint. Unbound webhooks exist in your configuration but never execute.
Binding Webhooks to Endpoints
There are two ways to create a binding between a webhook and an endpoint:
Method 1: From the HTTP Endpoint (Hooks Tab)
- Select your HTTP endpoint in the sidebar
- Go to the "Hooks" tab in the body section
- You'll see a list of all available webhooks
- Click on a webhook to toggle its binding
Tip: Use the search box to filter webhooks. Click the external link icon to jump to webhook settings.
Method 2: From the Webhook Settings
- Select your webhook in the sidebar (orange "HOOK" badge)
- Find the "Trigger Endpoints" dropdown
- Search and select endpoints to bind
- One webhook can be bound to multiple endpoints
Tip: This method is useful when binding the same webhook to many endpoints at once.
Webhook Configuration
Request Settings
| Setting | Description |
|---|---|
| Method | HTTP method (POST, PUT, GET, DELETE, PATCH, HEAD, OPTIONS) |
| URL | Target URL (http:// or https://) |
| Headers | Custom request headers (key-value pairs) |
| Body | Request body with template variable support |
Advanced Settings
| Setting | Default | Range | Description |
|---|---|---|---|
| Delay | 0 ms | 0-60000 | Wait time before sending |
| Timeout | 30000 ms | 1000-120000 | Max wait for response |
| Retry Count | 0 | 0-10 | Retry attempts on failure |
| Retry Delay | 1000 ms | 100-30000 | Wait between retries |
| Skip SSL Verify | false | - | Ignore SSL cert errors |
Authentication
Mocklantis supports 4 authentication types:
None
No authentication headers. Use for public webhooks.
Basic Auth
Username & password encoded as Base64.
Authorization: Basic dXNlcjpwYXNzBearer Token
JWT or OAuth token in Authorization header.
Authorization: Bearer eyJhbGc...API Key
Custom header or query parameter.
X-API-Key: your-api-key-hereTemplate Variables
Extract values from the original HTTP request and include them in your webhook payload using {{category.key}} syntax.
| Variable | Example | Description |
|---|---|---|
| request.path.* | {{request.path.id}} | Path parameter (e.g., /users/:id) |
| request.query.* | {{request.query.page}} | Query parameter (e.g., ?page=1) |
| request.header.* | {{request.header.X-User-Id}} | Request header value |
| request.body | {{request.body}} | Entire request body as-is |
| request.body.* | {{request.body.user.email}} | JSONPath extraction from body |
| request.method | {{request.method}} | HTTP method (GET, POST, etc.) |
| request.url | {{request.url}} | Full URL path with query string |
| request.timestamp | {{request.timestamp}} | ISO-8601 timestamp |
| random.uuid | {{random.uuid}} | Random UUID v4 |
| random.number | {{random.number(1,100)}} | Random number in range |
JSONPath for Body Extraction:
Example webhook body:
{
"event": "order_created",
"timestamp": "{{request.timestamp}}",
"data": {
"orderId": "{{request.path.id}}",
"customer": "{{request.body.customer.name}}",
"total": {{request.body.total}}
}
}Real-World Use Cases
Sports: Live Match Score Updates
Simulate a sports API that notifies subscribers when match scores change. Perfect for testing real-time sports apps.
- âĸ Push notifications to mobile apps
- âĸ Update live scoreboards
- âĸ Trigger betting system updates
- âĸ Feed social media bots
{
"type": "score_update",
"matchId": "{{request.path.matchId}}",
"homeTeam": "{{request.body.homeTeam}}",
"awayTeam": "{{request.body.awayTeam}}",
"homeScore": {{request.body.homeScore}},
"awayScore": {{request.body.awayScore}},
"minute": {{request.body.minute}},
"eventType": "{{request.body.eventType}}",
"timestamp": "{{request.timestamp}}"
}Stock Market: Price Alerts
Simulate a trading platform that sends alerts when stock prices hit certain thresholds.
- âĸ Price threshold alerts
- âĸ Portfolio rebalancing triggers
- âĸ Market volatility notifications
- âĸ Automated trading signals
{
"alert": "price_threshold",
"symbol": "{{request.path.symbol}}",
"currentPrice": {{request.body.price}},
"change": {{request.body.changePercent}},
"volume": {{request.body.volume}},
"timestamp": "{{request.timestamp}}",
"alertId": "{{random.uuid}}"
}AI/ML: Model Inference Callbacks
Simulate async AI/ML processing where results are delivered via callback after model inference completes.
- âĸ Image classification results
- âĸ NLP processing completion
- âĸ Recommendation engine outputs
- âĸ Batch prediction results
{
"jobId": "{{request.path.jobId}}",
"status": "completed",
"model": "{{request.body.model}}",
"result": {
"prediction": {{request.body.prediction}},
"confidence": {{request.body.confidence}},
"processingTime": {{request.body.processingTimeMs}}
},
"callbackId": "{{random.uuid}}",
"completedAt": "{{request.timestamp}}"
}Payment Processing: Transaction Callbacks
Simulate payment gateway callbacks (like Stripe, PayPal) that notify your app when transactions complete.
- âĸ Order fulfillment triggers
- âĸ Subscription activation
- âĸ Receipt generation
- âĸ Inventory updates
{
"event": "payment.completed",
"transactionId": "{{random.uuid}}",
"orderId": "{{request.body.orderId}}",
"amount": {{request.body.amount}},
"currency": "{{request.body.currency}}",
"paymentMethod": "{{request.body.paymentMethod}}",
"status": "success",
"processedAt": "{{request.timestamp}}",
"metadata": {
"customerId": "{{request.body.customerId}}",
"description": "{{request.body.description}}"
}
}E-commerce: Order Shipping Notifications
Simulate shipping carrier webhooks that notify customers when orders are shipped with tracking info.
- âĸ Customer email notifications
- âĸ SMS tracking updates
- âĸ Order status page updates
- âĸ Delivery estimate calculations
{
"event": "order.shipped",
"orderId": "{{request.path.orderId}}",
"trackingNumber": "{{random.uuid}}",
"carrier": "{{request.body.carrier}}",
"estimatedDelivery": "{{request.body.estimatedDelivery}}",
"items": {{request.body.items}},
"shippingAddress": {{request.body.shippingAddress}},
"notifiedAt": "{{request.timestamp}}"
}IoT: Sensor Alerts
Simulate IoT device webhooks that alert when sensor readings exceed thresholds.
- âĸ Temperature threshold alerts
- âĸ Motion detection notifications
- âĸ Equipment malfunction warnings
- âĸ Environmental monitoring
{
"deviceId": "{{request.path.deviceId}}",
"sensorType": "{{request.body.sensorType}}",
"reading": {
"value": {{request.body.value}},
"unit": "{{request.body.unit}}",
"threshold": {{request.body.threshold}}
},
"alertLevel": "{{request.body.alertLevel}}",
"location": {
"lat": {{request.body.latitude}},
"lng": {{request.body.longitude}}
},
"timestamp": "{{request.timestamp}}"
}Slack: Team Notifications
Send formatted messages to Slack channels when important events occur.
- âĸ New order notifications
- âĸ Error alerts to dev channels
- âĸ Deployment status updates
- âĸ Customer support tickets
{
"text": "New Order Received!",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Order #{{request.path.orderId}}*\nCustomer: {{request.body.customer.name}}\nTotal: ${{request.body.total}}"
}
}
]
}Discord: Game/Community Updates
Send rich embed messages to Discord channels for community updates.
- âĸ Game server status updates
- âĸ Tournament bracket changes
- âĸ Community event reminders
- âĸ Leaderboard updates
{
"content": "Match Update!",
"embeds": [{
"title": "{{request.body.homeTeam}} vs {{request.body.awayTeam}}",
"description": "Score: {{request.body.homeScore}} - {{request.body.awayScore}}",
"color": 5814783,
"fields": [
{"name": "Minute", "value": "{{request.body.minute}}'", "inline": true},
{"name": "Event", "value": "{{request.body.eventType}}", "inline": true}
],
"timestamp": "{{request.timestamp}}"
}]
}Microservices: Inter-Service Communication
Simulate event-driven architecture where services communicate via webhooks.
- âĸ Order â Inventory sync
- âĸ User â Notification service
- âĸ Payment â Fulfillment trigger
- âĸ Analytics event streaming
{
"eventType": "inventory.reserve",
"correlationId": "{{request.header.X-Correlation-Id}}",
"orderId": "{{request.path.orderId}}",
"items": {{request.body.items}},
"warehouseId": "{{request.body.warehouseId}}",
"priority": "{{request.body.priority}}",
"requestedAt": "{{request.timestamp}}"
}Audit Logging: Compliance & Security
Send all API activity to an audit service for compliance and security monitoring.
- âĸ GDPR/HIPAA compliance logging
- âĸ Security incident tracking
- âĸ User activity monitoring
- âĸ Data change history
{
"eventId": "{{random.uuid}}",
"timestamp": "{{request.timestamp}}",
"action": "{{request.body.action}}",
"resource": "{{request.body.resource}}",
"resourceId": "{{request.path.id}}",
"userId": "{{request.header.X-User-Id}}",
"ipAddress": "{{request.header.X-Forwarded-For}}",
"userAgent": "{{request.header.User-Agent}}",
"changes": {{request.body.changes}}
}Social Media: Activity Notifications
Simulate social platform webhooks for likes, follows, comments, and other interactions.
- âĸ Push notifications for new followers
- âĸ Like/comment activity feeds
- âĸ Milestone achievement alerts
- âĸ Creator dashboard updates
{
"event": "new_follower",
"userId": "{{request.path.userId}}",
"follower": {
"id": "{{request.body.followerId}}",
"username": "{{request.body.followerUsername}}",
"displayName": "{{request.body.followerDisplayName}}"
},
"totalFollowers": {{request.body.totalFollowers}},
"timestamp": "{{request.timestamp}}",
"notificationId": "{{random.uuid}}"
}Webhook History & Monitoring
Every webhook execution is logged and visible in the Response tab of your webhook. Monitor, debug, and verify that your webhooks are working correctly in real-time.
What's captured in history:
Real-time updates: Webhook history updates instantly via Server-Sent Events (SSE). Results appear automatically as webhooks execute - no refresh needed!
Testing Webhooks
Mocklantis provides a "Try" button to manually test webhooks without triggering them from an endpoint.
đ How to Test:
- Select your webhook in the sidebar
- Click the "Try" button in the header
- The webhook executes immediately
- Check the Response tab for results
â ī¸ Note:
When testing manually, template variables like {{request.body.field}} won't have real values since there's no triggering request. Use {{random.uuid}} or hardcoded test values for manual testing.
Retry Logic
Configure automatic retries for webhooks that fail due to network issues or temporary service outages.
How retries work:
Attempt 1: Failed (timeout)
â Wait retryDelay (1000ms)
Attempt 2: Failed (500 error)
â Wait retryDelay (1000ms)
Attempt 3: Success! (200 OK)â Success Criteria
HTTP status 200-299 is considered successful. Retries stop immediately on success.
â Failure Criteria
Non-2xx status codes, timeouts, or connection errors trigger retries until max attempts reached.
Troubleshooting
Webhook not firing?
- Check if the webhook is bound to the endpoint you're calling
- Verify the mock server is running
- Check the webhook URL is valid (http:// or https://)
- Look for any validation errors in the webhook configuration
Getting timeout errors?
- Increase the timeout value in Settings tab
- Check if the target URL is reachable from your machine
- Verify no firewall or VPN is blocking the connection
- Try the URL in a browser or with curl first
SSL certificate errors?
- Enable "Skip SSL Verification" in Settings tab for self-signed certs
- This is common in development/staging environments
- Don't use this option when connecting to production services
Template variables not working?
- Check the syntax:
{{request.path.id}}not{{path.id}} - Include the
request.prefix for request data - Ensure the triggering request has the expected data
- For body JSONPath, verify the path exists in the request body
- Check for typos in variable names (case-sensitive for body paths)
History not showing results?
- Select the webhook in the sidebar to see its history
- History is stored per-webhook, not globally
- Results update in real-time via SSE - check your network connection
- History persists during the session but clears when you close Mocklantis
Authentication not working?
- For Basic Auth, ensure username and password are both provided
- For Bearer Token, check the token doesn't have extra whitespace
- For API Key, verify the header name matches what the service expects
- Check the Response tab to see what headers were actually sent
Summary
Webhooks are perfect for:
- â Testing notification systems (Slack, Discord, Email)
- â Simulating payment gateway callbacks
- â Mocking inter-service communication
- â Testing async/event-driven workflows
- â Audit logging simulation
- â IoT device event handling
- â AI/ML job completion callbacks
- â Real-time score/data updates
Key features:
- â Fire-and-forget execution
- â Template variable support
- â Multiple authentication methods
- â Configurable retry logic
- â Real-time history monitoring
- â Delay simulation for realism
- â SSL verification control
- â Multi-endpoint binding
Tips & Best Practices
Use descriptive names so you know what webhooks do at a glance. Example: "Slack Notification - Order Created" instead of "Webhook 1"
Set appropriate timeouts - 30 seconds is usually plenty for most external services
Add delays (100-2000ms) to simulate real-world latency from payment processors and external services
Configure retries (3-5) for critical webhooks like audit logging that must succeed
Double-check webhook URLs before testing - don't accidentally send test data to production systems!
Credentials are stored locally - don't commit sensitive data to version control
Use the "Try" button to test webhooks without triggering from an endpoint
Check the Response tab to debug template variable issues and see what was actually sent
WebSocket Endpoints
Simulate and test real-time WebSocket connections with Mocklantis.
Quick Start
Creating a WebSocket endpoint takes just 3 steps:
- Set the path:
/ws/chat - Choose a mode: Conversational, Streaming, or Triggered Streaming
- Configure messages: Add patterns and responses
Path Configuration
Define the access path for your WebSocket endpoint. The path must always start with /.
Example Paths:
/ws/chat- Simple chat WebSocket/api/v1/notifications- Notification stream/live/stock-prices- Live stock datađĄ Tip: You can change the path while the server is running, active connections are preserved!
Mode Selection
Mocklantis offers 3 different WebSocket modes. Each mode is designed for different use cases:
Conversational Mode
Responds to each incoming message based on specific patterns.
When to use: Chat applications, command-based systems, Q&A bots
Example: User sends "hello" â Responds with "Hi there!"
Streaming Mode
Automatically sends periodic messages when a connection is established.
When to use: Live data feeds, sensor data, real-time analytics
Example: Current stock prices every 1 second
Triggered Streaming Mode
Starts a stream when a specific message is received, sends an initial response, then sends periodic messages.
When to use: On-demand data streams, progressive loading, long-running operations
Example: "start" message â Initial response â Progress updates every 2s
Connection Example
Once your server is running, you can connect to your WebSocket endpoint like this:
JavaScript:
const ws = new WebSocket('ws://localhost:5678/ws/chat');
ws.onopen = () => {
console.log('Connected!');
ws.send('Hello server!');
};
ws.onmessage = (event) => {
console.log('Received:', event.data);
};Python:
import websocket
ws = websocket.create_connection('ws://localhost:5678/ws/chat')
ws.send('Hello server!')
result = ws.recv()
print(f'Received: {result}')Next Steps
Explore Modes in Detail
Learn the detailed features and examples of each mode
Lifecycle Events
Automatic message sending on connection
Advanced Options
Advanced configurations and customizations
Tips & Best Practices
Edit while server is running: When you change endpoint configuration, there's no need to restart the server, changes apply instantly!
Test your patterns: In Conversational and Triggered Streaming modes, test your patterns with simple messages.
Performance: Don't set streaming interval too low (minimum 100ms recommended), otherwise clients may be affected by message load.
đŦ Conversational Mode
Intelligently respond to every incoming message based on patterns. Perfect for chat bots, command systems, and interactive applications!
How Does It Work?
In Conversational Mode, when a client sends a message, Mocklantis checks the pattern list from top to bottom. It sends the response of the first matching pattern.
Workflow:
Pattern Types
Mocklantis offers 4 powerful pattern matching types. Each is optimized for different scenarios:
EXACT Match - Exact Matching
The incoming message must be exactly the same as the pattern. Case-sensitive and whitespace matters.
Pattern:
helloResults:
helloâ MatchesHelloâ No match (uppercase)hello worldâ No match (extra words)đĄ When to use:
- Command-based systems:
/help,/start - Fixed API commands:
PING,STATUS - Specific event names:
user:login
Real-Life Example:
Pattern:
/balanceResponse:
{
"balance": 1250.50,
"currency": "USD"
}CONTAINS Match - Contains
Matches if the incoming message contains the pattern. The most flexible matching type.
Pattern:
errorResults:
errorâ Matchesconnection errorâ MatchesThere was an error in processingâ MatchesErrorâ No match (case-sensitive)đĄ When to use:
- Keyword-based responses: messages containing "help"
- Natural language processing: messages containing "hello", "hi"
- Error catching: messages containing "error", "failed"
Real-Life Example - Chat Bot:
Pattern:
priceResponse:
Our premium plan is $29/month. Type "subscribe" to get started!This pattern catches these messages:
- "What's the price?"
- "price info please"
- "Tell me about pricing"
REGEX Match - Regular Expression
Use regex for advanced pattern matching. The most powerful and flexible option.
Example 1: Email Validation
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$invalid-emailExample 2: Phone Number
^\d{10}$5551234567555-123-4567Example 3: Command Parameters
/send (.*) to (.*)/send money to john/send file to teamđĄ When to use:
- Format validation: email, phone, credit card
- Parameterized commands:
/order [product] qty:[number] - Complex patterns: code snippets, URLs
- Case-insensitive match:
(?i)hello
Real-Life Example - Order System:
Pattern:
^order #(\d+)$Response:
{
"orderId": "12345",
"status": "shipped",
"trackingNumber": "ABC123XYZ"
}order #12345, order #999â ī¸ Warning: Regex syntax errors will prevent the pattern from working. Test it!
JSON_PATH Match - JSON Path Queries
Check specific fields in JSON messages. Ideal for modern APIs!
Example 1: Root Level Field
$.type{
"type": "message",
"content": "Hello"
}Example 2: Nested Object
$.user.profile.role{
"user": {
"profile": {
"role": "admin"
}
}
}Example 3: Array Element
$.users[0].name{
"users": [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]
}Example 4: Nested in Array
$.data.items[1].status{
"data": {
"items": [
{"id": 101, "status": "active"},
{"id": 102, "status": "pending"}
]
}
}đĄ When to use:
- Event type routing: respond based on event type via
$.event - Auth checks: check if
$.auth.tokenexists - Nested data:
$.order.payment.method - Array operations:
$.cart.items[0].id
Real-Life Example - Event Router:
Pattern 1: User Login Event
$.eventMessage: {"event":"login","user":"john"}
Response:
{
"status": "success",
"message": "Welcome back!",
"sessionId": "abc123"
}đĄ Pro Tip: JSON Path only checks for field existence, not its value. Use REGEX for value checking.
Response Templating
Use {{request.message}} to reference the incoming message in your response. For JSON messages, you can access specific fields using dot notation.
Echo & Transform Messages
Example 1: Full Message Echo
Incoming:
{"action":"login","user":"john"}Response Template:
{
"type": "echo",
"received": {{request.message}}
}Actual Response:
{
"type": "echo",
"received": {"action":"login","user":"john"}
}Example 2: Extract Specific Fields
Incoming:
{"action":"subscribe","channel":"news","userId":"123"}Response Template:
{
"status": "subscribed",
"channel": "{{request.message.channel}}",
"user": "{{request.message.userId}}"
}Actual Response:
{
"status": "subscribed",
"channel": "news",
"user": "123"
}Example 3: Nested JSON Access
Incoming:
{
"event": "order",
"data": { "product": "Widget", "quantity": 5 }
}Response Template:
{
"confirmed": true,
"product": "{{request.message.data.product}}",
"qty": "{{request.message.data.quantity}}"
}Actual Response:
{
"confirmed": true,
"product": "Widget",
"qty": "5"
}đĄ Available Variables:
{{request.message}}- Full incoming message{{request.message.field}}- Specific JSON field{{request.message.nested.field}}- Nested field access{{request.timestamp}}- Current ISO timestamp{{random.uuid}}- Random UUID (and other random variables)
Response Configuration
Response Delay
You can add an optional delay (in milliseconds) for each pattern.
Delay: 0ms
â Instant response (default)
Delay: 1000ms
â Response after 1 second
Delay: 3000ms
â Response after 3 seconds (slow network simulation)
đĄ Use Cases:
- Network latency simulation
- Slow server testing (timeout tests)
- Progressive loading UX testing
- Realistic delay for "Thinking..." animations
Response Format
Response can be plain text or JSON. Mocklantis automatically determines content-type.
Plain Text:
Hello! How can I help you?
JSON:
{
"message": "Hello!",
"timestamp": 1234567890,
"userId": "user123"
}Pattern Priority
Patterns are checked from top to bottom. The first matching pattern wins!
â ī¸ Important: Ordering Strategy
- Put specific patterns at the top
- Put general patterns at the bottom (as fallback)
- CONTAINS type is the most general, use carefully
Bad Example â:
help(CONTAINS)/help balance(EXACT)â Pattern 1 catches EVERY message containing "help", Pattern 2 never gets reached!
Good Example â :
/help balance(EXACT)/help order(EXACT)help(CONTAINS - fallback)â Specific commands are checked first, if no match, general help message is sent.
Complete Example: Support Bot
A real customer support bot scenario. Uses all pattern types:
Pattern: hello
Response: Hi! I'm your support assistant. How can I help you today?
Delay: 0ms
Pattern: ^order #(\d+)$
Response:
{
"orderId": "12345",
"status": "shipped",
"estimatedDelivery": "2024-01-20"
}Delay: 500ms
Pattern: /balance
Response:
{
"balance": 1250.50,
"currency": "USD",
"lastUpdated": "2024-01-15T10:30:00Z"
}Delay: 800ms
Pattern: $.action
Message: {"action":"subscribe","plan":"premium"}
Response:
{
"status": "subscribed",
"plan": "premium",
"nextBillingDate": "2024-02-15"
}Delay: 1000ms
Pattern: . (any character)
Response: I didn't understand that. Type "help" for available commands.
Delay: 0ms
Best Practices
Put specific patterns at the top
Check special cases first, then general cases.
Use descriptive names for each pattern
Give names that describe the pattern's purpose: "Login Handler", "Order Status Query"
Use realistic delays
Simulate your production environment's response times.
Add a fallback pattern
Add a general CONTAINS pattern at the end to respond to unexpected messages.
Don't use CONTAINS as the first pattern
Very general patterns can prevent other patterns from working.
Don't use regex for simple matches
If EXACT or CONTAINS is sufficient, don't use regex for performance reasons.
đĄ Streaming Mode
Automatically send periodic messages when a connection is established. Perfect for real-time data feeds, sensor data, and live updates!
How Does It Work?
In Streaming Mode, as soon as the client connects to the WebSocket, Mocklantis automatically starts sending periodic messages. The stream continues even if the client doesn't send any messages.
Workflow:
Configuration
âąī¸Streaming Interval
Wait time between messages (in milliseconds). This interval remains constant.
100msâ Very fast (10 messages per second)1000msâ Normal (1 message per second)5000msâ Slow (1 message per 5 seconds)â ī¸ Performance Note: Don't set the interval too low (minimum 100ms recommended). Very fast streams can overwhelm the client's processing capacity.
đĄ Tip: You can change the interval while the server is running, and the change takes effect immediately!
đStream Messages
List of messages to be sent. Messages are sent sequentially and loop back to the beginning when the list ends.
Message Formats:
Plain Text:
Stock price: $150.25JSON:
{
"symbol": "AAPL",
"price": 150.25,
"timestamp": 1234567890
}XML:
<stock> <symbol>AAPL</symbol> <price>150.25</price> </stock>
đĄ Circular Streaming: Messages are sent in sequence and automatically loop back to the beginning when the list ends. This creates an infinite loop!
Use Cases
Streaming Mode is perfect for many real-time applications:
Stock / Crypto Prices
Simulate live price updates.
Configuration:
Interval: 1000ms (1 second)
Messages: 10-15 different price values
Example Message:
{
"symbol": "BTC",
"price": 42350.75,
"change": "+2.5%",
"volume": 1250000000
}IoT Sensor Data
Simulate sensor data such as temperature, humidity, and pressure.
Configuration:
Interval: 2000ms (2 seconds)
Messages: Different sensor readings
Example Message:
{
"sensorId": "TEMP-001",
"temperature": 23.5,
"humidity": 65,
"timestamp": "2024-01-15T10:30:00Z"
}Live Sports Scores
Match scores, statistics, and updates.
Configuration:
Interval: 3000ms (3 seconds)
Messages: Different match states
Example Messages:
Message 1: {"score": "1-0", "minute": "15"}
Message 2: {"score": "1-0", "minute": "30"}
Message 3: {"score": "2-0", "minute": "42"}
Message 4: {"score": "2-1", "minute": "68"}System Monitoring
System metrics such as CPU, RAM, and disk usage.
Configuration:
Interval: 5000ms (5 seconds)
Messages: Different metric values
Example Message:
{
"cpu": 45.2,
"memory": 62.8,
"disk": 78.5,
"network": 125.3
}Chat Activity Feed
Live chat messages and user activities.
Configuration:
Interval: 4000ms (4 seconds)
Messages: Different user messages
Example Messages:
Message 1: {"user": "Alice", "text": "Hello!"}
Message 2: {"user": "Bob", "text": "How are you?"}
Message 3: {"user": "Charlie", "text": "Great!"}Progress Updates
Progress status of long-running operations.
Configuration:
Interval: 2000ms (2 seconds)
Messages: Progress values from 0% to 100%
Example Messages:
Message 1: {"progress": 10, "status": "Processing..."}
Message 2: {"progress": 25, "status": "Processing..."}
Message 3: {"progress": 50, "status": "Half way..."}
Message 4: {"progress": 75, "status": "Almost done..."}
Message 5: {"progress": 100, "status": "Complete!"}Complete Example: Crypto Price Tracker
A real cryptocurrency exchange simulation. Continuously changing prices, volume, and percentage changes:
Configuration
Path: /live/crypto
Mode: Streaming
Interval: 1500ms (1.5 seconds)
Stream Messages (10 messages):
Message #1:
{
"symbol": "BTC/USD",
"price": 42150.25,
"change": "+1.2%",
"volume": 1250000000,
"timestamp": 1767225600000
}Message #2:
{
"symbol": "BTC/USD",
"price": 42180.5,
"change": "+1.3%",
"volume": 1255000000,
"timestamp": 1767225601500
}Message #3:
{
"symbol": "BTC/USD",
"price": 42165.75,
"change": "+1.2%",
"volume": 1260000000,
"timestamp": 1767225603000
}Message #4:
{
"symbol": "BTC/USD",
"price": 42200,
"change": "+1.4%",
"volume": 1270000000,
"timestamp": 1767225604500
}Message #5:
{
"symbol": "BTC/USD",
"price": 42175.25,
"change": "+1.3%",
"volume": 1265000000,
"timestamp": 1767225606000
}Message #6:
{
"symbol": "BTC/USD",
"price": 42190.5,
"change": "+1.3%",
"volume": 1275000000,
"timestamp": 1767225607500
}Message #7:
{
"symbol": "BTC/USD",
"price": 42210.75,
"change": "+1.4%",
"volume": 1280000000,
"timestamp": 1767225609000
}Message #8:
{
"symbol": "BTC/USD",
"price": 42195,
"change": "+1.4%",
"volume": 1278000000,
"timestamp": 1767225610500
}Message #9:
{
"symbol": "BTC/USD",
"price": 42220.25,
"change": "+1.5%",
"volume": 1285000000,
"timestamp": 1767225612000
}Message #10:
{
"symbol": "BTC/USD",
"price": 42205.5,
"change": "+1.4%",
"volume": 1282000000,
"timestamp": 1767225613500
}đĄ How It Works:
- Client connects
- A message is sent every 1.5 seconds
- After 10 messages, it loops back to the beginning (Message #1)
- Continues as an infinite loop
- Runs until the client disconnects
Example Client Code:
const ws = new WebSocket('ws://localhost:5678/live/crypto');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(`BTC Price: $${data.price} (${data.change})`);
// Update UI
updatePriceChart(data);
};
// Output:
// BTC Price: $42150.25 (+1.2%)
// BTC Price: $42180.50 (+1.3%)
// BTC Price: $42165.75 (+1.2%)
// ...Best Practices
â Use realistic intervals
Simulate the update frequency of your production environment.
â Add variation
Add 10-20 different messages to provide realistic data diversity.
â Include timestamps
Add timestamps to messages so clients can check data freshness.
â Use linear values for progress simulation
Use incrementing values like 0-100 to test loading/progress UIs.
â Don't use very low intervals
Intervals below 100ms can overload the client and cause performance issues.
â Don't add too few messages
A loop with 1-2 messages repeats too quickly and isn't realistic. Add at least 5-10 messages.
Dynamic Updates
âĄLive Configuration Changes
One of Mocklantis's most powerful features: You can change everything while the server is running!
Example Scenario:
- Server started, 3 clients connected, interval: 2000ms
- You changed the interval to 1000ms
- Clients stayed connected, new interval applied immediately
- You added 2 new messages
- New messages were included in the stream in the next cycle
Tips
đĄ Testing Strategy: Start with a large interval (5000ms) and verify the messages. Then gradually reduce the interval to achieve a realistic speed.
đĄ Data Variety: Instead of sending the same message repeatedly, create different versions with small variations (price, timestamp, etc.).
đĄ Client Disconnection Test: Test your reconnection logic by disconnecting and reconnecting the client while the stream is active.
đĄ Multiple Clients: Connect multiple clients to verify that each receives an independent stream with their own timer.
đ¯ Triggered Streaming Mode
Start a stream based on client messages, send an initial response, then send periodic messages and stop automatically. Ideal for long-running operations, progressive loading, and on-demand data streams!
How Does It Work?
Triggered Streaming Mode is a combination of Conversational and Streaming Modes. The client sends a "trigger" message, Mocklantis matches it against patterns, immediately sends the initial response, then begins sending stream messages at the specified interval and stops after the specified duration/count.
Workflow:
Configuration
In Triggered Streaming, you configure each trigger pattern separately:
đ¯Incoming Pattern (Optional)
The message pattern that will trigger the stream. Supports 4 types like Conversational Mode: EXACT, CONTAINS, REGEX, JSON_PATH. If left empty, EVERY message triggers.
Examples:
start(EXACT) - Only "start" triggersdownload(CONTAINS) - Messages containing "download"^process (\d+)$(REGEX) - Like "process 123"$.action(JSON_PATH) - JSON with action field(empty)- EVERY message triggersđĄ Pro Tip: With an empty pattern, you get "any message triggers stream" behavior. Perfect for using the first message as a trigger to start streaming!
âĄInitial Response
The first response sent immediately when a trigger message is received. This message comes before the stream and typically means "processing started."
Example 1: Plain Text
Processing started...Example 2: JSON
{
"status": "started",
"jobId": "job-123",
"message": "Download initiated"
}â ī¸ Important: Initial response is separate from stream messages. This is sent first, then after the interval the first stream message arrives.
đ¨Stream Messages
Messages sent periodically after the initial response. The list is sent in order and loops back to the beginning (circular).
Example: Progress Updates
{"progress": 10}{"progress": 25}{"progress": 50}{"progress": 75}{"progress": 100, "status": "complete"}đĄ Tip: For progress simulation, use linear values (0, 20, 40, 60, 80, 100). For log streaming, add different log lines!
âąī¸Interval
The wait time between stream messages (in milliseconds).
500msâ Fast updates (2 messages per second)1000msâ Normal speed (1 message per second)2000msâ Slow updates (1 message per 2 seconds)đStop Conditions
When will the stream stop? There are two conditions - whichever occurs first stops the stream:
stopAfter (Required) - Time-based
Maximum duration in milliseconds after stream starts (Max: 600000ms = 10 minutes)
10000msâ Stop after 10 seconds30000msâ Stop after 30 seconds60000msâ Stop after 1 minutestopCount (Optional) - Count-based
Stop after how many stream messages? (Max: 50 messages, can be left empty)
5â Stop after 5 messages10â Stop after 10 messages(empty)â Only use stopAfterâ ī¸ Critical: Stream stopping logic: stopAfter OR stopCount - whichever comes first! If both are set, the first to occur wins.
Example Scenario:
- âĸ Interval: 1000ms (1 message per second)
- âĸ stopAfter: 10000ms (10 seconds)
- âĸ stopCount: 5
- âĸ Result: Stops after 5th message (5 seconds), because stopCount was reached first
Response Templating
Use {{request.message}} to reference the trigger message in your responses. Works in both Initial Response and Stream Messages!
Echo Trigger Data in Responses
Example: File Processing with Trigger Data
Trigger Message:
{"action":"process","fileId":"abc123","format":"mp4"}Initial Response Template:
{
"status": "started",
"fileId": "{{request.message.fileId}}",
"format": "{{request.message.format}}",
"jobId": "{{random.uuid}}"
}Actual Initial Response:
{
"status": "started",
"fileId": "abc123",
"format": "mp4",
"jobId": "f7e8d9c0-1234-5678-abcd-ef0123456789"
}Stream Messages with Trigger Data:
Stream Message Template:
{
"fileId": "{{request.message.fileId}}",
"progress": {{random.number(1,100)}},
"timestamp": "{{request.timestamp}}"
}Actual Stream Messages:
{"fileId": "abc123", "progress": 23, "timestamp": "2024-..."}
{"fileId": "abc123", "progress": 67, "timestamp": "2024-..."}
{"fileId": "abc123", "progress": 91, "timestamp": "2024-..."}đĄ Available Variables:
{{request.message}}- Full trigger message{{request.message.field}}- Specific JSON field{{request.message.nested.field}}- Nested field access{{request.timestamp}}- Current ISO timestamp{{random.uuid}}- Random UUID (and other random variables)
â ī¸ Note: The trigger message is captured when the stream starts. All stream messages reference the same trigger message throughout the stream.
Use Cases
Triggered Streaming Mode is ideal for the most complex and realistic scenarios:
File Upload Progress
Send progress updates while a file is being uploaded.
Configuration:
Pattern: upload (CONTAINS)
Initial Response: {"status":"uploading","fileId":"f123"}
Interval: 500ms
stopAfter: 10000ms (10 seconds)
stopCount: 20
Stream Messages:
{"progress": 5, "bytesUploaded": 512000}
{"progress": 10, "bytesUploaded": 1024000}
{"progress": 20, "bytesUploaded": 2048000}
...
{"progress": 100, "status": "complete"}Video Processing
Progress and log messages during video encoding/decoding.
Configuration:
Pattern: $.action (JSON_PATH)
Trigger: {"action":"encode","video":"vid.mp4"}
Initial Response: {"status":"encoding","jobId":"enc-456"}
Interval: 2000ms
stopAfter: 60000ms (1 minute)
Stream Messages:
{"stage": "analyzing", "progress": 10}
{"stage": "encoding", "progress": 30}
{"stage": "encoding", "progress": 60}
{"stage": "finalizing", "progress": 90}
{"stage": "complete", "progress": 100, "url": "..."}AI Text Generation
ChatGPT-style streaming response - delivered word by word.
Configuration:
Pattern: generate (CONTAINS)
Initial Response: {"thinking": true}
Interval: 300ms
stopAfter: 15000ms
stopCount: 30
Stream Messages (word by word):
{"token": "The"}
{"token": "quick"}
{"token": "brown"}
{"token": "fox"}
{"token": "jumps"}
...
{"done": true}Build / Deploy Process
CI/CD pipeline logs, build progress, deployment stages.
Configuration:
Pattern: ^deploy (.*)$ (REGEX)
Trigger: deploy production
Initial Response: Deployment started...
Interval: 1500ms
stopAfter: 45000ms
Stream Messages:
[LOG] Building Docker image... [LOG] Running tests... [LOG] Tests passed â [LOG] Pushing to registry... [LOG] Deploying to k8s... [LOG] Deployment complete! â
Large Data Export
Large data export process, chunk-by-chunk progress.
Configuration:
Pattern: (empty) - EVERY message triggers
Initial Response: {"exportId":"exp-789","status":"started"}
Interval: 1000ms
stopAfter: 30000ms
stopCount: 15
Stream Messages:
{"chunk": 1, "records": 1000, "progress": 10}
{"chunk": 2, "records": 2000, "progress": 20}
...
{"chunk": 10, "records": 10000, "progress": 100, "downloadUrl": "..."}Live Search Results
When user searches, results arrive progressively.
Configuration:
Pattern: search (CONTAINS)
Initial Response: {"searching": true}
Interval: 800ms
stopAfter: 10000ms
stopCount: 10
Stream Messages:
{"results": [{"id": 1, "title": "Result 1"}]}
{"results": [{"id": 2, "title": "Result 2"}]}
{"results": [{"id": 3, "title": "Result 3"}]}
...
{"done": true, "totalResults": 10}Complete Example: Video Upload & Processing
A real video upload scenario. User types "process video.mp4", upload starts, progress arrives, encoded, completed:
Configuration
Path: /api/video-process
Mode: Triggered Streaming
Trigger Pattern:
Incoming Pattern: ^process (.*)$
Match Type: REGEX
Initial Response:
{
"status": "processing_started",
"jobId": "job-abc123",
"filename": "video.mp4",
"timestamp": 1234567890
}Stream Configuration:
Interval: 1000ms
stopAfter: 30000ms (30 seconds)
stopCount: 15 messages
Stream Messages (15 messages):
Message #1 (T+1s):
{
"stage": "uploading",
"progress": 10,
"message": "Uploading file..."
}Message #2 (T+2s):
{
"stage": "uploading",
"progress": 25,
"message": "Uploading file..."
}Message #3 (T+3s):
{
"stage": "uploading",
"progress": 50,
"message": "Upload in progress..."
}Message #4 (T+4s):
{
"stage": "uploading",
"progress": 75,
"message": "Almost uploaded..."
}Message #5 (T+5s):
{
"stage": "uploaded",
"progress": 100,
"message": "Upload complete!"
}Message #6 (T+6s):
{
"stage": "analyzing",
"progress": 100,
"message": "Analyzing video..."
}Message #7 (T+7s):
{
"stage": "encoding",
"progress": 15,
"message": "Encoding started..."
}Message #8 (T+8s):
{
"stage": "encoding",
"progress": 30,
"message": "Encoding 30%..."
}Message #9 (T+9s):
{
"stage": "encoding",
"progress": 50,
"message": "Encoding 50%..."
}Message #10 (T+10s):
{
"stage": "encoding",
"progress": 70,
"message": "Encoding 70%..."
}Message #11 (T+11s):
{
"stage": "encoding",
"progress": 90,
"message": "Almost done..."
}Message #12 (T+12s):
{
"stage": "encoding",
"progress": 100,
"message": "Encoding complete!"
}Message #13 (T+13s):
{
"stage": "finalizing",
"progress": 100,
"message": "Finalizing..."
}Message #14 (T+14s):
{
"stage": "thumbnail",
"progress": 100,
"message": "Generating thumbnail..."
}Message #15 (T+15s):
{
"stage": "complete",
"progress": 100,
"message": "All done!",
"videoUrl": "https://cdn.example.com/video-abc123.mp4",
"thumbnailUrl": "https://cdn.example.com/thumb-abc123.jpg"
}đŦ Timeline:
- T=0s: User sends "process video.mp4"
- T=0s: Initial response sent immediately
- T=1s: Message #1 (Upload 10%)
- T=2s: Message #2 (Upload 25%)
- ...
- T=15s: Message #15 (Complete!) â Stream stops (stopCount reached)
- Total duration: 15 seconds (stopCount came first, didn't reach stopAfter 30s)
Client Code Example:
const ws = new WebSocket('ws://localhost:5678/api/video-process');
ws.onopen = () => {
// Trigger stream
ws.send('process video.mp4');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.status === 'processing_started') {
showProgressBar();
console.log('Job ID:', data.jobId);
} else if (data.stage) {
updateProgress(data.progress, data.message);
if (data.stage === 'complete') {
hideProgressBar();
showSuccessMessage(data.videoUrl);
ws.close();
}
}
};
// Output:
// Job ID: job-abc123
// [Progress: 10%] Uploading file...
// [Progress: 25%] Uploading file...
// ...
// [Progress: 100%] All done!
// Video URL: https://cdn.example.com/video-abc123.mp4Stream Locking (Important!)
A critical feature in Triggered Streaming: New trigger messages are ignored while a stream is active!
â ī¸ Why?
To prevent multiple streams from starting simultaneously. Otherwise, messages would get mixed up and it would be unclear which stream they belong to.
Scenario:
- T=0s: User sends "start" â Stream 1 starts
- T=2s: User sends "start" again â IGNORED! (Stream 1 still active)
- T=15s: Stream 1 stops (stopAfter or stopCount)
- T=17s: User sends "start" â Stream 2 starts (Stream 1 finished, now accepted)
đĄ Testing Tip: Send multiple trigger messages while stream is active to test the lock mechanism. You should see "Ignoring message (stream active)" in backend logs!
Dynamic Configuration
âĄLive Updates (No Restart!)
You can change trigger patterns, stream messages, intervals, and stop conditions while the server is running!
Example Scenario:
- Stream started, interval: 2000ms, stopAfter: 30000ms
- After 5 seconds you changed interval to 1000ms
- Active stream immediately switched to 1s interval
- You reduced stopAfter to 15000ms
- Stream stopped at 15 seconds (new stopAfter value applied)
Best Practices
â Always send initial response
Immediately notify the client that processing has started - critical for UX!
â Make progress linear
Use predictable increments like 0, 20, 40, 60, 80, 100.
â Add "done" flag in final message
Let client know stream is finished: {"done": true}
â Always set stopAfter
Required field, specify maximum duration (max 10 minutes).
â Control message count with stopCount
For progress scenarios where message count is known (0-100 = 10 messages), use stopCount.
â Don't add too many stream messages
5-20 messages is sufficient, they repeat because it's circular.
â Don't set stopAfter too large
10-60 seconds is sufficient for testing, max 10 minutes.
Advanced Tips
đĄ Multiple Trigger Patterns: Define different streams for different triggers. Example: "upload" â upload stream, "process" â processing stream.
đĄ Empty Pattern Trick: If you leave pattern empty, EVERY message starts a stream. Perfect for "first message triggers" behavior.
đĄ Stream Lock Testing: Send 5-10 messages while stream is active to test the lock mechanism. Watch the backend logs!
đĄ Progressive Content: To simulate AI generation, add one word in each message, combine on the client to show full text.
đĄ Error Simulation: Test client's error handling by sending error messages mid-stream:{"error": "Connection lost", "retry": true}
đ Lifecycle Events
Send automatic messages throughout the WebSocket connection lifecycle. Welcome messages when clients connect, goodbye messages when disconnecting, and more!
What are Lifecycle Events?
Lifecycle Events are events that are automatically triggered at specific moments during a WebSocket connection. Mocklantis currently supports the onConnect event.
Supported Events:
onConnect
Triggered when client connects to the WebSocket
onDisconnect
When client disconnects (may be added in the future)
onError
When an error occurs in the connection (may be added in the future)
onConnect Event
Automatically sends a message when the client connects to the WebSocket. Ideal for welcome messages, session information, initial state, and similar data.
đŦMessage
The message to send when the client connects. Can be plain text or JSON.
Plain Text Example:
Welcome to the chat! You are now connected.JSON Example:
{
"event": "connected",
"sessionId": "sess-abc123",
"timestamp": 1234567890,
"message": "Welcome! You are now connected."
}âąī¸Delay (Optional)
How many milliseconds after connection to send the message. Default: 0ms (instant)
0msâ Send instantly (default)500msâ After 0.5 seconds1000msâ After 1 second3000msâ After 3 secondsđĄ When to use delay?
- To simulate server "preparation" time
- To test connection handshake delay
- UX: To show "Connecting..." animation
Use Cases
The onConnect event can be used for many scenarios:
Welcome Message
Notify the user that the connection was successful.
Configuration:
Message: Welcome to our chat! You are now online.
Delay: 0ms
Session Information
Send session ID, user info, and connection details to the client.
Configuration:
Message:
{
"event": "session_created",
"sessionId": "sess-abc123",
"userId": "user-456",
"connectedAt": 1234567890,
"expiresIn": 3600
}Delay: 0ms
Initial State / Data
Send initial data to the client when connection is established.
Configuration:
Message:
{
"type": "initial_state",
"data": {
"unreadMessages": 5,
"onlineUsers": 42,
"serverVersion": "1.2.3"
}
}Delay: 0ms
Server Status
Inform about server health, capabilities, and feature flags.
Configuration:
Message:
{
"server": {
"status": "healthy",
"version": "2.1.0",
"features": ["chat", "files", "video"],
"maintenance": false
}
}Delay: 0ms
Authentication Confirmation
Confirm that authentication was successful and the token is valid.
Configuration:
Message:
{
"auth": "success",
"user": {
"id": "user-123",
"username": "john_doe",
"role": "premium"
},
"permissions": ["read", "write", "admin"]
}Delay: 500ms (auth check simulation)
Instructions / Help
Tell the user how to use the system and what commands are available.
Configuration:
Message:
Welcome! Available commands: /help - Show this message /status - Check server status /users - List online users /quit - Disconnect
Delay: 1000ms (for connection animation)
Timeline Example
See how the onConnect event works with different modes:
Scenario: Conversational Mode + onConnect
Configuration:
- âĸ Mode: Conversational
- âĸ onConnect Message: "Welcome! Send 'hello' to start."
- âĸ onConnect Delay: 500ms
- âĸ Pattern 1: "hello" â "Hi there!"
Timeline:
- T=0ms: Client connects to WebSocket
- T=500ms: onConnect message arrives: "Welcome! Send 'hello' to start."
- T=2000ms: User sends "hello"
- T=2000ms: Pattern matches, response sent: "Hi there!"
Scenario: Streaming Mode + onConnect
Configuration:
- âĸ Mode: Streaming
- âĸ onConnect Message: "Stream starting..."
- âĸ onConnect Delay: 0ms
- âĸ Streaming Interval: 2000ms
- âĸ Stream Messages: ["Message 1", "Message 2", "Message 3"]
Timeline:
- T=0ms: Client connects to WebSocket
- T=0ms: onConnect message arrives immediately: "Stream starting..."
- T=0ms: Streaming timer starts
- T=2000ms: Stream message #1: "Message 1"
- T=4000ms: Stream message #2: "Message 2"
- T=6000ms: Stream message #3: "Message 3"
- T=8000ms: Back to Message 1 (circular)
Scenario: Triggered Streaming + onConnect
Configuration:
- âĸ Mode: Triggered Streaming
- âĸ onConnect Message: {"ready": true, "instruction": "Send 'start' to begin"}
- âĸ onConnect Delay: 1000ms
- âĸ Trigger Pattern: "start"
- âĸ Initial Response: "Processing..."
- âĸ Stream Interval: 1000ms
Timeline:
- T=0ms: Client connects to WebSocket
- T=1000ms: onConnect message arrives: {"ready": true, ...}
- T=3000ms: User sends "start"
- T=3000ms: Initial response sent immediately: "Processing..."
- T=4000ms: Stream message #1
- T=5000ms: Stream message #2
- ...
Best Practices
â Always add an onConnect message
Inform the client that the connection was successful - important for UX!
â Use JSON format
Sending structured data makes client parsing easier.
â Add an event type field
{"event": "connected", ...} helps the client easily distinguish message types.
â Simulate realistic latency with delay
Add 500-1000ms delay to simulate authentication checks.
â Include useful info
Add information like session ID, timestamp, server version.
â Don't send overly long messages
onConnect should be short and concise, use a separate endpoint for large data.
â Don't set delay too high
More than 3 seconds keeps the user waiting, 1-2 seconds is ideal.
Comprehensive Example: Chat Application
onConnect configuration for a production-ready chat application:
Configuration
Path: /chat/room-123
Mode: Conversational
onConnect Event:
Delay: 800ms
Message:
{
"event": "room_joined",
"roomId": "room-123",
"roomName": "General Chat",
"sessionId": "sess-abc456",
"user": {
"id": "user-789",
"username": "john_doe",
"avatar": "https://example.com/avatar.jpg"
},
"stats": {
"onlineUsers": 42,
"totalMessages": 1250
},
"capabilities": {
"canSendImages": true,
"canSendFiles": true,
"maxFileSize": 10485760
},
"commands": [
"/help - Show available commands",
"/users - List online users",
"/history - Show message history"
],
"timestamp": 1234567890
}Client Implementation
const ws = new WebSocket('ws://localhost:5678/chat/room-123');
ws.onopen = () => {
console.log('Connecting to chat room...');
showLoadingSpinner();
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.event === 'room_joined') {
// onConnect message received!
hideLoadingSpinner();
// Display welcome info
showWelcomeMessage(`Welcome to ${data.roomName}!`);
// Update UI with room stats
updateOnlineCount(data.stats.onlineUsers);
// Store session info
localStorage.setItem('sessionId', data.sessionId);
// Display available commands
showCommandsPanel(data.commands);
console.log('Connected to room:', data.roomId);
console.log('Online users:', data.stats.onlineUsers);
} else {
// Handle other message types (chat messages, etc.)
handleChatMessage(data);
}
};
// Expected Console Output:
// > Connecting to chat room...
// (800ms delay...)
// > Connected to room: room-123
// > Online users: 42Tips
đĄ Loading States: Use delay to test your "Connecting..." or "Authenticating..." loading states.
đĄ Error Testing: Test your connection failure handling by sending an error in the onConnect message:{"error": "Room full"}
đĄ Version Checking: Send the server version in onConnect to test client version compatibility checks.
đĄ Initial State Sync: Send initial data with onConnect to test the client's first-render optimization.
đĨ Advanced Options & Tips
Advanced features, debugging techniques, troubleshooting, and production-level test strategies for mastering Mocklantis!
đĨ Multi-Client Testing
Simulate real-world scenarios by testing with multiple clients:
đMultiple Browser Tabs
The easiest method: Open clients in different tabs of the same browser.
Test Steps:
- Connect WebSocket client in the first tab
- Open a second tab, connect to the same endpoint
- Open a third tab, connect to the same endpoint again
- Monitor messages with console.log in each tab
- Streaming: Does each tab receive an independent stream? â
đDifferent Browsers
Perform cross-browser testing with Chrome, Firefox, and Safari.
Why is it important?
- WebSocket implementations may differ
- Reconnection logic varies by browser
- Message handling timings are different
đąMobile + Desktop
Realistic multi-platform testing with phone + computer.
Setup:
- Start Mocklantis server on your computer
- Find your IP address (e.g., 192.168.1.5)
- Open browser on your phone
- Connect to ws://192.168.1.5:5678/your-path
- Test desktop + mobile simultaneously!
đ¯ Advanced Test Scenarios
Advanced strategies for production-level test scenarios:
Reconnection Logic Testing
Simulate network loss and verify the client reconnects.
Test Steps:
- Connect client, start stream
- Stop the Mocklantis server
- Reconnection logic is triggered in the client
- Restart the server
- Does the client reconnect automatically? â
- Does the stream continue? â
Race Condition Testing
Catch race conditions with rapid sequential messages.
Test Code:
// Rapid fire messages
for (let i = 0; i < 10; i++) {
ws.send(`message ${i}`);
}
// Does the client handle it properly?
// Is message order preserved?
// Does the UI freeze?Memory Leak Testing
Run for a long time and check for memory leaks.
Test Strategy:
- Start streaming mode (interval: 1000ms)
- Open Browser DevTools â Performance â Memory
- Run for 10-15 minutes
- Does memory usage increase or stay constant?
- Disconnect â Reconnect
- Is memory cleaned up? â
Error Recovery Testing
Test error handling by sending invalid JSON and malformed data.
Test Messages:
// Invalid JSON
ws.send('{invalid json}');
// Huge message
ws.send('x'.repeat(1000000));
// Special characters
ws.send('\x00\x01\x02');
// Does the client crash?
// Does it show an error message?
// Can it recover?Concurrent Operations
Send messages and receive streams simultaneously.
Scenario:
- Conversational Mode + onConnect active
- onConnect message arrives
- User sends a message simultaneously
- Receives response
- Sends another message simultaneously
- Are all messages handled correctly? â
Load Testing
Perform stress tests with multiple clients.
Test Script:
// Node.js script
const WebSocket = require('ws');
// Create 50 clients
for (let i = 0; i < 50; i++) {
const ws = new WebSocket('ws://localhost:5678/chat');
ws.on('open', () => {
console.log(`Client ${i} connected`);
});
}
// Does the UI stay responsive?
// Is the server stable?
// Are messages distributed correctly?đ§ Troubleshooting
Common problems and solutions:
â Can't connect
- Is the server running? Are there logs in the terminal?
- Is the port correct? (ws://localhost:5678/path)
- Is the path correct? (does it start with /)?
- Is the firewall blocking it?
â ī¸ Pattern not matching
- Is the match type correct? (EXACT is very strict)
- Is there whitespace? ("hello " â "hello")
- Case-sensitive! ("Hello" â "hello")
- JSON_PATH: Does the field actually exist?
- REGEX: Is the syntax correct? Test it
đŦ Not receiving messages
- Is the ws.onmessage handler defined?
- Are there any errors in the console?
- There might be a JSON.parse error, add try-catch
- Is there "Sent response" in the backend log?
đ Stream not starting
- Streaming: Are messages empty?
- Triggered: Make sure you sent the trigger message
- Triggered: Is the stream already active? (check logs)
- Are interval and stopAfter set correctly?
⥠Slow performance
- Is the interval too low? (min 100ms)
- Are there too many patterns? (10-20 ideal)
- Is the regex too complex?
- Is the message size too large?
- Are too many clients connected?
đ Pro Tips & Tricks
đĄ Tip #1: Pattern Priority Testing
Add 2 patterns that match the same message. Does the first one work? Test if priority is correct.
đĄ Tip #2: Timestamp in Every Message
Add timestamps to responses to measure client-side latency.
đĄ Tip #3: Message ID
Give each message a unique ID to test duplicate detection.
đĄ Tip #4: Error Messages
Test error handling by sending {"error": "...", "code": 500} in the middle of a stream.
đĄ Tip #5: Progressive Enhancement
Start with simple patterns, increase complexity as you verify they work.
đĄ Tip #6: Multiple Endpoints
Use different paths for different features: /chat, /notifications, /data
đĄ Tip #7: Browser DevTools Network Tab
You can see WebSocket frames in the Network tab, check the raw data.
đĄ Tip #8: Save Configurations
Export your Mocklantis configs as JSON (future feature), share with your team.
SSE Endpoints
Simulate real-time server-to-client streaming with Server-Sent Events. Perfect for live notifications, AI streaming responses, real-time feeds, and more!
What is SSE?
Server-Sent Events (SSE) is a standard that enables servers to push real-time updates to clients over HTTP. Unlike WebSockets, SSE is unidirectional (server-to-client only), making it simpler and perfect for scenarios where the client only needs to receive data.
SSE vs WebSocket
| Feature | SSE | WebSocket |
|---|---|---|
| Direction | Server â Client (unidirectional) | Bidirectional |
| Protocol | HTTP/HTTPS | WS/WSS |
| Auto Reconnect | Built-in | Manual |
| Event IDs | Built-in | Manual |
| Complexity | Simple | More complex |
When to use SSE: When you need real-time updates from server to client without client sending data back. Examples: notifications, live feeds, AI streaming responses, stock tickers.
Quick Start
Creating an SSE endpoint takes just 3 steps:
- Set the path:
/events - Configure streaming: Set interval and optional retry
- Add messages: Create the events to be streamed
Example: Basic Notification Stream
Path: /notifications
Interval: 3000ms
Messages:
Message 1: {"type": "info", "message": "New user signed up"}
Message 2: {"type": "alert", "message": "Server CPU at 80%"}
Message 3: {"type": "success", "message": "Backup completed"}Path Configuration
Define the access path for your SSE endpoint. The path must always start with /.
Example Paths:
/events- General event stream/api/v1/notifications- Notification stream/stream/prices- Price updates/chat/completions- AI response streamingâ Live Updates: You can change the path while the server is running - active connections are preserved!
SSE Protocol Format
Mocklantis generates SSE messages following the official specification. Here's how the wire format looks:
Wire Format:
id: 1
event: notification
data: {"type": "info", "message": "Hello!"}
id: 2
event: notification
data: {"type": "alert", "message": "Warning!"}
SSE Fields:
id:Event ID
Unique identifier for reconnection support
event:Event Type
Custom event name (defaults to "message")
data:Event Data
The actual message content (JSON, text, etc.)
retry:Retry Interval
Client reconnection delay in milliseconds
đĄ Multi-line Data: When your data contains multiple lines, each line is automatically prefixed with data:. The client reconstructs the original content.
Streaming Settings
âąī¸Interval (ms)
Time between messages in milliseconds. This is the base timing for your stream.
500msâ Fast (2 messages per second)1000msâ Normal (1 message per second)5000msâ Slow (1 message per 5 seconds)đRetry (ms) - Optional
Tells the client how long to wait before attempting to reconnect if the connection drops. This value is sent once when the connection is established.
1000msâ Quick reconnect (1 second)3000msâ Default browser behavior10000msâ Conservative (10 seconds)đSupport Last-Event-ID
When enabled, clients can resume from where they left off after a disconnection.
How it works:
- Client connects and receives events with IDs (1, 2, 3...)
- Connection drops at event ID 5
- Client reconnects with header:
Last-Event-ID: 5 - Server resumes from event ID 6
â ī¸ Important: For this to work, you must assign unique IDs to your messages!
Messages Configuration
Configure the messages that will be streamed to clients. Messages are sent sequentially and loop back to the beginning when the list ends.
Message Fields:
Event Type- optionalCustom event name. Clients can listen for specific event types using addEventListener().
Examples: message, notification, update, error
Event ID- optionalUnique identifier for the event. Required for Last-Event-ID reconnection support.
Formats: 1, 2, 3 (sequential), uuid, timestamp
Data- requiredThe actual content of the event. Can be JSON, plain text, XML, or any format.
{"type": "notification", "message": "Hello!"}Delay (ms)- optionalAdditional delay before sending this specific message. Added on top of the interval.
Example: Interval=1000ms, Delay=5000ms â This message waits 6 seconds total
đĄ Random Variables: You can use random variables in your data! Use {{$randomInt}}, {{$randomEmail}}, etc. to generate dynamic content.
On Connect Message
Optionally send a welcome message immediately when a client connects, before the regular stream starts.
Use Cases:
Example On Connect Message:
{
"status": "connected",
"server": "mocklantis-sse-v1",
"timestamp": "2024-01-15T10:30:00Z"
}Connection Examples
Connect to your SSE endpoint using these examples:
JavaScript (EventSource)
const eventSource = new EventSource('http://localhost:5678/events');
// Listen for default "message" events
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
// Listen for custom event types
eventSource.addEventListener('notification', (event) => {
console.log('Notification:', event.data);
});
// Handle connection events
eventSource.onopen = () => console.log('Connected!');
eventSource.onerror = () => console.log('Error/Reconnecting...');
// Close connection
// eventSource.close();curl
# Basic connection curl -N http://localhost:5678/events # With Last-Event-ID (resume from event 5) curl -N -H "Last-Event-ID: 5" http://localhost:5678/events # The -N flag disables buffering for real-time output
Python (sseclient)
import sseclient
import requests
url = 'http://localhost:5678/events'
response = requests.get(url, stream=True)
client = sseclient.SSEClient(response)
for event in client.events():
print(f'Event: {event.event}')
print(f'ID: {event.id}')
print(f'Data: {event.data}')
print('---')Node.js (eventsource)
import EventSource from 'eventsource';
const es = new EventSource('http://localhost:5678/events');
es.onmessage = (event) => {
console.log('Data:', event.data);
};
es.addEventListener('notification', (event) => {
console.log('Notification:', JSON.parse(event.data));
});Real-World Use Cases
SSE is used across many industries for real-time data delivery. Here are practical examples:
AI/LLM Response Streaming
Mock ChatGPT, Claude, or any AI API that streams responses token by token.
Configuration:
Path: /v1/chat/completions
Interval: 50ms (fast token streaming)
Example Messages (OpenAI format):
{"choices":[{"delta":{"content":"Hello"}}]}
{"choices":[{"delta":{"content":" there"}}]}
{"choices":[{"delta":{"content":"!"}}]}
{"choices":[{"delta":{"content":" How"}}]}
{"choices":[{"delta":{"content":" can"}}]}
{"choices":[{"delta":{"content":" I"}}]}
{"choices":[{"delta":{"content":" help"}}]}
{"choices":[{"delta":{"content":"?"}}]}
[DONE]Industry: AI/ML platforms, chatbots, coding assistants, content generation
Real-Time Notifications
Push notifications for social apps, e-commerce, or enterprise dashboards.
Configuration:
Path: /api/notifications
Interval: 5000ms
Example Messages:
{"type": "like", "user": "john", "message": "liked your post"}
{"type": "comment", "user": "jane", "message": "commented on your photo"}
{"type": "follow", "user": "mike", "message": "started following you"}
{"type": "order", "message": "Your order #1234 has shipped"}Industry: Social media, e-commerce, SaaS platforms, mobile apps
Stock & Crypto Prices
Real-time price feeds for trading platforms and financial dashboards.
Configuration:
Path: /stream/prices
Interval: 1000ms
Example Messages:
{"symbol": "BTC", "price": 42350.75, "change": "+2.5%"}
{"symbol": "ETH", "price": 2245.30, "change": "+1.8%"}
{"symbol": "AAPL", "price": 178.25, "change": "-0.3%"}Industry: FinTech, trading platforms, crypto exchanges, banking
Live Sports Scores
Real-time match updates, scores, and statistics.
Configuration:
Path: /live/match/123
Interval: 3000ms
Example Messages:
{"minute": 15, "score": "1-0", "event": "GOAL", "team": "home"}
{"minute": 32, "score": "1-1", "event": "GOAL", "team": "away"}
{"minute": 45, "event": "HALFTIME"}
{"minute": 78, "score": "2-1", "event": "GOAL", "team": "home"}Industry: Sports betting, live score apps, sports media
IoT Sensor Data
Stream sensor readings from IoT devices - temperature, humidity, motion, etc.
Configuration:
Path: /sensors/room-1
Interval: 2000ms
Example Message:
{
"sensorId": "TEMP-001",
"temperature": 23.5,
"humidity": 65,
"pressure": 1013.25,
"timestamp": "2024-01-15T10:30:00Z"
}Industry: Smart home, industrial IoT, agriculture, healthcare monitoring
Log Streaming
Real-time log output for monitoring dashboards and debugging tools.
Configuration:
Path: /logs/stream
Interval: 500ms
Event Types: info, warn, error
Example Messages:
{"level": "info", "message": "User login: [email protected]"}
{"level": "warn", "message": "High memory usage: 85%"}
{"level": "error", "message": "Database connection timeout"}
{"level": "info", "message": "Request processed in 234ms"}Industry: DevOps, monitoring tools, debugging platforms, observability
News & Social Feeds
Real-time content updates for news sites, social platforms, and content aggregators.
Configuration:
Path: /feed/latest
Interval: 10000ms
Example Messages:
{"type": "article", "title": "Breaking: New Tech Release", "author": "TechNews"}
{"type": "tweet", "user": "@elonmusk", "content": "Exciting announcement..."}
{"type": "post", "user": "jane_doe", "content": "Just shipped v2.0!"}Industry: Media, journalism, social networks, content platforms
Progress & Status Updates
Track long-running operations like file uploads, data processing, or deployments.
Configuration:
Path: /jobs/123/status
Interval: 2000ms
Example Messages:
{"progress": 10, "status": "Initializing..."}
{"progress": 30, "status": "Processing files..."}
{"progress": 60, "status": "Analyzing data..."}
{"progress": 90, "status": "Finalizing..."}
{"progress": 100, "status": "Complete!", "result": "success"}Industry: CI/CD, file hosting, data processing, cloud services
Best Practices
â Use appropriate intervals
Match your production environment. AI streaming: 50-100ms. Notifications: 3-5s. Metrics: 1-2s.
â Add Event IDs for reliability
Enable Last-Event-ID support so clients can resume after disconnection.
â Use Event Types for filtering
Categorize events so clients can subscribe to specific types they care about.
â Include timestamps
Add timestamps to messages for client-side freshness checks.
â Test reconnection scenarios
Verify your client handles reconnection gracefully with Last-Event-ID.
â Don't use too few messages
Add variety - 5-10+ messages create more realistic simulations.
â Don't forget the retry field
Set a reasonable retry interval so clients don't hammer your server on reconnection.
Dynamic Updates
âĄLive Configuration Changes
Mocklantis allows real-time configuration changes without server restart or client disconnection!
Example Scenario:
- Server running, 5 clients connected, interval: 2000ms
- You change interval to 500ms
- All clients stay connected, new interval applies immediately
- You add 3 new messages
- New messages appear in the stream on next cycle
Testing Tips
đĄ Browser DevTools: Open Network tab, filter by "EventStream" to see SSE connections and inspect incoming messages in real-time.
đĄ Multiple Clients: Open multiple browser tabs to verify each client receives their own independent stream.
đĄ Test Reconnection: Kill the connection (curl Ctrl+C) and reconnect with Last-Event-ID header to verify resume functionality.
đĄ Verify Event Types: Use different event types and ensure your client'saddEventListener() calls receive the correct events.
Summary
Mocklantis SSE provides a complete Server-Sent Events implementation with all the features you need:
Features:
- â Event Types
- â Event IDs
- â Per-message Delay
- â Retry Interval
- â Last-Event-ID Support
- â On Connect Message
- â Random Variables
Benefits:
- â Zero Config Complexity
- â Live Updates
- â No Server Restart
- â Connection Preserved
- â Protocol Compliant
- â Production-Ready
Import & Export
Mocklantis provides powerful import and export features to help you quickly create endpoints from existing APIs or save your work for later use. Access these features from the Import & Export button in the top-right corner of the workspace.
đĨImport from Curl
Convert any curl command into a fully configured mock endpoint. Perfect for replicating existing API calls.
đ How to Import from Curl:
- Click the Import & Export button in the top-right corner
- Select "Import from Curl" from the dropdown menu
- Paste your curl command in the text area
- Click "Import"
- Mocklantis will automatically detect:
- HTTP method (GET, POST, PUT, DELETE, etc.)
- Endpoint path and query parameters
- Request headers (Authorization, Content-Type, etc.)
- Request body (if present)
- A new endpoint will be created with all detected parameters
Example Curl Command:
curl -X POST "http://localhost:3000/api/users?page=1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer token123" \
--data '{"name":"John","email":"[email protected]"}'What gets imported:
- Method: POST
- Path: /api/users
- Query Param: page=1 (type: number)
- Request Headers: Content-Type, Authorization
- Request Body: {"name":"John","email":"[email protected]"}
đĄ Pro Tip: You can copy curl commands directly from your browser's Network tab or API documentation!
đImport from .mock
Load previously exported endpoint configurations from .mock files. Great for sharing endpoints or backing up your work.
đ How to Import from .mock:
- Click the Import & Export button in the top-right corner
- Select "Import from .mock" from the dropdown menu
- Choose a .mock file from your computer
- The endpoint configuration will be loaded with all settings:
- Method, path, and status code
- Request and response headers
- Request and response body
- Query parameters and path variables
- Response delay
- The imported endpoint will be added to your current server
Use Cases:
- Team Collaboration: Share endpoint configurations with teammates
- Version Control: Commit .mock files to Git for version tracking
- Backup & Restore: Save your work and restore it later
- Quick Setup: Import pre-configured endpoints for common APIs
đĄ Pro Tip: .mock files are human-readable text files. You can edit them directly if needed!
đžExport as .mock
Save your endpoint configuration to a .mock file. This allows you to backup, share, or version control your mock endpoints.
đ How to Export as .mock:
- Select the endpoint you want to export
- Click the Import & Export button in the top-right corner
- Select "Export as .mock" from the dropdown menu
- Choose a location and filename for the .mock file
- The file will be saved with all endpoint configuration:
- Complete endpoint definition
- All headers and parameters
- Request/response bodies
- Validation rules
â ī¸ Important Notes:
- Only the currently selected endpoint is exported (not the entire server)
- If no endpoint is selected, the first endpoint will be exported
- The export button is disabled if the server has no endpoints
- .mock files are portable - they work across different computers and Mocklantis versions
đĄ Best Practice: Export endpoints regularly to create backups, especially before making major changes!
đComplete Workflow Example
Scenario: Copying an endpoint from production to Mocklantis
- Step 1: Open your browser's Developer Tools (F12)
- Step 2: Go to the Network tab and make a request to the API
- Step 3: Right-click the request â Copy â Copy as cURL
- Step 4: In Mocklantis, click Import & Export â "Import from Curl"
- Step 5: Paste the curl command and click Import
- Step 6: Customize the response body with your mock data
- Step 7: Start the server and test your mock endpoint
- Step 8: Export as .mock to save for future use
đ¯ Result: You've successfully created a mock endpoint that mirrors your production API, and you can now share it with your team or reuse it in different projects!
Pro Tips
đĄ Use curl import to quickly replicate any API call without manual configuration
đĄ Store .mock files in version control (Git) to track endpoint changes over time
đĄ Create a library of .mock files for commonly used endpoints across projects
đ¯ Combine import and export to migrate endpoints between different Mocklantis instances
â After importing, always review and customize the response body to match your testing needs
Logging & Request Monitoring
Mocklantis provides real-time request logging and monitoring for all HTTP requests hitting your mock servers. The Logs panel shows you every detail of incoming requests and outgoing responses, similar to browser DevTools Network tab.
Located at the bottom of the application, the Logs panel automatically captures all traffic and displays it in real-time as requests come in.
đAccessing the Logs Panel
- The Logs panel is located at the bottom of the application
- Click on the "Logs" header to expand/collapse the panel
- The panel shows a count of total logs captured:
Logs (47) - You can resize the panel by dragging the top border up or down
đWhat Gets Logged
Every HTTP request to your mock servers is automatically logged with the following information:
đInspecting Request Details
Click on any log entry to expand it and view full details. The expanded view provides four tabs:
Request Headers
View all headers sent by the client, including Content-Type, Authorization, User-Agent, etc. Useful for debugging authentication issues or content negotiation.
Request Body
Inspect the payload sent by the client. For JSON requests, you'll see the formatted JSON. This helps verify that clients are sending the correct data structure.
Response Headers
See all headers returned by your mock, including Content-Type, CORS headers, custom headers, etc. Verify that your response headers are configured correctly.
Response Body
View the exact response payload sent back to the client. Verify random variables were replaced, response body matches expectations, and JSON structure is correct.
đ¨Visual Color Coding
Logs use color coding to help you quickly identify request types and response statuses:
HTTP Methods:
Status Codes:
đŧReal-World Use Cases
1. Debugging Authentication Issues
When testing login flows, check the Request Headers to verify the Authorization token is being sent correctly. Check the Response Body to ensure your mock is returning the expected token format.
2. Verifying CORS Configuration
Look at Response Headers to confirm CORS headers (Access-Control-Allow-Origin, etc.) are present. Check for OPTIONS requests (preflight) in the logs to ensure they're handled correctly.
3. Testing Random Variables
Expand logs and view Response Body to verify random variables like {{random.uuid}} are being replaced with actual values. Each request should show different random data.
4. Monitoring Response Times
Check the Duration (in milliseconds) for each request. If you've configured a response delay, verify it's working by checking the duration matches your configured delay.
5. Validating Request Matching
When using query parameter matching or header matching, inspect logs to see which endpoint was matched. Check Request Headers and query parameters to verify the matching logic is working as expected.
âĄKey Features
- âReal-time Streaming: Logs appear instantly as requests come in, no refresh needed
- âAuto-scroll: Panel automatically scrolls to show the latest logs
- âResizable Panel: Drag the top border to adjust panel height (150px - 500px)
- âCollapsible: Click the header to show/hide logs panel
- âClear Logs: Remove all logs with a single click using the "Clear Logs" button
- âMulti-server Support: Logs from all running servers appear in a single unified view
- âComplete Request/Response Inspection: View every detail of HTTP transactions
Pro Tips
đĄ Keep the Logs panel open during development to monitor all API traffic in real-time
đĄ Use the timestamp to correlate logs with actions in your frontend application
đĄ Check status codes - orange/red indicates errors that need attention
đĄ Verify request bodies before investigating response issues - often the problem is in what the client sends
đĄ Clear logs periodically to focus on recent requests and improve performance
đĄ Use the duration to identify slow endpoints - if it's much higher than your configured delay, something's wrong
đĄ For WebSocket endpoints, check the logs for the initial HTTP upgrade request