Personal example and learning exercise for an Axum REST API.
Features:
- OpenAPI documentation using utoipa with Swagger UI, Redoc, RapiDoc, Scalar,
embedded Markdown descriptions (
docs/openapi/), and an explicit/api-docs/openapi.jsonroute - API key authentication for admin routes with a custom extractor
- Typed
ApiErrorthat renders every failure (including404and405) as the same JSON error body - Typed runtime configuration from environment variables with startup validation and redacted errors
- Structured
/healthand detailed/statusendpoints usingjiffRFC 3339 timestamps - Sliding-window per-client rate limiting with bounded client buckets and standard
RateLimit-*/Retry-Afterheaders - Request ID propagation, configurable
prettyorjsonlogs (LOG_FORMAT), and structured completion logs - OpenTelemetry HTTP metrics with per-route in-flight gauges, cancellation tracking, bounded route/method labels,
optional OTLP export, and Prometheus
/metricsscraping - Embedded Model Context Protocol server at
/mcpwith tool annotations - Library and binary split with integration (
tests/), CLI subprocess (tests/cli.rs), property (proptest), fuzz (fuzz/), and mutation (cargo-mutants) test suites - Strict Clippy lints,
unsafe_code = "forbid", andmissing_docs = "warn"
Usage:
Axum API example
Usage: axum-example [OPTIONS]
Options:
-H, --host <IP> Optional host IP to listen on (for example "0.0.0.0") [env: HOST=]
-l, --log <LEVEL> Log level to use [default: info] [possible values: trace, debug, info, warn, error]
--log-format <FORMAT> Log output format ("pretty" or "json") [env: LOG_FORMAT=] [possible values: pretty, json]
-p, --port <PORT> TCP port number to listen on [env: PORT=] [default: 3000]
-v, --version Print version info and exit
-h, --help Print help (see more with '--help')Run locally:
cargo run --locked --release
# Specify log level and format
cargo run --locked --release -- --log debug --log-format json
# Log level and format from env
RUST_LOG=debug LOG_FORMAT=pretty cargo run --locked --releaseBuild Docker image and run container on host loopback (http://127.0.0.1:8080):
./docker-run.shRuntime configuration is read from environment variables at startup. Invalid values stop the server with a descriptive, redacted error instead of falling back silently.
| Variable | Default | Description |
|---|---|---|
HOST |
127.0.0.1 |
Listen address, same as --host. |
PORT |
3000 |
Listen port, same as --port. |
API_ENV |
local |
Runtime environment. production hides doc UIs and OpenAPI JSON. |
LOG_FORMAT |
env-dependent | pretty (default in local) or json (default elsewhere). |
API_KEY |
axum-api-key |
API key required by the /admin routes. |
RATE_LIMIT_REQUESTS |
300 |
Maximum requests per client in one window. |
RATE_LIMIT_WINDOW_SECONDS |
60 |
Sliding window length in seconds. |
RATE_LIMIT_DISABLED |
false |
Set to true to turn rate limiting off. |
REQUEST_TIMEOUT_SECONDS |
10 |
Timeout applied to every request. |
OTEL_EXPORTER_OTLP_ENDPOINT |
unset | Enables OTLP metric export when non-blank. |
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT |
unset | Enables OTLP metric export with a metrics-specific endpoint. |
| Method | Path | Description |
|---|---|---|
GET |
/ |
Service name and current UTC timestamp. |
GET |
/health |
Overall health, version, and uptime. |
GET |
/status |
Individual checks, request counters, config, and env var names. |
GET |
/version |
Build metadata. |
GET |
/metrics |
Prometheus text metrics. |
GET |
/api-docs/openapi.json |
Generated OpenAPI 3.1 JSON document (hidden in production). |
GET |
/item?name=... |
Look up one item by name. |
GET |
/items |
List items with optional skip and limit. |
POST |
/items |
Create an item. |
GET |
/items/{name} |
Get one item. |
PUT |
/items/{name} |
Update an item. |
DELETE |
/admin/remove/{name} |
Remove an item, requires the api-key header. |
DELETE |
/admin/clear_items |
Remove all items, requires the api-key header. |
POST |
/mcp |
Model Context Protocol endpoint. |
Errors (including unknown paths 404 and unsupported methods 405) use one JSON shape across all routes:
{ "error": "Not Found", "message": "Item does not exist: missing" }Start the server first and then in another terminal:
./test-routes.sh --timingEvery route except /health and /metrics is limited per client with a sliding window
and a bounded in-memory bucket table (MAX_CLIENT_BUCKETS).
The client is identified by the rightmost non-empty X-Forwarded-For address,
falling back to the socket peer address.
Responses include standard rate limit headers:
RateLimit-Limit: 300
RateLimit-Remaining: 299
RateLimit-Reset: 60
Rejected requests get 429 Too Many Requests with a Retry-After header rounded up to whole seconds
and still carry x-request-id plus completion logs and telemetry.
State is in-memory and per process,
so running several replicas needs a shared store such as Redis.
The service embeds a Model Context Protocol server at /mcp.
It uses the Streamable HTTP transport, runs stateless, and returns plain JSON responses.
Service tools are health, status, version, and metrics.
Item tools are list_items, get_item, create_item, update_item, and delete_item.
Resources are axum-example://service/metadata and axum-example://openapi.json.
Each tool call builds an internal HTTP request and sends it through the base router (build_router),
preserving ConnectInfo<SocketAddr> and trusted forwarding headers while stripping caller-supplied credentials.
delete_item forwards to the admin route and takes the API key as an apiKey argument.
Swagger UI is available at /doc,
Redoc at /redoc,
RapiDoc at /rapidoc,
and Scalar at /docs with a /scalar alias.
The raw JSON is served from /api-docs/openapi.json.
Documentation UIs and the JSON spec route are not mounted when API_ENV=production.
The app records generic HTTP metrics with OpenTelemetry instruments.
Prometheus text output is available from /metrics.
OTLP export is disabled by default. Set one of these env vars to a non-blank endpoint to push metrics to an OpenTelemetry collector:
OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4317 cargo run --locked --release
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://127.0.0.1:4317 cargo run --locked --releaseMetrics use low-cardinality labels (method, route, status_class, status_code, error_kind, area).
Route labels come from a bounded closed set (src/classification.rs) and unknown methods map to "unknown".
Exported metric names:
axum_example_http_requests_started_totalaxum_example_http_requests_completed_totalaxum_example_http_requests_cancelled_totalaxum_example_http_request_duration_msaxum_example_http_in_progress_requestsaxum_example_http_errors_totalaxum_example_http_rate_limited_total
The per-route in-progress gauge uses a drop guard (InProgressGuard),
so cancelled requests decrement the gauge and increment axum_example_http_requests_cancelled_total.
Graceful shutdown drains in-flight requests and flushes the OTLP meter provider before exiting.
Run the full verification loop before committing:
cargo fmt
cargo fmt --manifest-path fuzz/Cargo.toml
cargo check --locked --manifest-path fuzz/Cargo.toml --bins
cargo clippy --locked --all-targets -- -Dwarnings
cargo clippy --locked --all-targets --all-features -- -Dwarnings
cargo test --locked
cargo test --locked --all-featuresUnit tests and inline proptest! suites live alongside the code in src/.
Run a deeper property sweep with:
PROPTEST_CASES=1000 cargo test --locked --libIntegration tests live in tests/:
| File | Covers |
|---|---|
tests/service_routes.rs |
root, health, status, version, metrics, HEAD, 405, docs |
tests/item_routes.rs |
item CRUD and validation |
tests/admin_routes.rs |
API key handling and admin routes |
tests/rate_limit.rs |
rate limit headers, 429 responses, x-request-id, exemptions |
tests/mcp.rs |
MCP initialize, tools, annotations, resources, cycle check |
tests/cli.rs |
binary CLI flags, scrubbed-env startup, invalid config exits |
Coverage-guided fuzz targets live in the standalone fuzz/ workspace
(enabled via the opt-in fuzzing feature).
See fuzz/README.md for details:
rustup toolchain install nightly
cargo install --locked cargo-fuzz
./fuzz.sh --require --fuzz-time 30Mutation testing uses cargo-mutants with .cargo/mutants.toml and cargo-nextest:
cargo install --locked cargo-mutants cargo-nextest
./mutants.sh --list
./mutants.sh --require --in-diff mainFor coverage, install cargo-llvm-cov:
cargo install --locked cargo-llvm-cov
cargo llvm-cov --locked --all-targets
cargo llvm-cov --locked --all-targets --htmlThis repository uses .pre-commit-config.yaml with prek or pre-commit:
brew install prek
prek install -f
prek run -a