### Install Frontend Dependencies and Start Dev Server Source: https://github.com/burgan-tech/mocklab/blob/master/docs/getting-started.md Navigate to the frontend directory, install npm dependencies, and start the development server for hot-reloading. The dev server proxies API calls to the backend. ```bash cd src/Mocklab.Host/frontend npm install npm run dev ``` -------------------------------- ### List endpoint mock example Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Example of a GET request and its corresponding JSON response. ```http GET /api/users ``` ```json { "users": [ { "id": 1, "name": "John Doe" }, { "id": 2, "name": "Jane Smith" } ] } ``` -------------------------------- ### Start Docker Compose Services Source: https://github.com/burgan-tech/mocklab/blob/master/docs/docker.md Starts Mocklab and its PostgreSQL dependency using a provided docker-compose.yml file. Navigate to the 'docs/' directory first. ```bash cd docs docker compose up -d ``` -------------------------------- ### Start Development Server Source: https://github.com/burgan-tech/mocklab/blob/master/src/Mocklab.Host/frontend/README.md Use this command to start the local development server. The application will be accessible at http://localhost:3000. ```bash npm run dev ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/burgan-tech/mocklab/blob/master/src/Mocklab.Host/frontend/README.md Run this command in your terminal to install all necessary project dependencies. ```bash npm install ``` -------------------------------- ### Query string mock example Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Example of a GET request with query parameters and its corresponding JSON response. ```http GET /api/products?category=electronics ``` ```json { "products": [ { "id": 1, "category": "electronics" } ] } ``` -------------------------------- ### Request Templating Examples Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Examples demonstrating how to use request and helper functions within mock response templates. ```APIDOC ## Example: Full template (headers, request, helpers, loop) ### Description This example shows a complex response template utilizing headers, request details, helper functions, and loops. ### Response Body Example ```json { "correlationId": "{{ headers["x-correlation-id"] | helpers.guid() }}", "path": "{{ request.path }}", "isPremium": {{ request.query["tier"] == "premium" }}, "items": [ {{ for i in 0..2 }} { "id": "{{ helpers.guid() }}", "amount": {{ helpers.rand_int(10, 500) }} }{{ if !for.last }}, {{ end }} {{ end }} ], "user": { "username": "{{ helpers.username() }}", "email": "{{ helpers.email() }}" } } ``` ## Example: Request echo and request.json ### Description This example demonstrates echoing request details and including the parsed JSON body of the incoming request. ### Response Body Example ```json { "echo": { "method": "{{ request.method }}", "path": "{{ request.path }}", "userId": "{{ request.route.id }}", "auth": "{{ request.headers["Authorization"] }}" }, "requestId": "{{ helpers.guid() }}", "bodyParsed": {{ request.json }} } ``` ### Note on Helpers Multiple occurrences of the same helper in one response produce different values (e.g., two `{{ helpers.guid() }}` yield two different UUIDs). ``` -------------------------------- ### Full Template Example Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Demonstrates a comprehensive template using headers, request data, helpers, and loops to generate a dynamic JSON response. ```json { "correlationId": "{{ headers["x-correlation-id"] | helpers.guid() }}", "path": "{{ request.path }}", "isPremium": {{ request.query["tier"] == "premium" }}, "items": [ {{ for i in 0..2 }} { "id": "{{ helpers.guid() }}", "amount": {{ helpers.rand_int(10, 500) }} }{{ if !for.last }}, {{ end }} {{ end }} ], "user": { "username": "{{ helpers.username() }}", "email": "{{ helpers.email() }}" } } ``` -------------------------------- ### Run Mocklab Container with Persistent Data Source: https://github.com/burgan-tech/mocklab/blob/master/docs/docker.md Starts a Mocklab container and mounts a named volume 'mocklab-data' to '/app' to preserve the SQLite database across restarts. ```bash docker run -d \ --name mocklab \ -p 8080:5000 \ -v mocklab-data:/app \ mocklab:latest ``` -------------------------------- ### POST request mock example Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Example of a POST request with a body and its corresponding 201 response. ```http POST /api/users Content-Type: application/json { "name": "New User", "email": "new@example.com" } ``` ```json { "id": 3, "name": "New User", "message": "User created successfully" } ``` -------------------------------- ### Restore Dependencies and Run Backend Source: https://github.com/burgan-tech/mocklab/blob/master/docs/getting-started.md Restore project dependencies and run the MockLab backend application. The application starts on http://localhost:5000 by default. The SQLite database is created automatically on first run. ```bash dotnet restore dotnet run --project src/Mocklab.Host ``` -------------------------------- ### Run Mocklab Container (Basic) Source: https://github.com/burgan-tech/mocklab/blob/master/docs/docker.md Starts a Mocklab container in detached mode, mapping host port 8080 to container port 5000. The application will be accessible at http://localhost:8080. ```bash docker run -d --name mocklab -p 8080:5000 mocklab:latest ``` -------------------------------- ### Per-Environment Configuration with appsettings.json Source: https://github.com/burgan-tech/mocklab/blob/master/docs/integration.md Recommended approach for configuring Mocklab by binding settings from appsettings.json and overriding them per environment. This example shows binding and specific overrides for development and production. ```csharp builder.Services.AddMocklab(options => { builder.Configuration.GetSection("Mocklab").Bind(options); }); ``` ```json { "Mocklab": { "SeedSampleData": true, "EnableUI": true } } ``` ```json { "Mocklab": { "AutoMigrate": false, "SeedSampleData": false, "EnableUI": false } } ``` -------------------------------- ### Conditional Responses: Auth-Based Example Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Demonstrates setting up conditional responses for an API endpoint based on the presence and value of the Authorization header. Rules are evaluated by priority, with the first match determining the response. ```bash # No token -> 401 curl http://localhost:5000/api/secure-data # Expired token -> 403 curl -H "Authorization: Bearer expired" http://localhost:5000/api/secure-data # Valid token -> 200 curl -H "Authorization: Bearer valid-token" http://localhost:5000/api/secure-data ``` -------------------------------- ### Create Mock with Dynamic Template Variables (Scriban) Source: https://context7.com/burgan-tech/mocklab/llms.txt Set up a mock endpoint that uses Scriban templating to generate dynamic response content. This allows for unique values like GUIDs, usernames, emails, random numbers, and timestamps in each response. ```bash curl -X POST "http://localhost:5000/_admin/mocks" \ -H "Content-Type: application/json" \ -d '{ "httpMethod": "GET", "route": "/api/users/random", "statusCode": 200, "responseBody": "{\n \"id\": \"{{ helpers.guid() }}\",\n \"username\": \"{{ helpers.username() }}\",\n \"email\": \"{{ helpers.email() }}\",\n \"age\": {{ helpers.rand_int(18, 65) }},\n \"apiKey\": \"{{ helpers.alphanum(32) }}\",\n \"requestedAt\": \"{{ iso_timestamp }}\",\n \"requestPath\": \"{{ request.path }}\"\n}", "contentType": "application/json", "description": "Random user with dynamic values", "isActive": true }' ``` -------------------------------- ### Get Specific Mock Details Source: https://context7.com/burgan-tech/mocklab/llms.txt Fetch detailed information for a specific mock, including its rules and sequence items, by its ID. ```bash curl "http://localhost:5000/_admin/mocks/1" ``` -------------------------------- ### Rate Limiting Sequence Example Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Illustrates a sequence for testing rate limiting. It returns 200 OK twice before returning a 429 Too Many Requests status code. ```bash # This example does not contain executable code, but describes a sequence. ``` -------------------------------- ### Production Environment Mocklab Configuration Source: https://github.com/burgan-tech/mocklab/blob/master/docs/integration.md Configure Mocklab for a production environment. This setup uses the host database, disables auto-migration, seeding, and the UI, and sets a route prefix. ```csharp builder.Services.AddMocklab(options => { options.UseHostDatabase = true; options.DatabaseProvider = "postgresql"; options.SchemaName = "mocklab"; options.RoutePrefix = "mock"; options.AutoMigrate = false; options.SeedSampleData = false; options.EnableUI = false; }); ``` -------------------------------- ### Retry Testing Sequence Example Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Demonstrates a mock for POST /api/orders with sequential responses for testing retry logic. The sequence cycles through 500, 503, and 200 status codes, wrapping around after the last step. ```bash curl -X POST http://localhost:5000/api/orders # -> 500 curl -X POST http://localhost:5000/api/orders # -> 503 curl -X POST http://localhost:5000/api/orders # -> 200 (success!) curl -X POST http://localhost:5000/api/orders # -> 500 (wrap-around) ``` -------------------------------- ### Simulating Response Delay with cURL Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Example of how to test a delayed response using cURL. The response will arrive after the specified delay. ```bash curl http://localhost:5000/api/reports/heavy # Response arrives after ~3 seconds ``` -------------------------------- ### Get Specific Mock Source: https://context7.com/burgan-tech/mocklab/llms.txt Retrieves a specific mock with its associated rules and sequence items. ```APIDOC ## Get Specific Mock ### Description Get a specific mock with rules and sequence items. ### Method GET ### Endpoint `/_admin/mocks/{mockId}` ### Parameters #### Path Parameters - **mockId** (string) - Required - The ID of the mock to retrieve. ``` -------------------------------- ### Useful Docker Compose Commands Source: https://github.com/burgan-tech/mocklab/blob/master/docs/docker.md Common commands for managing services defined in a docker-compose.yml file, including starting, viewing logs, stopping, and removing services and their associated volumes. ```bash # Start services docker compose up -d # View Mocklab logs docker compose logs -f mocklab # Stop services docker compose down # Stop and reset database docker compose down -v ``` -------------------------------- ### Querying Request Logs with cURL Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Provides examples of using cURL to query MockLab's request logs for debugging and analysis. Supports filtering by match status, method, and time. ```bash # All logs (paginated) curl "http://localhost:5000/_admin/logs?page=1&pageSize=20" ``` ```bash # Only unmatched requests (debug "why 404?") curl "http://localhost:5000/_admin/logs?isMatched=false" ``` ```bash # Only POST requests curl "http://localhost:5000/_admin/logs?method=POST" ``` ```bash # Count requests in last 5 minutes curl "http://localhost:5000/_admin/logs/count?minutes=5" ``` ```bash # Clear all logs curl -X DELETE "http://localhost:5000/_admin/logs/clear" ``` -------------------------------- ### GET /_admin/mocks Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Retrieve a list of all mocks, with optional filtering by activity status or collection ID. ```APIDOC ## GET /_admin/mocks ### Description List all mocks, optionally filtered by query parameters. ### Method GET ### Endpoint /_admin/mocks ### Parameters #### Query Parameters - **isActive** (bool) - Optional - Filter active mocks - **collectionId** (int) - Optional - Filter by collection ID ``` -------------------------------- ### Conditional Responses: Body-Based Example Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Illustrates creating conditional responses for a POST request based on values within the request body, such as amount and currency. This allows for dynamic validation and error handling. ```bash # Normal payment -> 200 curl -X POST http://localhost:5000/api/payments \ -H "Content-Type: application/json" \ -d '{"amount": 500, "currency": "TRY"}' # High amount -> 400 curl -X POST http://localhost:5000/api/payments \ -H "Content-Type: application/json" \ -d '{"amount": 15000, "currency": "TRY"}' # Unsupported currency -> 422 curl -X POST http://localhost:5000/api/payments \ -H "Content-Type: application/json" \ -d '{"amount": 500, "currency": "BTC"}' ``` -------------------------------- ### Build Project for Production Source: https://github.com/burgan-tech/mocklab/blob/master/src/Mocklab.Host/frontend/README.md Execute this command to build the project for production deployment. ```bash npm run build ``` -------------------------------- ### Build and Run Mocklab with Docker Source: https://github.com/burgan-tech/mocklab/blob/master/README.md Commands to build a Docker image and run the Mocklab container. ```bash docker build -t mocklab:latest . docker run -d --name mocklab -p 8080:5000 mocklab:latest ``` -------------------------------- ### GET /_admin/logs Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Retrieve paginated request logs with various filtering options. ```APIDOC ## GET /_admin/logs ### Description List request logs with pagination and filtering. ### Method GET ### Endpoint /_admin/logs ### Parameters #### Query Parameters - **method** (string) - Optional - Filter by HTTP method - **statusCode** (int) - Optional - Filter by response status code - **isMatched** (bool) - Optional - Filter matched/unmatched requests - **from** (datetime) - Optional - Start date filter - **to** (datetime) - Optional - End date filter - **page** (int) - Optional - Page number - **pageSize** (int) - Optional - Items per page ``` -------------------------------- ### Add Mocklab Reference Source: https://github.com/burgan-tech/mocklab/blob/master/README.md Add the Mocklab host project as a reference to your existing .NET project. ```bash dotnet add reference path/to/Mocklab.Host.csproj ``` -------------------------------- ### Generate Migrations for All Providers Source: https://github.com/burgan-tech/mocklab/blob/master/docs/getting-started.md Use the helper script to create migrations for all supported database providers simultaneously. ```bash ./add-migration.sh ``` -------------------------------- ### Configure PostgreSQL Integration Source: https://context7.com/burgan-tech/mocklab/llms.txt Set up Mocklab to use an existing PostgreSQL database with schema isolation. ```json { "ConnectionStrings": { "DefaultConnection": "Host=localhost;Port=5432;Database=myapp;Username=myuser;Password=mypassword" }, "Mocklab": { "UseHostDatabase": true, "DatabaseProvider": "postgresql", "SchemaName": "mocklab", "AutoMigrate": true } } ``` ```csharp // Tables created in separate schema: mocklab."MockResponses", mocklab."MockCollections", etc. builder.Services.AddMocklab(options => { options.UseHostDatabase = true; options.DatabaseProvider = "postgresql"; options.SchemaName = "mocklab"; options.RoutePrefix = "mock"; }); ``` -------------------------------- ### Run Mocklab with Environment Variables Source: https://context7.com/burgan-tech/mocklab/llms.txt Runs Mocklab with custom environment variables to enable sample data, the UI, and set a route prefix. Ensure ports are correctly mapped. ```bash docker run -d \ --name mocklab \ -p 8080:5000 \ -e Mocklab__SeedSampleData=true \ -e Mocklab__EnableUI=true \ -e Mocklab__RoutePrefix=mock \ mocklab:latest ``` -------------------------------- ### Build Mocklab Docker Image Source: https://github.com/burgan-tech/mocklab/blob/master/docs/docker.md Builds the Mocklab Docker image from the project root. This command creates a multi-stage image containing both the React frontend and .NET backend. ```bash docker build -t mocklab:latest . ``` -------------------------------- ### Run Mocklab Standalone Source: https://github.com/burgan-tech/mocklab/blob/master/README.md Commands to clone and execute the Mocklab host project. ```bash git clone https://github.com/user/mocklab.git cd mocklab dotnet run --project src/Mocklab.Host ``` -------------------------------- ### Build Frontend for Embedding Source: https://github.com/burgan-tech/mocklab/blob/master/docs/getting-started.md Build the React admin UI for embedding into the .NET DLL as static files. The output is served automatically by the middleware at /_admin/. ```bash cd src/Mocklab.Host/frontend npm run build ``` -------------------------------- ### Import Mock from cURL Command Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Shows how to import a mock by providing a cURL command. MockLab will parse the command to create a mock response. ```http POST /_admin/mocks/import/curl Content-Type: application/json { "curl": "curl -X GET https://api.example.com/users -H 'Accept: application/json'" } ``` -------------------------------- ### Manage Data Buckets Source: https://context7.com/burgan-tech/mocklab/llms.txt Create and list JSON datasets for use within Scriban templates. ```bash # Create a data bucket for a collection curl -X POST "http://localhost:5000/_admin/collections/1/data-buckets" \ -H "Content-Type: application/json" \ -d '{ "name": "products", "description": "Sample product data", "data": "[{\"id\": 1, \"name\": \"Laptop\", \"price\": 999}, {\"id\": 2, \"name\": \"Phone\", \"price\": 599}]" }' # List data buckets curl "http://localhost:5000/_admin/collections/1/data-buckets" # Use in mock templates # {{ products[0].name }} -> "Laptop" # {{ random_item("products").price }} -> 999 or 599 curl -X POST "http://localhost:5000/_admin/mocks" \ -H "Content-Type: application/json" \ -d '{ "httpMethod": "GET", "route": "/api/products/random", "statusCode": 200, "responseBody": "{{ random_item(\"products\") | json }}", "contentType": "application/json", "collectionId": 1, "isActive": true }' ``` -------------------------------- ### Configure Request Echoing Source: https://context7.com/burgan-tech/mocklab/llms.txt Create a mock that echoes request details back in the response using template variables. ```bash curl -X POST "http://localhost:5000/_admin/mocks" \ -H "Content-Type: application/json" \ -d '{ "httpMethod": "POST", "route": "/api/echo/{id}", "statusCode": 200, "responseBody": "{\n \"echo\": {\n \"method\": \"{{ request.method }}\",\n \"path\": \"{{ request.path }}\",\n \"routeId\": \"{{ request.route.id }}\",\n \"auth\": \"{{ request.headers[\"Authorization\"] }}\",\n \"queryPage\": \"{{ request.query.page }}\"\n },\n \"requestId\": \"{{ helpers.guid() }}\",\n \"receivedBody\": {{ request.json }}\n}", "contentType": "application/json", "description": "Echo request details", "isActive": true }' # Test echo endpoint curl -X POST "http://localhost:5000/mock/api/echo/123?page=5" \ -H "Authorization: Bearer my-token" \ -H "Content-Type: application/json" \ -d '{"name": "test", "value": 42}' ``` -------------------------------- ### Configure Mocklab Services in Program.cs Source: https://github.com/burgan-tech/mocklab/blob/master/docs/integration.md Configure Mocklab services and middleware in your application's Program.cs file. This includes adding Mocklab services and enabling its middleware. ```csharp using Mocklab.Host.Extensions; var builder = WebApplication.CreateBuilder(args); // Your existing services builder.Services.AddControllers(); // Add Mocklab builder.Services.AddMocklab(options => { builder.Configuration.GetSection("Mocklab").Bind(options); }); var app = builder.Build(); // Enable Mocklab middleware app.UseMocklab(); app.MapControllers(); app.Run(); ``` -------------------------------- ### Configure Mocklab via appsettings.json Source: https://context7.com/burgan-tech/mocklab/llms.txt Define Mocklab settings in the configuration file and bind them in the application code. ```json { "Mocklab": { "UseHostDatabase": false, "DatabaseProvider": "sqlite", "ConnectionString": "Data Source=mocklab.db", "SchemaName": "mocklab", "AutoMigrate": true, "SeedSampleData": true, "RoutePrefix": "mock", "AdminRoutePrefix": "_admin", "EnableUI": true } } ``` ```csharp // Bind configuration in Program.cs builder.Services.AddMocklab(options => { builder.Configuration.GetSection("Mocklab").Bind(options); }); ``` -------------------------------- ### Configure Mocklab in appsettings.json Source: https://github.com/burgan-tech/mocklab/blob/master/docs/integration.md Configure Mocklab settings such as database usage, migrations, sample data, UI enablement, and route prefix in appsettings.json. ```json { "Mocklab": { "UseHostDatabase": false, "AutoMigrate": true, "SeedSampleData": true, "EnableUI": true, "RoutePrefix": "mock" } } ``` -------------------------------- ### Configure Mocklab Integration Source: https://github.com/burgan-tech/mocklab/blob/master/README.md Configure Mocklab with a specific route prefix and sample data seeding. ```csharp builder.Services.AddMocklab(options => { options.RoutePrefix = "mock"; // Serve mocks under /mock/... options.SeedSampleData = true; }); app.UseMocklab(); ``` -------------------------------- ### Manage Mocklab Container Source: https://github.com/burgan-tech/mocklab/blob/master/docs/docker.md Provides essential commands for managing a running Mocklab Docker container, including viewing logs, stopping, and removing the container. ```bash # View logs docker logs -f mocklab # Stop docker stop mocklab # Remove docker rm mocklab ``` -------------------------------- ### Docker Compose Configuration using Pre-built Image Source: https://github.com/burgan-tech/mocklab/blob/master/docs/docker.md Configures Docker Compose to use a pre-built Mocklab image instead of building from source. Includes port mapping, environment variables, and restart policy. ```yaml services: mocklab: image: mocklab:latest ports: - "8080:5000" environment: Mocklab__SeedSampleData: "true" restart: unless-stopped ``` -------------------------------- ### Create a Mock Response via Admin API Source: https://context7.com/burgan-tech/mocklab/llms.txt Use the admin API to create a new mock endpoint and verify it. ```bash curl -X POST "http://localhost:5000/_admin/mocks" \ -H "Content-Type: application/json" \ -d '{ "httpMethod": "GET", "route": "/api/users", "statusCode": 200, "responseBody": "{\"users\": [{\"id\": 1, \"name\": \"John Doe\"}, {\"id\": 2, \"name\": \"Jane Smith\"}]}", "contentType": "application/json", "description": "Get all users", "isActive": true }' # Response: 201 Created # { # "id": 1, # "httpMethod": "GET", # "route": "/api/users", # "statusCode": 200, # "responseBody": "{\"users\": [...]}", # "contentType": "application/json", # "description": "Get all users", # "isActive": true, # "createdAt": "2026-01-30T10:00:00Z" # } # Test the mock endpoint curl "http://localhost:5000/mock/api/users" # Returns: {"users": [{"id": 1, "name": "John Doe"}, {"id": 2, "name": "Jane Smith"}]} ``` -------------------------------- ### Integrate Mocklab in ASP.NET Core Source: https://context7.com/burgan-tech/mocklab/llms.txt Register Mocklab services and middleware in the application startup. ```csharp using Mocklab.Host.Extensions; var builder = WebApplication.CreateBuilder(args); // Add Mocklab services with options builder.Services.AddMocklab(options => { options.RoutePrefix = "mock"; // Serve mocks under /mock/... options.SeedSampleData = true; // Populate with sample data options.EnableUI = true; // Enable admin UI at /_admin/ options.AutoMigrate = true; // Apply migrations automatically }); var app = builder.Build(); // Enable Mocklab middleware app.UseMocklab(); app.MapControllers(); app.Run(); // Admin UI: http://localhost:5000/_admin/ // Mock endpoints: http://localhost:5000/mock/api/... ``` -------------------------------- ### Create Mock API Endpoint Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Demonstrates how to create a new mock API endpoint using an HTTP POST request to the MockLab admin interface. ```http POST /_admin/mocks Content-Type: application/json { "httpMethod": "GET", "route": "/api/products", "statusCode": 200, "responseBody": "{\"products\": [{\"id\": 1, \"name\": \"Laptop\"}]}", "contentType": "application/json", "description": "Product list", "isActive": true } ``` -------------------------------- ### Docker Compose for Production Deployment with PostgreSQL Source: https://context7.com/burgan-tech/mocklab/llms.txt A Docker Compose configuration for deploying Mocklab with PostgreSQL. It sets up the Mocklab service, PostgreSQL database, and defines health checks and volumes for persistence. ```yaml services: mocklab: build: context: .. dockerfile: Dockerfile ports: - "8080:5000" environment: ConnectionStrings__DefaultConnection: "Host=postgres;Port=5432;Database=mocklab;Username=postgres;Password=postgres" Mocklab__UseHostDatabase: "true" Mocklab__DatabaseProvider: "postgresql" Mocklab__SchemaName: "mocklab" Mocklab__AutoMigrate: "true" Mocklab__SeedSampleData: "true" Mocklab__EnableUI: "true" depends_on: postgres: condition: service_healthy postgres: image: postgres:17 environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: mocklab volumes: - postgres-data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 5s retries: 5 volumes: postgres-data: ``` -------------------------------- ### Generate Individual Migrations Source: https://github.com/burgan-tech/mocklab/blob/master/docs/getting-started.md Run migrations for specific providers using the dotnet CLI, optionally setting the MOCKLAB_DB_PROVIDER environment variable. ```bash # SQLite dotnet ef migrations add \ --project src/Mocklab.Migrations.Sqlite \ --startup-project src/Mocklab.Host # PostgreSQL MOCKLAB_DB_PROVIDER=postgresql dotnet ef migrations add \ --project src/Mocklab.Migrations.PostgreSql \ --startup-project src/Mocklab.Host ``` -------------------------------- ### Run Mocklab Container with Custom Configuration Source: https://github.com/burgan-tech/mocklab/blob/master/docs/docker.md Runs a Mocklab container with custom environment variables to override default settings. Use double underscore notation for nested settings. ```bash docker run -d \ --name mocklab \ -p 8080:5000 \ -e Mocklab__SeedSampleData=true \ -e Mocklab__EnableUI=true \ mocklab:latest ``` -------------------------------- ### Import OpenAPI/Swagger Specification Source: https://context7.com/burgan-tech/mocklab/llms.txt Use this endpoint to generate mocks from an OpenAPI specification. Ensure the OpenAPI JSON is correctly formatted. ```bash curl -X POST "http://localhost:5000/_admin/mocks/import/openapi" \ -H "Content-Type: application/json" \ -d '{ "openApiJson": "{\"openapi\": \"3.0.0\", \"info\": {\"title\": \"Pet Store\", \"version\": \"1.0\"}, \"paths\": {\"/pets\": {\"get\": {\"responses\": {\"200\": {\"description\": \"List of pets\"}}}}, \"/pets/{id}\": {\"get\": {\"responses\": {\"200\": {\"description\": \"Pet by ID\"}}}}}}"' ``` -------------------------------- ### Docker Compose Configuration for Mocklab with PostgreSQL Source: https://github.com/burgan-tech/mocklab/blob/master/docs/docker.md Defines the services for Mocklab and PostgreSQL using Docker Compose. This configuration specifies build context, ports, environment variables for database connection and Mocklab settings, and service dependencies. ```yaml services: mocklab: build: context: .. dockerfile: Dockerfile ports: - "8080:5000" environment: ConnectionStrings__DefaultConnection: "Host=postgres;Port=5432;Database=mocklab;Username=postgres;Password=postgres" Mocklab__UseHostDatabase: "true" Mocklab__DatabaseProvider: "postgresql" Mocklab__SchemaName: "mocklab" Mocklab__AutoMigrate: "true" Mocklab__SeedSampleData: "true" Mocklab__EnableUI: "true" depends_on: postgres: condition: service_healthy ``` -------------------------------- ### Development Environment Mocklab Configuration Source: https://github.com/burgan-tech/mocklab/blob/master/docs/integration.md Configure Mocklab for a development environment with a specified route prefix, sample data enabled, and the admin UI active. ```csharp builder.Services.AddMocklab(options => { options.RoutePrefix = "mock"; options.SeedSampleData = true; options.EnableUI = true; }); ``` -------------------------------- ### Import Mocks Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Import mock configurations from cURL commands or OpenAPI/Swagger specifications. ```APIDOC ## Import from cURL ### Description Parses a cURL command and creates a mock response from it. ### Method POST ### Endpoint `/_admin/mocks/import/curl` ### Request Body - **curl** (string) - Required - The cURL command to import. ### Request Example ```http POST /_admin/mocks/import/curl Content-Type: application/json { "curl": "curl -X GET https://api.example.com/users -H 'Accept: application/json'" } ``` ## Import from OpenAPI / Swagger ### Description Parses an OpenAPI JSON spec and creates mock responses for each endpoint. ### Method POST ### Endpoint `/_admin/mocks/import/openapi` ### Request Body - **openApiJson** (string) - Required - The OpenAPI 3.0 specification in JSON format. ### Request Example ```http POST /_admin/mocks/import/openapi Content-Type: application/json { "openApiJson": "{ ... OpenAPI 3.0 spec ... }" } ``` ### Response Example ```json { "message": "Successfully imported 12 mock response(s) from OpenAPI specification.", "importedCount": 12, "mocks": [ ... ] } ``` ``` -------------------------------- ### Create Mock with Route Parameters Source: https://context7.com/burgan-tech/mocklab/llms.txt Define a mock endpoint that uses path parameters for dynamic responses. ```bash curl -X POST "http://localhost:5000/_admin/mocks" \ -H "Content-Type: application/json" \ -d '{ "httpMethod": "GET", "route": "/api/users/{id}", "statusCode": 200, "responseBody": "{\"id\": \"{{ request.route.id }}\", \"name\": \"User {{ request.route.id }}\", \"email\": \"user{{ request.route.id }}@example.com\"}", "contentType": "application/json", "description": "Get user by ID", "isActive": true }' # Test with different IDs curl "http://localhost:5000/mock/api/users/123" # Returns: {"id": "123", "name": "User 123", "email": "user123@example.com"} curl "http://localhost:5000/mock/api/users/456" # Returns: {"id": "456", "name": "User 456", "email": "user456@example.com"} ``` -------------------------------- ### Request Echo and JSON Body Parsing Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Shows how to echo request details like method, path, and headers, and how to parse the request body as JSON. ```json { "echo": { "method": "{{ request.method }}", "path": "{{ request.path }}", "userId": "{{ request.route.id }}", "auth": "{{ request.headers["Authorization"] }}" }, "requestId": "{{ helpers.guid() }}", "bodyParsed": {{ request.json }} } ``` -------------------------------- ### Import Mocks from cURL Source: https://context7.com/burgan-tech/mocklab/llms.txt Generate a mock by submitting a cURL command string to the import endpoint. ```bash curl -X POST "http://localhost:5000/_admin/mocks/import/curl" \ -H "Content-Type: application/json" \ -d '{ "curl": "curl -X GET https://api.example.com/users -H \'Accept: application/json\' -H \'Authorization: Bearer token123\'" }' ``` -------------------------------- ### Create Mock with Sequential Responses for Retry Testing Source: https://context7.com/burgan-tech/mocklab/llms.txt Configure a mock to cycle through a predefined sequence of responses. This is ideal for simulating transient errors like 500 or 503, followed by a successful response, to test retry mechanisms. ```bash curl -X POST "http://localhost:5000/_admin/mocks" \ -H "Content-Type: application/json" \ -d '{ "httpMethod": "POST", "route": "/api/orders", "statusCode": 200, "responseBody": "{}", "contentType": "application/json", "description": "Order endpoint with retry simulation", "isActive": true, "isSequential": true, "sequenceItems": [ { "order": 0, "statusCode": 500, "responseBody": "{\"error\": \"Internal Server Error\"}", "contentType": "application/json" }, { "order": 1, "statusCode": 503, "responseBody": "{\"error\": \"Service Unavailable\", \"retryAfter\": 1}", "contentType": "application/json" }, { "order": 2, "statusCode": 200, "responseBody": "{\"orderId\": \"ORD-{{ helpers.guid() }}\", \"status\": \"created\"}", "contentType": "application/json" } ] }' ``` -------------------------------- ### List Collections Source: https://context7.com/burgan-tech/mocklab/llms.txt Retrieve a list of all available collections. Optionally, include mock counts or folder structures for UI representation. ```bash curl "http://localhost:5000/_admin/collections" ``` ```bash curl "http://localhost:5000/_admin/collections?includeFolders=true" ``` -------------------------------- ### Standalone SQLite Configuration Source: https://github.com/burgan-tech/mocklab/blob/master/docs/integration.md Configure Mocklab to use a standalone SQLite database. This is the default mode and does not require an external database. ```csharp builder.Services.AddMocklab(options => { options.UseHostDatabase = false; options.ConnectionString = "Data Source=mocklab.db"; }); ``` -------------------------------- ### Create a Mock Collection Source: https://context7.com/burgan-tech/mocklab/llms.txt Group related mocks into collections for better organization. Collections can be named, described, and assigned a color. Ensure the Content-Type header is set to application/json. ```bash curl -X POST "http://localhost:5000/_admin/collections" \ -H "Content-Type: application/json" \ -d '{ "name": "Payment APIs", "description": "All payment-related endpoints", "color": "#6366f1" }' ``` -------------------------------- ### Import Collection with Mocks Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Import a collection and its associated mocks in a single API request. Ensure the request body includes both the collection details and a list of mocks. ```http POST /_admin/collections/import Content-Type: application/json { "collection": { "name": "User APIs", "description": "User management endpoints", "color": "#22c55e" }, "mocks": [ { "httpMethod": "GET", "route": "/api/users/profile", "statusCode": 200, "responseBody": "{\"id\": 1, \"name\": \"Mehmet\"}", "contentType": "application/json", "description": "User profile", "isActive": true } ] } ``` -------------------------------- ### Register Mocklab in ASP.NET Core Source: https://github.com/burgan-tech/mocklab/blob/master/README.md Basic registration of Mocklab services and middleware in an ASP.NET Core application. ```csharp builder.Services.AddMocklab(); app.UseMocklab(); ``` -------------------------------- ### Host Database Configuration - PostgreSQL Source: https://github.com/burgan-tech/mocklab/blob/master/docs/integration.md Configure Mocklab to use the host application's PostgreSQL database with a separate schema. Ensure your connection string is set in appsettings.json. ```json { "ConnectionStrings": { "DefaultConnection": "Host=localhost;Port=5432;Database=myapp;Username=myuser;Password=mypassword" }, "Mocklab": { "UseHostDatabase": true, "DatabaseProvider": "postgresql", "SchemaName": "mocklab" } } ``` -------------------------------- ### Host Database Configuration - SQL Server Source: https://github.com/burgan-tech/mocklab/blob/master/docs/integration.md Configure Mocklab to use the host application's SQL Server database with a separate schema. Ensure your connection string is set in appsettings.json. ```json { "ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=MyApp;Trusted_Connection=True;TrustServerCertificate=True" }, "Mocklab": { "UseHostDatabase": true, "DatabaseProvider": "sqlserver", "SchemaName": "mocklab" } } ``` -------------------------------- ### Simulate Response Delays Source: https://context7.com/burgan-tech/mocklab/llms.txt Simulate network latency using fixed delays or sequential steps with varying delay times. ```bash # Mock with fixed delay curl -X POST "http://localhost:5000/_admin/mocks" \ -H "Content-Type: application/json" \ -d '{ "httpMethod": "GET", "route": "/api/reports/heavy", "statusCode": 200, "responseBody": "{\"report\": \"data\", \"generatedAt\": \"{{ iso_timestamp }}\"}", "contentType": "application/json", "description": "Slow report endpoint", "delayMs": 3000, "isActive": true }' # Response arrives after ~3 seconds curl "http://localhost:5000/mock/api/reports/heavy" # Sequence with varying delays per step curl -X POST "http://localhost:5000/_admin/mocks" \ -H "Content-Type: application/json" \ -d '{ "httpMethod": "GET", "route": "/api/status", "statusCode": 200, "responseBody": "{}", "contentType": "application/json", "isSequential": true, "isActive": true, "sequenceItems": [ {"order": 0, "statusCode": 200, "responseBody": "{\"status\": \"fast\"}", "contentType": "application/json", "delayMs": 100}, {"order": 1, "statusCode": 200, "responseBody": "{\"status\": \"slow\"}", "contentType": "application/json", "delayMs": 2000}, {"order": 2, "statusCode": 200, "responseBody": "{\"status\": \"very slow\"}", "contentType": "application/json", "delayMs": 5000} ] }' ``` -------------------------------- ### Import Mocks from OpenAPI/Swagger Specification Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Enables importing multiple mock responses by providing an OpenAPI JSON specification. MockLab generates mocks for each defined endpoint. ```http POST /_admin/mocks/import/openapi Content-Type: application/json { "openApiJson": "{ ... OpenAPI 3.0 spec ... }" } ``` -------------------------------- ### Create Mock with Conditional Rules Source: https://context7.com/burgan-tech/mocklab/llms.txt Define a mock that returns different responses based on request conditions like headers, body, query parameters, or HTTP method. Multiple rules can be defined with priorities. ```bash curl -X POST "http://localhost:5000/_admin/mocks" \ -H "Content-Type: application/json" \ -d '{ "httpMethod": "GET", "route": "/api/secure-data", "statusCode": 200, "responseBody": "{\"data\": \"secret information\"}", "contentType": "application/json", "description": "Secure endpoint with auth rules", "isActive": true, "rules": [ { "conditionField": "header.Authorization", "conditionOperator": "notExists", "conditionValue": null, "statusCode": 401, "responseBody": "{\"error\": \"Token required\"}", "contentType": "application/json", "priority": 0 }, { "conditionField": "header.Authorization", "conditionOperator": "equals", "conditionValue": "Bearer expired", "statusCode": 403, "responseBody": "{\"error\": \"Token expired\"}", "contentType": "application/json", "priority": 1 } ] }' ``` -------------------------------- ### Import Collection Source: https://context7.com/burgan-tech/mocklab/llms.txt Imports a collection, including its mocks, into the MockLab system. ```APIDOC ## Import Collection ### Description Import a collection into MockLab. ### Method POST ### Endpoint `/_admin/collections/import` ### Request Body - **collection** (object) - Required - Details of the collection to import (name, description, color). - **mocks** (array) - Optional - An array of mock objects to import with the collection. ### Request Example ```json { "collection": { "name": "User APIs", "description": "User management endpoints", "color": "#22c55e" }, "mocks": [ { "httpMethod": "GET", "route": "/api/users/profile", "statusCode": 200, "responseBody": "{\"id\": 1, \"name\": \"John\"}", "contentType": "application/json", "isActive": true } ] } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of the import. - **collectionId** (integer) - The ID of the imported collection. - **importedCount** (integer) - The number of mocks imported. ``` -------------------------------- ### POST /_admin/collections Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Create a new collection to group related mocks. ```APIDOC ## POST /_admin/collections ### Description Create a new collection for organizing mocks. ### Method POST ### Endpoint /_admin/collections ### Request Body - **name** (string) - Required - Name of the collection - **description** (string) - Optional - Description of the collection - **color** (string) - Optional - Hex color code for UI identification ### Request Example { "name": "Payment APIs", "description": "All payment-related endpoints", "color": "#6366f1" } ``` -------------------------------- ### Import a Collection Source: https://context7.com/burgan-tech/mocklab/llms.txt Import a collection, along with its mocks, from a JSON payload. The response includes a success message, the new collection ID, and the count of imported mocks. Ensure the Content-Type header is set to application/json. ```bash curl -X POST "http://localhost:5000/_admin/collections/import" \ -H "Content-Type: application/json" \ -d '{ "collection": { "name": "User APIs", "description": "User management endpoints", "color": "#22c55e" }, "mocks": [ { "httpMethod": "GET", "route": "/api/users/profile", "statusCode": 200, "responseBody": "{\"id\": 1, \"name\": \"John\"}", "contentType": "application/json", "isActive": true } ] }' ``` -------------------------------- ### Create Collection Source: https://context7.com/burgan-tech/mocklab/llms.txt Groups related mocks into collections, which can be color-coded. ```APIDOC ## Create a Collection ### Description Group related mocks into color-coded collections. ### Method POST ### Endpoint `/_admin/collections` ### Request Body - **name** (string) - Required - The name of the collection. - **description** (string) - Optional - A description for the collection. - **color** (string) - Optional - A hex color code for the collection (e.g., "#6366f1"). ### Request Example ```json { "name": "Payment APIs", "description": "All payment-related endpoints", "color": "#6366f1" } ``` ### Response #### Success Response (201 Created) - **id** (integer) - The ID of the newly created collection. - **name** (string) - The name of the collection. - **description** (string) - The description of the collection. - **color** (string) - The color code of the collection. - **createdAt** (string) - The timestamp when the collection was created. ``` -------------------------------- ### Create a New Collection Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Use this HTTP POST request to create a new collection. Include the collection's name, an optional description, and an optional color in the request body. ```http POST /_admin/collections Content-Type: application/json { "name": "Payment APIs", "description": "All payment-related endpoints", "color": "#6366f1" } ``` -------------------------------- ### Test Dynamic Template Variables Source: https://context7.com/burgan-tech/mocklab/llms.txt Send a request to a mock endpoint configured with Scriban templates to verify that dynamic values are generated correctly. Each request should yield a unique set of user details. ```bash # Each request returns unique values curl "http://localhost:5000/mock/api/users/random" ``` -------------------------------- ### List and Filter Mocks Source: https://context7.com/burgan-tech/mocklab/llms.txt Retrieve a list of mocks with optional filtering parameters. ```bash # List all mocks curl "http://localhost:5000/_admin/mocks" # List only active mocks curl "http://localhost:5000/_admin/mocks?isActive=true" ``` -------------------------------- ### Toggle Mock Active/Inactive Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Illustrates how to toggle the active status of a mock using an HTTP PATCH request. ```http PATCH /_admin/mocks/1/toggle ``` -------------------------------- ### Log Entry Model Structure Source: https://github.com/burgan-tech/mocklab/blob/master/docs/api-reference.md Defines the structure of a log entry, detailing information about incoming requests and how they were handled by MockLab. ```json { "id": 49, "httpMethod": "GET", "route": "/api/users/random", "queryString": null, "requestBody": null, "requestHeaders": "{\"Accept\":\"*/*\",\"Host\":\"localhost:5000\"}", "matchedMockId": 22, "matchedMockDescription": "Dynamic user", "responseStatusCode": 200, "isMatched": true, "timestamp": "2026-02-19T08:10:32.078Z", "responseTimeMs": 45 } ``` -------------------------------- ### Test Body-Based Conditional Rules Source: https://context7.com/burgan-tech/mocklab/llms.txt Send requests to a mock endpoint configured with conditional rules to test different scenarios. This demonstrates how the mock responds to normal, high-amount, and unsupported currency requests. ```bash # Normal payment - 200 approved curl -X POST "http://localhost:5000/mock/api/payments" \ -H "Content-Type: application/json" \ -d '{"amount": 500, "currency": "USD"}' ``` ```bash # High amount - 400 limit exceeded curl -X POST "http://localhost:5000/mock/api/payments" \ -H "Content-Type: application/json" \ -d '{"amount": 15000, "currency": "USD"}' ``` ```bash # Unsupported currency - 422 curl -X POST "http://localhost:5000/mock/api/payments" \ -H "Content-Type: application/json" \ -d '{"amount": 100, "currency": "BTC"}' ```