Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Adapters

The cargo features of the runtime turn on its adapters and codecs. The table lists what turns each one on. generate writes them all but simd, which is yours to list or leave out. cargo honig check reports them when they are out of date.

FeatureCrateAddsOn when
clienttower-serviceThe generated client: the Transport bound over tower services and TowerTransportYou generate the client
servertower-serviceThe generated server: a tower Service, routing, conditional requests and the wide eventYou generate the server
reqwestreqwestReqwestTransport: async client with streaming bodiesclient = { adapters = ["reqwest"] }
reqwest-middlewarereqwest-middlewareReqwestMiddlewareTransport: retries, tracing and caching from your middleware stackclient = { adapters = ["reqwest-middleware"] }
urequreqUreqTransport: blocking clientclient = { adapters = ["ureq"] }
gloo-netgloo-netGlooTransport: browser fetch on wasm32 onlyclient = { adapters = ["gloo-net"] }
axumaxumServer::into_axum and the address of the client from the ConnectInfo of axumserver = { adapters = ["axum"] }
tracingtracingA span per request and a log line for each wide eventserver = { adapters = ["tracing"] }
tracing-opentelemetryopentelemetryW3C Trace Context: traceparent and tracestateadapters = ["tracing-opentelemetry"] in client or server
ipnetipnetformat: ipv4-cidr and ipv6-cidr checksThe description calls for it
idnidnaemail, idn-email, hostname and idn-hostname checksThe description calls for it
regressregresspattern and patternProperties checks (ECMA-262)The description calls for it
oauthThe OAuth 2.0 flows of the client: token grants, device authorization and discoveryThe description calls for it
pkcesha2Pkce, authorization_url and exchange_code: the OAuth 2.0 authorization code flow. Outside wasm32 Pkce::new makes a verifier from OS randomnessThe description calls for it
cookiecookieCookie parameters and API keysThe description calls for it
multipartmultermultipart/* bodies and partsThe description calls for it
base64base64Binary data in JSON (format: byte, contentEncoding, base64url) and http basic credentialsThe description calls for it
xmlquick-xmlXML bodies and partsThe description calls for it
simdsonic-rsSIMD for large bodies: JSON with sonic-rs (x86_64 and aarch64), the UTF-8 check of text with simdutf8 and base64 with base64-simd. Multipart boundaries use memchr with or without itYou or cargo honig init add it

An adapter is compiled whenever its half lists it, also when its library is an optional dependency that is off. Depend on the major version that the table names. Otherwise cargo builds two copies whose types do not match.

axum

into_axum() returns a Router with a route per path template. It merges next to your own routes or nests under a prefix:

async fn serve(addr: &str) -> std::io::Result<()> {
    let listener = tokio::net::TcpListener::bind(addr).await?;
    println!("serving the catalog on http://{addr}/v1");
    let app = api::Server::new(Catalog::default())
        // One JSON line per request: the operation, the status, the duration, the body sizes and more.
        .on_event(|event: &api::RequestEvent| println!("{}", event.to_json()))
        .into_axum();
    axum::serve(listener, app).await
}

A path that the description does not declare falls through to the fallback of the router: a bare 404 with no body and no wide event. To answer it in the error schema with a wide event, give the router a fallback that is the server:

/// An axum router whose undeclared paths reach the server too. They then get its 404 in the error schema and a wide
/// event. Leave the fallback out to give those paths to routes of your own.
fn with_fallback(lines: Arc<Mutex<Vec<String>>>) -> axum::Router {
    let server = || {
        let lines = Arc::clone(&lines);
        api::Server::new(Catalog::default()).on_event(move |event: &api::RequestEvent| {
            if let Ok(mut lines) = lines.lock() {
                lines.push(event.to_json());
            }
        })
    };
    server().into_axum().fallback_service(server().into_service())
}

axum refuses to merge two routers that both have a fallback. Set it once, on the router that you serve.

Recipes serves a web app next to the API and a WebSocket next to the generated routes.

hyper and other servers

into_service() is a tower Service over http requests:

async fn serve_with_hyper(listener: tokio::net::TcpListener) -> std::io::Result<()> {
    let service = api::Server::new(Catalog::default()).into_service();
    loop {
        let (stream, _) = listener.accept().await?;
        let service = hyper_util::service::TowerToHyperService::new(service.clone());
        let io = hyper_util::rt::TokioIo::new(stream);
        tokio::spawn(hyper::server::conn::http1::Builder::new().serve_connection(io, service));
    }
}

Blocking client

UreqTransport sends with ureq. block_on runs the call with no async runtime:

/// The blocking client. `block_on` returns once the response is read with no async runtime.
fn list_products(base_url: &str) -> Result<ops::list_products::Response, api::Error> {
    let client = api::Client::new(api::UreqTransport::new(base_url)).with_api_key("secret");
    api::block_on(client.list_products(ops::list_products::Params::new()))
}

Testing without a socket

A server’s into_service() is a transport too. The client then sends each request straight to the server in memory:

/// A client wired straight to the server with no socket. A test of your server needs this.
fn in_memory_client() -> api::Client<impl api::Transport> {
    let service = api::Server::new(Catalog::default()).into_service();
    api::Client::new(service).with_api_key("secret")
}

Your own transport

A transport is any tower Service of http requests. Write one to send with any HTTP client. Wrap one with tower’s layers:

/// A transport is any tower `Service`, so tower's layers wrap one: this one adds a request ID to every request.
fn with_request_id(transport: impl api::Transport) -> impl api::Transport {
    tower::ServiceBuilder::new()
        .map_request(|mut req: api::Request| {
            req.headers_mut().insert("x-request-id", api::http::HeaderValue::from_static("req-1"));
            req
        })
        .service(transport)
}

TLS

TLS comes from your own dependency. honig depends on reqwest and ureq without default features. Cargo adds the features that your crate turns on. The default is rustls. If your crate turns them off then add rustls or native-tls. Otherwise every https request fails.