A lightweight, fast, feature complete echo service with many nice tools included
3.6K
Leywn is an all-in-one demo/test backend for APIs and HTTP services. It gives you a single deployable service that echoes requests, enforces every common authentication scheme, returns arbitrary HTTP status codes, generates random data, serves mock REST APIs from plain JSON files, and hosts a live Swagger UI — so you can test clients, proxies, load balancers, and API gateways without standing up any real backend.
docker run -p 4000:4000 -p 4443:4443 svenwal/leywn:latest
Open http://localhost:4000 in your browser for the Swagger UI.
Pull and run the latest image:
docker run -p 4000:4000 -p 4443:4443 svenwal/leywn:latest
Build from source:
git clone https://github.com/svenwal/leywn.git
cd leywn/Leywn/leywn
docker build -t leywn .
docker run -p 4000:4000 -p 4443:4443 leywn
Port 4000 serves plain HTTP. Port 4443 serves HTTPS with a self-signed server certificate and mTLS support (client certificate optional except on /auth/mtls).
The image uses a multi-stage build on an Alpine base: only the compiled OTP release is included in the final layer — no Mix, Hex, or source code at runtime (~38 MB). It runs as a non-root user (UID 1001, GID 0) and is compatible with OpenShift's arbitrary-UID injection.
Create a docker-compose.yml:
services:
leywn:
image: svenwal/leywn:latest
ports:
- "4000:4000"
- "4443:4443"
environment:
LEYWN_PORT: 4000
LEYWN_TLS_PORT: 4443
LEYWN_ECHO_MAX_BODY_BYTES: 65536
Then:
docker compose up
Prerequisites: Elixir 1.18+ and Erlang/OTP 27+.
git clone https://github.com/svenwal/leywn.git
cd leywn/Leywn/leywn
mix deps.get
mix run --no-halt
The server starts on http://localhost:4000 and https://localhost:4443.
All settings are controlled through environment variables.
| Variable | Default | Description |
|---|---|---|
LEYWN_PORT | 4000 | HTTP listen port |
LEYWN_TLS_PORT | 4443 | HTTPS / mTLS listen port |
LEYWN_ECHO_MAX_BODY_BYTES | 65536 | Maximum request body size echoed back (64 KB) |
LEYWN_ECHO_ON_HOME | (unset) | When set to true, serve echo output on / instead of the HTML home page |
LEYWN_MTLS_IN_HEADER | (unset) | When set to a header name, read the client certificate PEM from that header instead of the TLS handshake (see proxy mode) |
LEYWN_TLS_SERVER_CRT | (unset) | PEM-encoded server certificate for the HTTPS listener; if set together with LEYWN_TLS_SERVER_KEY, used instead of the auto-generated one (expired → warning, invalid → error) |
LEYWN_TLS_SERVER_KEY | (unset) | PEM-encoded private key matching LEYWN_TLS_SERVER_CRT |
LEYWN_MTLS_CERT | (unset) | PEM-encoded client certificate (and optional CA chain) to use instead of the auto-generated one; served at /auth/mtls/get-client-cert and automatically trusted by the mTLS listener |
LEYWN_MTLS_KEY | (unset) | PEM-encoded private key matching LEYWN_MTLS_CERT |
LEYWN_TRUST_FORWARD | (unset) | When set to true, derive the caller IP from the X-Forwarded-For header instead of the socket address |
LEYWN_ONLY_JSON | (unset) | When set to true, disable XML content negotiation and always return JSON regardless of the Accept header |
LEYWN_CORS_ORIGIN | * | Value of the Access-Control-Allow-Origin response header. When set to a specific origin, Vary: Origin is sent as well |
LEYWN_EXTERNAL_HTTP_URL | (unset) | Public HTTP base URL when running behind a reverse proxy; used in the OpenAPI servers list and the Insomnia collection |
LEYWN_EXTERNAL_HTTPS_URL | (unset) | Public HTTPS base URL when running behind a reverse proxy; preferred over the HTTP one |
LEYWN_NAMES_FILE | priv/names.txt | Path to the name list backing /random/name and /random/email (one name per line, # comments allowed) |
LEYWN_EMAIL_DOMAINS_FILE | priv/email_domains.txt | Path to the domain list backing /random/email (one domain per line) |
LEYWN_TLS_SERVER_CRT and LEYWN_TLS_SERVER_KEY must be set together — setting
only one aborts startup rather than silently falling back to a generated
certificate. The name and domain files are read once at first use and cached, so
replacing them requires a restart.
The mock endpoints are the only part of Leywn that accepts writes and keeps state between requests, so they carry their own limits. The defaults are sized for a demo backend: enough room to show a CRUD flow, not enough to store a workload. See /mocks for what they do in practice.
| Variable | Default | Description |
|---|---|---|
LEYWN_MOCKS_DIR | priv/mocks | Directory scanned at startup; each subfolder becomes one mock |
LEYWN_MOCK_READONLY | (unset) | When set to true, only GET is served and no state is ever created |
LEYWN_MOCK_ENTRY_TTL_SECONDS | 300 | Seconds after which a written record — or a deletion — is forgotten |
LEYWN_MOCK_MAX_NEW_ENTRIES | 100 | Maximum changes held per mock; further writes return 507 |
LEYWN_MOCK_MAX_OVERLAY_BYTES | 1048576 | Total bytes of held changes across all mocks (1 MiB) |
LEYWN_MOCK_WRITE_RATE_LIMIT | 60 | Mutating requests per minute, per client IP |
LEYWN_MOCK_WRITE_RATE_LIMIT_GLOBAL | 600 | Mutating requests per minute across all clients |
LEYWN_MOCK_RATE_BUCKETS | 10000 | Per-IP rate-limit rows tracked before falling back to the global budget alone |
LEYWN_MOCK_MAX_BODY_BYTES | 16384 | Maximum body accepted by a mutating mock request (16 KB) |
LEYWN_MOCK_MAX_DEPTH | 16 | Maximum nesting depth of a write body |
LEYWN_MOCK_MAX_KEYS | 100 | Maximum keys in any single object of a write body |
LEYWN_MOCK_MAX_PAGE_SIZE | 200 | Maximum records returned by one collection read |
LEYWN_MOCK_MAX_FILTERS | 10 | Maximum query parameters honoured as field filters |
LEYWN_MOCK_MAX_FILE_BYTES | 8388608 | Maximum size of a mock's JSON file (8 MiB); larger files are skipped with a warning |
LEYWN_MOCK_MAX_MOCKS | 50 | Maximum number of mocks loaded from the directory |
LEYWN_MOCK_MAX_COLLECTIONS | 100 | Maximum collections within a single mock |
Example with custom ports:
docker run -e LEYWN_PORT=8080 -e LEYWN_TLS_PORT=8443 -p 8080:8080 -p 8443:8443 leywn
All endpoints support JSON (default) and XML responses via content negotiation — see Content negotiation.
GET / # home page with embedded Swagger UI
GET /docs # alias for /
GET /openapi.json # the OpenAPI 3.0 specification
GET /request-collection # Insomnia v4 collection covering every endpoint
Serves an HTML page with a Swagger UI loaded from /openapi.json. Use it to explore and try every endpoint interactively.
open http://localhost:4000
/openapi.json lists the origin the page was loaded from as its first server entry, so "Try it out" always calls back to the same host — plus any LEYWN_EXTERNAL_* URLs you configure. /request-collection is served as a download and its base_url environment variable is derived the same way.
Set LEYWN_ECHO_ON_HOME=true to serve echo output on / instead of the HTML page.
GET /health
Returns server status, version, and uptime. Suitable for use as a Kubernetes liveness/readiness probe.
curl http://localhost:4000/health
# {"status":"ok","version":"1.1.0-beta2","uptime_seconds":42}
ANY /echo
ANY /echo/{*path}
Returns every detail of the incoming request: method, scheme, host, port, path, query parameters, headers, remote IP, and body (if text/UTF-8 and within the size limit).
# Basic GET
curl http://localhost:4000/echo
# POST with body and query params
curl -X POST "http://localhost:4000/echo/foo/bar?hello=world" \
-H "Content-Type: application/json" \
-d '{"message": "test"}'
Example response:
{
"method": "POST",
"scheme": "http",
"host": "localhost",
"port": 4000,
"path": "/echo/foo/bar",
"path_info": ["foo", "bar"],
"query_string": "hello=world",
"query_params": { "hello": "world" },
"headers": {
"content-type": "application/json",
"host": "localhost:4000"
},
"remote_ip": "127.0.0.1",
"body": {
"present": true,
"bytes": 18,
"truncated": false,
"utf8": true,
"included": true,
"body": "{\"message\": \"test\"}"
},
"timestamp_unix_ms": 1700000000000
}
A header sent once is reported as a plain string; only a header that genuinely appears more than once becomes an array.
Bodies larger than LEYWN_ECHO_MAX_BODY_BYTES are acknowledged but not included (truncated: true). Binary bodies are detected and excluded (utf8: false, included: false).
ANY /anything
ANY /anything/{*path}
Identical to /echo. Provided as a convenience alias familiar to users of similar tools.
curl -X DELETE http://localhost:4000/anything/some/path
ANY /status/{code}
Responds with the exact HTTP status code you specify (100–599).
{"status": <code>}# Trigger a 418 I'm a teapot
curl -i http://localhost:4000/status/418
# Test how your client handles 503
curl -i http://localhost:4000/status/503
# Test redirects
curl -iL http://localhost:4000/status/301
ANY /delay/{ms}
Delays the response by the requested number of milliseconds (0–30 000). Useful for testing timeouts, retry logic, and client-side loading states.
# Delay by 2 seconds
curl http://localhost:4000/delay/2000
# {"requested_ms":2000,"delayed_ms":2000}
# Over the 30-second limit → 400
curl -i http://localhost:4000/delay/60000
GET /stream/{n}
Streams n newline-delimited JSON objects (NDJSON) as chunked transfer encoding, one line per chunk (max 100). Each object contains line, total, and timestamp_unix_ms.
curl http://localhost:4000/stream/5
# {"line":1,"total":5,"timestamp_unix_ms":...}
# {"line":2,"total":5,"timestamp_unix_ms":...}
# ...
ANY /chaos-engineering
ANY /chaos-engineering/{error_pct}/{mangled_pct}/{latency_pct}/{max_latency_ms}
Returns an echo response but randomly injects faults — useful for testing resilience and circuit-breaker logic.
| Fault | What happens |
|---|---|
| Error | A random 4xx/5xx status code is returned |
| Mangled | Response is truncated mid-stream so JSON is syntactically invalid |
| Latency | A random delay up to max_latency_ms is added |
Path parameters (all integers, 0–100 for percentages, 0–30000 for max latency):
# 10% errors, 10% mangled, 20% latency up to 2 s (same as defaults)
curl http://localhost:4000/chaos-engineering/10/10/20/2000
Header-based configuration (percentages as X-Chaos-* headers, falls back to defaults):
curl http://localhost:4000/chaos-engineering \
-H "X-Chaos-Error-Percentage: 50" \
-H "X-Chaos-Maximum-Latency: 500"
Every response includes a _chaos field with the applied parameters and actual latency introduced.
Default credentials (basic / password):
ANY /auth/basic-auth
# Correct credentials
curl -u basic:password http://localhost:4000/auth/basic-auth
# Wrong credentials → 401
curl -u wrong:credentials http://localhost:4000/auth/basic-auth
# No credentials → 401 with WWW-Authenticate header
curl -i http://localhost:4000/auth/basic-auth
Custom credentials in the URL path:
ANY /auth/basic-auth/{username}/{password}
curl -u alice:secret http://localhost:4000/auth/basic-auth/alice/secret
Success response includes authenticated: true, auth_type: "basic-auth", username, plus the full echo payload.
Default (header apikey: my-key):
ANY /auth/api-key
# Correct key
curl -H "apikey: my-key" http://localhost:4000/auth/api-key
# Wrong key → 401
curl -H "apikey: wrong" http://localhost:4000/auth/api-key
Custom header name and value:
ANY /auth/api-key/{header_name}/{key_value}
curl -H "X-Api-Token: supersecret" \
http://localhost:4000/auth/api-key/X-Api-Token/supersecret
ANY /auth/jwt
Validates the structure of a JWT in the Authorization: Bearer <token> header. The signature is not verified — this endpoint validates format and decodes header/claims, making it useful for testing token generation and parsing.
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIiwibmFtZSI6IkFsaWNlIn0.signature"
curl -H "Authorization: Bearer $TOKEN" http://localhost:4000/auth/jwt
Success response includes the decoded jwt_header and claims maps alongside the echo payload.
{
"authenticated": true,
"auth_type": "jwt",
"jwt_header": { "alg": "HS256", "typ": "JWT" },
"claims": { "sub": "user123", "name": "Alice" },
"method": "GET",
...
}
ANY /auth/jwt/exchange
Validates the incoming Authorization: Bearer <token> JWT (structure only, signature not verified), then issues a new HS256-signed token with the original claims merged with iss: "leywn", iat (issued-at), and a fresh jti (JWT ID).
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIn0.signature"
curl -H "Authorization: Bearer $TOKEN" http://localhost:4000/auth/jwt/exchange
Success response includes exchanged_token (the new signed JWT) and the updated claims alongside the echo payload:
{
"authenticated": true,
"auth_type": "jwt",
"exchanged_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"claims": { "sub": "user123", "iss": "leywn", "iat": 1700000000, "jti": "..." },
"method": "POST",
...
}
ANY /auth/mtls (HTTPS port 4443 only, or header mode on any port)
GET /auth/mtls/get-client-cert
A fresh CA, server certificate, and client certificate are generated on every startup and kept in memory. The /auth/mtls endpoint validates that the caller presents a certificate signed by that CA.
To use your own client certificate instead of the generated one, set LEYWN_MTLS_CERT (PEM, optionally a full chain) and LEYWN_MTLS_KEY. Leywn will serve those at /auth/mtls/get-client-cert and automatically add the cert's issuing CA to its trusted list.
Use the HTTPS port with the generated client certificate:
# Step 1: download the client certificate and key
curl -k https://localhost:4443/auth/mtls/get-client-cert \
| python3 -c "
import sys, json
d = json.load(sys.stdin)
open('client.pem','w').write(d['cert_pem'])
open('client.key','w').write(d['key_pem'])
print('saved client.pem and client.key')
"
# Step 2: call /auth/mtls with the client cert
curl -k --cert client.pem --key client.key https://localhost:4443/auth/mtls
Success response includes client_dn and client_ca extracted from the certificate:
{
"authenticated": true,
"auth_type": "mtls",
"client_dn": "CN=Leywn Demo Client",
"client_ca": "CN=Leywn Demo CA",
...
}
When a TLS-terminating proxy (e.g. Nginx, AWS ALB, Envoy) handles the TLS handshake and forwards the client certificate in a header, set LEYWN_MTLS_IN_HEADER to the header name:
docker run -e LEYWN_MTLS_IN_HEADER=X-Client-Cert -p 4000:4000 leywn
Leywn will then read the PEM certificate from that header (URL-encoded is accepted) instead of the TLS peer data:
# URL-encode the PEM and pass it in the configured header
CERT=$(python3 -c "import urllib.parse; print(urllib.parse.quote(open('client.pem').read()))")
curl http://localhost:4000/auth/mtls -H "X-Client-Cert: $CERT"
GET /uuid
Returns a randomly generated UUID v4.
curl http://localhost:4000/uuid
# {"uuid":"6986f945-a01e-4ffd-aff8-a15648be7946"}
GET /guuid
Returns a UUID v4 wrapped in curly braces, in the Windows GUID format.
curl http://localhost:4000/guuid
# {"guuid":"{d3afb989-99bf-49b2-9cd6-820c039a1e6f}"}
GET /image/png
GET /image/jpeg (jpg is accepted as alias)
GET /image/gif
GET /image/svg # dynamic SVG with Leywn branding
GET /image/webp # PNG re-encoded as WebP (generated at build time)
An unknown type returns 400 (unsupported_image_type); a known type whose file is not present returns 404 (image_not_available).
curl -o logo.png http://localhost:4000/image/png
curl -o logo.svg http://localhost:4000/image/svg
GET /image/color/{rgb} # 64×64 PNG
GET /image/color/{rgb}/{width}/{height} # custom size, max 4096×4096
{rgb} accepts 3-char (f00), 6-char (ff0000), or 8-char RGBA (ff0000cc) hex strings.
curl -o red.png http://localhost:4000/image/color/ff0000
curl -o blue.png http://localhost:4000/image/color/0000ff/200/100
GET /random
Returns one sample of every random type in a single response.
curl http://localhost:4000/random
GET /random/int # range: -32000 to 32000
GET /random/int/{lower}/{upper} # custom range (inclusive)
curl http://localhost:4000/random/int
# {"value": -14203}
curl http://localhost:4000/random/int/1/6
# {"value": 4} (simulates a dice roll)
curl http://localhost:4000/random/int/-1000000/1000000
GET /random/uint # range: 0 to 65535
curl http://localhost:4000/random/uint
# {"value": 42817}
GET /random/lorem-ipsum # one paragraph
GET /random/lorem-ipsum/{n} # n paragraphs, max 32
The first paragraph always opens with the classic sentence. Subsequent paragraphs are generated from a word pool, so each response is unique.
curl http://localhost:4000/random/lorem-ipsum
curl http://localhost:4000/random/lorem-ipsum/5
GET /random/name # random first name
GET /random/email # random email address
GET /random/color # random RGB colour
Names and email domains are drawn from priv/names.txt and priv/email_domains.txt. Mount your own files and point LEYWN_NAMES_FILE / LEYWN_EMAIL_DOMAINS_FILE at them to customise the output.
curl http://localhost:4000/random/name
# {"name":"Alice"}
curl http://localhost:4000/random/email
# {"email":"[email protected]"}
curl http://localhost:4000/random/color
# {"hex":"#3a7fc1","r":58,"g":127,"b":193}
GET /ip # both IPv4 and IPv6
GET /ip/v4 # IPv4 only
GET /ip/v6 # IPv6 only
Returns the caller's IP address(es). When LEYWN_TRUST_FORWARD=true is set, the first value from the X-Forwarded-For header is used instead of the socket address (useful behind a proxy or load balancer).
curl http://localhost:4000/ip
# {"ipv4":"127.0.0.1","ipv6":null}
curl http://localhost:4000/ip/v4
# {"ipv4":"127.0.0.1"}
curl http://localhost:4000/ip/v6
# {"ipv6":null}
GET /date # UTC
GET /date/{timezone} # any IANA timezone, e.g. America/New_York
Returns the current date in ISO 8601 format. Unknown timezones return HTTP 404.
curl http://localhost:4000/date
# {"date":"2026-04-01","timezone":"UTC"}
curl http://localhost:4000/date/Europe/Berlin
# {"date":"2026-04-01","timezone":"Europe/Berlin"}
# Unknown timezone → 404
curl -i http://localhost:4000/date/Invalid/Zone
POST /format/json # pretty-print a JSON body
POST /format/yaml # re-indent a YAML body
POST /format/xml # re-indent an XML body
POST /format/camelCase # convert the body text to camelCase
POST /format/kebab-case # convert the body text to kebab-case
POST /format/snake_case # convert the body text to snake_case
POST /format/toUpper # uppercase the body text
POST /format/toLower # lowercase the body text
POST /format/collapse-lines # collapse multiple blank lines into one
All format endpoints accept a POST body (limited to LEYWN_ECHO_MAX_BODY_BYTES). The three structured endpoints — json, yaml and xml — re-format input of their own type and return 422 if it does not parse. The case and text endpoints operate on the raw body as plain text and return text/plain.
# Pretty-print JSON
curl -s -X POST http://localhost:4000/format/json \
-H "Content-Type: application/json" \
-d '{"b":2,"a":1}'
# Re-indent YAML with consistent 2-space indentation
curl -s -X POST http://localhost:4000/format/yaml \
-H "Content-Type: text/plain" \
--data-binary $'person:\n name: Bob\n age: 25'
# Re-indent XML and add a declaration header
curl -s -X POST http://localhost:4000/format/xml \
-H "Content-Type: text/plain" \
-d '<root><child><name>Alice</name></child></root>'
# Convert text between naming conventions
curl -s -X POST http://localhost:4000/format/snake_case -d 'myVariableName'
# my_variable_name
curl -s -X POST http://localhost:4000/format/camelCase -d 'my_variable_name'
# myVariableName
POST /encode/base64 POST /decode/base64
POST /encode/url POST /decode/url
POST /encode/hex POST /decode/hex
POST /encode/rot13 POST /decode/rot13
POST /decode/jwt # decode JWT header + payload (no sig verification)
curl -s -X POST http://localhost:4000/encode/base64 -d "hell
Content type
Image
Digest
sha256:1cd2a66eb…
Size
15.9 MB
Last updated
about 2 months ago
docker pull svenwal/leywn