ApiGate
ApiGate is a macro-driven API gateway for Rust services.
It lets you declare reverse-proxy routes as Rust modules, validate typed request data, run pre-proxy hooks, transform requests before forwarding, choose upstream backends with routing/balancing policies, and customize errors and observability without exposing axum details in your application code.
Under the hood ApiGate is built on axum, hyper-util, tower, and tracing.
What It Provides
- Declarative service and route macros:
#[apigate::service],#[apigate::get],#[apigate::post], etc. - Reverse proxying with streaming passthrough when a route does not need to read the body.
- Typed validation for
path,query,json, andforminputs. beforehooks for auth, headers, request metadata, and per-request state.mapfunctions for typed request transformation before the upstream call.- Multipart passthrough without buffering file bodies.
- Built-in policies: round-robin, consistent hash, header/path sticky, least-request, least-time.
- Custom routing strategies and custom balancers.
- Custom error rendering, including JSON envelopes and fully custom hook/map responses.
- Optional runtime observability through
tracingor a custom runtime observer. - External
tower/axummiddleware composition through the underlying router.
Installation
Add the facade crate to your application:
[]
= "0.2.5"
= { = "1", = ["rt-multi-thread", "macros"] }
= { = "1", = ["derive"] }
= "1"
Optional dependencies used in examples:
= "0.8"
= "1"
= "1"
= "0.1"
= { = "0.3", = ["env-filter", "fmt"] }
= { = "0.6", = ["trace"] }
= { = "1", = ["v4", "serde"] }
Supported Rust
ApiGate declares Rust 1.88 as its package rust-version. Rust 1.88 stabilizes let chains in the Rust 2024 edition, which ApiGate uses in its implementation. CI checks that the library crates compile on Rust 1.88 and runs the full test suite on the latest stable toolchain.
Quick Start
use SocketAddr;
async
Run a local upstream and the example gateway:
Then call:
Core Concepts
ApiGate has three layers:
| Layer | Purpose |
|---|---|
| Service | A macro-generated collection of routes with an optional prefix and default policy. |
| Route | An HTTP method/path declaration with optional validation, hooks, mapping, rewrite, and policy override. |
| App | Runtime configuration: mounted services, upstream backends, shared state, timeouts, policies, errors, and observability. |
The normal flow is:
- A request matches an axum route generated by ApiGate.
- ApiGate optionally extracts typed path parameters.
beforehooks run in order.- The route optionally validates or maps
query,json, orformdata. - A routing strategy selects candidate backends.
- A balancer picks one backend.
- ApiGate rewrites the URI and proxies the request to the upstream.
- Runtime events are emitted only if a runtime observer is configured.
Services
A service is an inline Rust module annotated with #[apigate::service].
Service arguments:
| Argument | Description |
|---|---|
name = "sales" |
Logical service name. Defaults to the module name. This name is used for backend registration. |
prefix = "/sales" |
Public URL prefix for all routes in the service. Defaults to "". |
policy = "name" |
Default named policy for all routes in the service. |
The service macro injects a routes() function. Mount it with backends:
let app = builder
.mount_service
.build?;
If you want to register backends separately, use .backend(...).mount(...):
let app = builder
.backend
.mount
.build?;
Routes
Supported method attributes:
Full route shape:
async
Route arguments:
| Argument | Description |
|---|---|
"/path" |
Public route path relative to the service prefix. Supports {param} segments. |
to = "/path" |
Upstream path rewrite. Without to, ApiGate strips the service prefix and forwards the remaining path. Supports {param} template captures. |
path = T |
Deserializes typed path parameters with axum. T should be Deserialize + Clone + Send + Sync + 'static. |
query = T |
Validates query string as T. With map, serializes mapped output back into the query string. |
json = T |
Validates JSON body as T. With map, serializes mapped output as a new JSON body. |
form = T |
Validates application/x-www-form-urlencoded data as T. With map, serializes mapped output back as form data or query data for GET/HEAD. |
multipart |
Enables multipart passthrough. The body is not read or buffered. |
before = [...] |
Hooks executed before proxying. They run in the listed order. |
map = fn_name |
Typed request transformation for query, json, or form. Not supported with multipart. |
policy = "name" |
Route-level policy override. |
Only one body/data mode can be used per route: query, json, form, or multipart.
Path Rewrites
No to means strip the service prefix:
GET /sales/ping is forwarded to /ping on the upstream.
Static rewrite:
async
Template rewrite:
async
Typed Inputs
Path Parameters
use Deserialize;
use Uuid;
Path values are extracted before hooks and inserted into RequestScope. Hooks and maps can request &SalePath or owned SalePath as parameters.
Query, JSON, and Form
async
async
async
Without map, ApiGate validates the input and forwards the original body/query data. For json and form bodies, validation requires reading the body up to map_body_limit.
With map, ApiGate validates the input, calls your mapper, and forwards the mapped output.
Multipart
async
Multipart bodies are proxied as streaming passthrough. ApiGate does not read or buffer the file body. map is intentionally not supported for multipart routes.
Hooks
Hooks run before the upstream request is sent. Use them for authentication, authorization, request IDs, header injection, request mutation, and per-request metadata.
async
async
PartsCtx exposes the request head:
| Method | Purpose |
|---|---|
service() |
Current logical service name. |
route_path() |
Route path relative to the service prefix. |
method() |
Current HTTP method. |
uri() / uri_mut() |
Read or mutate the request URI. |
headers() / headers_mut() |
Read or mutate headers. |
header(name) |
Read a UTF-8 header as Option<&str>. |
set_header(name, value) |
Insert or replace a header. |
set_header_if_absent(name, value) |
Insert a header only when absent. |
remove_header(name) |
Remove a header. |
extensions() / extensions_mut() |
Access request extensions. |
Maps
Maps transform typed query, json, or form inputs before proxying.
use ;
async
async
Mapping behavior:
| Route data | Map output handling |
|---|---|
query = T |
Serialized with serde_urlencoded and written into the URI query string. |
json = T |
Serialized with serde_json and sent as a new JSON body. |
form = T |
Serialized with serde_urlencoded; sent as a form body for non-GET/HEAD and as query string for GET/HEAD. |
Hook and Map Parameters
#[apigate::hook] and #[apigate::map] rewrite your function signature into an efficient internal form. You declare only the values you need.
| Parameter | Source | Example |
|---|---|---|
&mut PartsCtx |
Request head context. | ctx: &mut apigate::PartsCtx |
&mut RequestScope |
Direct access to per-request scope. | scope: &mut apigate::RequestScope |
&T |
Local per-request value first, then shared app state. | config: &AuthConfig |
&mut T |
Local per-request value only. | counter: &mut RequestCounter |
T in a hook |
scope.take::<T>(); falls back to cloning shared state. |
path: SalePath |
First owned T in a map |
Typed input from query, json, or form. |
input: PublicBuy |
Additional owned T in a map |
scope.take::<T>(); falls back to cloning shared state. |
path: SalePath |
Rules enforced by the macros:
- At most one
&mut PartsCtxparameter. - At most one
&mut RequestScopeparameter. - At most one extracted
&mut Tparameter. &mut RequestScopecannot be combined with extracted&Tor&mut Tparameters.- Extracted
&mut Tcannot be combined with extracted&Tparameters. - Hook and map functions must be
async.
Example using shared state and per-request path data:
async
async
Shared and Per-Request State
Register app state with .state(...):
let app = builder
.mount_service
.state
.build?;
State is stored in Extensions and exposed to hooks/maps by reference. Read-only access through &T does not clone state per request.
For per-request data, insert into RequestScope from a hook:
async
async
RequestScope methods:
| Method | Purpose |
|---|---|
get::<T>() |
Read local value first, then shared app state. |
get_mut::<T>() |
Mutably read local per-request value only. |
insert(value) |
Insert local per-request value. |
take::<T>() |
Remove local value, or clone from shared app state if absent. |
take_body() |
Take request body ownership. Used by generated pipelines. |
body_limit() |
Current generated pipeline body limit. |
Error Handling
ApiGate separates two use cases:
| Use case | API |
|---|---|
| Framework-rendered errors | Return ApigateError::bad_request(...), unauthorized(...), forbidden(...), etc. These go through the global error renderer. |
| Fully custom responses | Return ApigateError::from_response(...) or ApigateError::json(...). These bypass the global renderer. |
Default Behavior
By default, framework errors are returned as text/plain with the error status code and a user-facing message.
Build-time configuration errors are returned from .build() as ApigateBuildError.
Runtime framework errors are normalized as ApigateFrameworkError before rendering:
Useful methods:
| Method | Purpose |
|---|---|
status_code() |
Default HTTP status for the error. |
code() |
Stable machine-readable code. |
user_message() |
Message safe to return to clients. |
debug_details() |
Internal diagnostic details intended for logs. |
Global JSON Error Renderer
Use .error_renderer(...) when you want one JSON format for framework errors:
use ;
use ;
use StatusCode;
let app = builder
.mount_service
.error_renderer
.build?;
Custom Hook and Map Errors
Return framework-rendered errors:
async
Return a custom JSON response that bypasses the global renderer:
async
Convenience JSON constructors:
bad_request_json
unauthorized_json
forbidden_json
Other common framework constructors:
new
bad_request
unauthorized
forbidden
payload_too_large
unsupported_media_type
bad_gateway
gateway_timeout
internal
Full example:
Runtime Observability and Tracing
ApiGate does not install a global tracing subscriber. Your application owns tracing configuration.
By default, ApiGate runtime observer is disabled. This keeps the hot path low-overhead: request handling only checks whether an observer exists.
Enable the built-in tracing observer:
let app = builder
.mount_service
.enable_default_tracing
.build?;
Or provide a custom runtime observer:
let app = builder
.mount_service
.runtime_observer
.build?;
Runtime event kinds include request start, backend selection, pipeline failure, dispatch failure, upstream success, and upstream failure. Success-oriented events are debug-level in the default observer. Expected client errors are logged as info, and server/upstream failures as warn.
Disable observer explicitly after conditional configuration:
let app = builder
.mount_service
.disable_runtime_observer
.build?;
External Tower Layers
Use with_router to add outer tower/axum middleware after building the app:
use TraceLayer;
let app = builder
.mount_service
.build?
.with_router;
run.await?;
For full manual composition, take the underlying router:
let router = builder
.mount_service
.build?
.into_router;
let router = router.layer;
run_router.await?;
Useful examples:
RUST_LOG=debug,apigate=trace
RUST_LOG=debug,apigate=debug,tower_http=debug
hyper-util also emits internal logs for transport, connection pooling, and connecting. Enable them only for diagnostics:
RUST_LOG=info,apigate=debug,hyper_util::client::legacy=debug
Policies, Routing, and Balancing
A policy combines:
| Component | Purpose |
|---|---|
| Routing strategy | Selects candidate backends and optionally produces an affinity key. |
| Balancer | Picks the final backend from the candidate set. |
Default policy: NoRouteKey + RoundRobin.
Register named policies:
let app = builder
.mount_service
.policy
.policy
.policy
.policy
.build?;
Use a service-level policy:
Override per route:
async
Policy priority:
- Route-level
policy = "name". - Service-level
policy = "name". - Builder default policy.
Built-in policy presets:
| Preset | Meaning |
|---|---|
Policy::round_robin() |
NoRouteKey + RoundRobin. |
Policy::consistent_hash() |
NoRouteKey + ConsistentHash; falls back to round-robin when no affinity key exists. |
Policy::header_sticky("x-user-id") |
HeaderSticky + ConsistentHash. |
Policy::path_sticky("id") |
PathSticky + ConsistentHash. |
Policy::least_request() |
NoRouteKey + LeastRequest. |
Policy::least_time() |
NoRouteKey + LeastTime. |
You can also build custom combinations:
let policy = new
.router
.balancer;
Custom Routing Strategy
use ;
;
RouteCtx includes service, prefix, route path, method, URI, and headers. RoutingDecision returns an optional affinity key and either all backend candidates or explicit backend indices.
Custom Balancer
use ;
;
BalanceCtx gives access to service, affinity, backend pool, candidate count, candidate indices, candidate backends, and candidate membership checks.
Built-in balancers use atomics and avoid locks on the request path.
App Builder Reference
Common builder methods:
| Method | Description |
|---|---|
.mount_service(routes, urls) |
Register backend URLs for routes.service and mount the routes. |
.backend(service, urls) |
Register backend URLs by service name. |
.mount(routes) |
Mount macro-generated routes. Requires matching .backend(...). |
.policy(name, policy) |
Register a named policy. |
.default_policy(policy) |
Set fallback policy for routes without route/service policy. |
.state(value) |
Insert shared application state available to hooks and maps. |
.request_timeout(duration) |
Total timeout for an upstream request. Default: 30s. |
.connect_timeout(duration) |
TCP connect timeout for upstream connections. Default: 5s. |
.pool_idle_timeout(duration) |
Idle connection lifetime in the upstream client pool. Default: 90s. |
.pool_max_idle_per_host(max) |
Maximum idle upstream connections per host. Default: unlimited. |
.upstream(config) |
Replace the upstream transport configuration. |
.map_body_limit(bytes) |
Max body size read by generated validation/map pipelines. Default: 2 MiB. |
.error_renderer(renderer) |
Configure framework error rendering. |
.enable_default_tracing() |
Emit built-in runtime events through tracing. |
.runtime_observer(observer) |
Configure a custom runtime observer. |
.disable_runtime_observer() |
Disable runtime observer events. |
.build() |
Build the gateway app. |
UpstreamConfig methods:
| Method | Description |
|---|---|
.connect_timeout(duration) |
TCP connect timeout for upstream connections. |
.pool_idle_timeout(duration) |
Idle connection lifetime in the upstream client pool. |
.pool_max_idle_per_host(max) |
Maximum idle upstream connections per host. |
.tcp_nodelay(bool) |
Toggle TCP_NODELAY for upstream TCP connections. |
| `.configure_client( | client |
| `.configure_connector( | connector |
For reusable or detailed transport settings, build a config value from defaults:
let upstream = default
.connect_timeout
.tcp_nodelay;
let app = builder
.mount_service
.upstream
.build?;
Use the hyper-util escape hatches for less common client or connector knobs:
let upstream = default
.configure_connector
.configure_client;
App methods:
| Method | Description |
|---|---|
| `.with_router( | router |
.into_router() |
Consume the app and return the axum Router. |
Serving helpers:
run.await?;
run_router.await?;
Tune the listener socket when ApiGate owns it:
let config = new
.backlog
.reuse_address
.tcp_nodelay;
run_with.await?;
ServeConfig also supports listener buffer sizes, IPv6-only binding, and
SO_REUSEPORT on supported Unix platforms. Use run_router_with for the same
socket options with a manually composed router.
Performance Notes
ApiGate is designed to avoid unnecessary work on routes that do not need it:
- Routes without
path,before,query,json,form, ormaphave no generated pipeline and proxy the body as streaming passthrough. - Multipart routes stream the request body without reading or buffering it.
jsonandformvalidation read the body only when the route declares typed validation or mapping.queryvalidation does not read the body.- Shared app state is accessed by reference through
Extensions; read-only&Taccess does not clone per request. - Per-request
RequestScopelocal storage allocates only when values are inserted. - Route metadata is stored in a table and request routing carries a small route index.
- The upstream client uses keep-alive pooling,
TCP_NODELAY, configurable connect timeout, configurable idle timeout, and exposes hyper-util client/connector tuning hooks. - Built-in balancers are lock-free and use atomics.
- Runtime observer is disabled by default; when disabled, the hot path only performs an
Optioncheck.
Routes with json, form, or mapped bodies intentionally allocate for parsed/serialized payloads. Keep those routes for boundaries where validation or transformation is worth the cost.
Examples
Run the mock upstream first:
Then run any example:
Example guide:
| Example | Shows |
|---|---|
basic |
Passthrough proxying, static rewrite, rewrite templates. |
hooks |
Shared state, auth, header injection, hook chains, per-request scope data. |
errors |
Global JSON error renderer, user/debug message separation, custom JSON from hooks. |
logging |
Built-in tracing observer and custom runtime observer. |
tower_logging |
External tower_http::TraceLayer with .with_router(...). |
runtime_tuning |
Listener socket tuning plus upstream hyper-util client/connector settings. |
path |
Typed path validation, path data in hooks, path data in maps. |
map |
Query, JSON, and form transformations. |
policy |
Header/path sticky routing, consistent hash, least-request, least-time, round-robin. |
multipart |
Multipart upload passthrough with and without auth. |
Each example prints ready-to-run curl commands.