Client
Each operation of the description is a method of the generated Client. It takes a Params with one field per parameter and returns one variant per documented response:
async fn create_and_read(base_url: &str, product: types::Product) -> Result<types::Product, api::Error> {
let client = api::Client::new(api::ReqwestTransport::new(base_url)).with_api_key("secret");
client.create_product(ops::create_product::Params::new(product)).await?;
match client.get_product(ops::get_product::Params::new(0)).await? {
ops::get_product::Response::Ok(product) => Ok(product),
ops::get_product::Response::NotFound(error) => panic!("{}", error.message),
}
}
Params::new takes the path parameters in URL order. Then it takes the other required parameters and then a required body. The URL fixes the argument order. So a reordered description cannot swap two arguments silently. With no arguments Params::default() is the same value.
A method takes its Params or a reference to them. So ¶ms keeps them for a retry. JSON, XML, form and multipart bodies are encoded from the reference with no copy.
Each security scheme gets its own setter with its name, such as with_api_key or with_bearer_auth. A misspelt scheme is a compile error.
Response media type
An operation whose success responses come in several media types has a media in its Params. The client prefers it in Accept and lists the others after it at q=0.9. A server whose answer depends on the resource then sends one the client decodes and not 406:
/// One product as XML from an operation that answers in JSON unless asked otherwise.
async fn product_as_xml(client: &api::Client<impl api::Transport>) -> Result<ops::get_product::Response, api::Error> {
let params = ops::get_product::Params { media: ops::get_product::Media::Xml, ..ops::get_product::Params::new(7) };
client.get_product(params).await
}
Links and callbacks
Response links become typed structs that fill the parameters of the linked operation:
let request = ops::create_product::Params { body: None, ..Default::default() };
let body = serde_json::json!({"id": 7, "name": "Desk lamp"});
let update = ops::create_product::links::UpdateProduct::new(&request, &body);
assert_eq!(update.product_id, Some(7));
The URL of a callback comes from the request that declares it:
/// Where the `productCreated` callback goes: the URL the request's body names.
fn created_callback(request: &api::Request) -> Option<String> {
let exchange = api::Exchange { request: Some(request), method: "POST", ..Default::default() };
ops::create_product::callbacks::product_created_url(&ops::create_product::Params::default(), &exchange)
}
OAuth2
A client credentials flow fetches its token with authorize_<scheme>. A device authorization flow (OpenAPI 3.2) shows a code to the user and then polls:
/// Signs in on another device. The user opens a page and types the code. Meanwhile this polls until they did.
async fn sign_in(client: &mut api::Client<impl api::Transport>) -> Result<(), api::Error> {
let code = client.device_start_o_auth2("shop-cli", &["read:products"]).await?;
println!("Open {} and enter {}", code.verification_uri, code.user_code);
loop {
match client.device_poll_o_auth2("shop-cli", &code).await? {
api::DevicePoll::Ready(_) => return Ok(()), // the token is now the client's credential
api::DevicePoll::Pending | api::DevicePoll::SlowDown => {
tokio::time::sleep(Duration::from_secs(code.interval)).await;
}
}
}
}
Other flows get helpers by what the scheme declares:
| Flow | Methods |
|---|---|
| Authorization code (PKCE) | Client::authorization_url_<s>(..., &pkce) and then exchange_code_<s>(code, ..., &pkce) |
| Password | authorize_password_<s>(user, password, client_id, secret, scopes) |
| Implicit | Client::implicit_url_<s>(...) |
| Refresh | refresh_<s>(refresh_token, client_id, secret) |
| OpenID Connect and RFC 8414 | discover_<s>() returns the token, authorization and device endpoints |
Streams
A response declared as a sequence also gets <op>_stream. The sequence is JSON Lines or JSON text sequences or server-sent events. <op>_stream gives a Stream that yields each item as it arrives. Read it with futures_util::StreamExt::next. A binary response gets the Response with its body still to come: resp.into_body().into_stream() yields its raw chunks. An item that does not decode is an Err. The items after it can still be read:
/// Every product event of the feed read as they arrive. The feed ends with `data: [DONE]`. That is not an event.
async fn product_events(client: &api::Client<impl api::Transport>) -> Result<Vec<types::ProductEvent>, api::Error> {
let params = ops::stream_product_events::Params::default();
let api::Streamed::Ok(mut stream) = client.stream_product_events_stream(params).await? else {
return Ok(vec![]); // another declared status, decoded whole
};
let mut events = vec![];
while let Some(item) = stream.next().await {
match item {
Ok(event) => events.push(event),
Err(api::Error::Decode { body, .. }) if body.ends_with(b"[DONE]") => break,
Err(error) => return Err(error),
}
}
Ok(events)
}
The plain method reads the whole body before it decodes it. On a feed that never ends it waits for ever.
Reconnecting
Reconnects the stream through transport when it ends or breaks off, as the EventSource of a browser
does.
It keeps a clone of transport: wrap a transport that is not Clone in an Arc. It waits
ItemStream::retry (3 seconds until the server sends a retry). Then it sends req again with
Last-Event-ID, so the server can resume after the last event read. An event that the connection broke inside
is dropped. So no event is read twice.
A failed reconnection is an Err and the next poll tries again. Each time it waits twice as long, up to a
minute. A 429 or 5xx counts as failed. The stream ends on a 204 or another status, on a response that is
not text/event-stream and after ItemStream::max_retries failed reconnections in a row.
ItemStream::no_reconnect ends it with the body. Other framings and a req of None end where the body
ends: a streamed request body cannot be sent twice.
/// Follows the feed. When the connection ends or breaks off the stream waits for the `retry` of the server. Then it
/// asks again with `Last-Event-ID`. So no event is lost or read twice. It ends when the server answers `204` or after
/// five failed reconnections in a row.
async fn follow(
client: &api::Client<impl api::Transport>,
mut on_event: impl FnMut(types::ProductEvent),
) -> Result<(), api::Error> {
let params = ops::stream_product_events::Params::default();
let api::Streamed::Ok(stream) = client.stream_product_events_stream(params).await? else {
return Ok(()); // another declared status: the feed is gone
};
let mut stream = stream.max_retries(5);
while let Some(event) = stream.next().await {
on_event(event?);
}
Ok(())
}
Conditional requests
A client sends a conditional request when the operation declares an If-None-Match header parameter. It can then ask for a product only if its copy is stale. When the description declares no 304 for the operation a 304 is Err(api::Error::NotModified). It has the headers of the response:
/// The product or `None` when the copy tagged `etag` is still current.
async fn product_if_changed(
client: &api::Client<impl api::Transport>,
etag: &str,
) -> Result<Option<ops::get_product::Response>, api::Error> {
let params = ops::get_product::Params { if_none_match: Some(etag.to_owned()), ..ops::get_product::Params::new(7) };
match client.get_product(params).await {
Err(api::Error::NotModified { .. }) => Ok(None),
other => other.map(Some),
}
}
Retries and caching
Retries, timeouts and caching come from a reqwest-middleware stack. ReqwestMiddlewareTransport sends through it. This one caches with http-cache-reqwest and retries with reqwest-retry:
/// Retries only methods that RFC 9110 calls idempotent. `RetryTransientMiddleware` alone retries any method. A `POST`
/// sent twice may create twice.
struct IdempotentOnly<M>(M);
#[async_trait::async_trait]
impl<M: reqwest_middleware::Middleware> reqwest_middleware::Middleware for IdempotentOnly<M> {
async fn handle(
&self,
req: reqwest::Request,
extensions: &mut http::Extensions,
next: reqwest_middleware::Next<'_>,
) -> reqwest_middleware::Result<reqwest::Response> {
use reqwest::Method;
let idempotent = [Method::GET, Method::HEAD, Method::OPTIONS, Method::PUT, Method::DELETE];
if idempotent.contains(req.method()) {
self.0.handle(req, extensions, next).await
} else {
next.run(req, extensions).await
}
}
}
/// A client that keeps an in-memory HTTP cache and revalidates with `If-None-Match`. It retries transient failures
/// (a lost connection, 5xx, 429) of idempotent requests with exponential backoff. It is a `reqwest-middleware` stack
/// sent through `ReqwestMiddlewareTransport`.
fn retrying(base_url: &str) -> api::Client<api::ReqwestMiddlewareTransport> {
use http_cache_reqwest::{Cache, CacheMode, HttpCache, HttpCacheOptions, MokaManager};
let policy = reqwest_retry::policies::ExponentialBackoff::builder().build_with_max_retries(3);
let cache =
HttpCache { mode: CacheMode::Default, manager: MokaManager::default(), options: HttpCacheOptions::default() };
let stack = reqwest_middleware::ClientBuilder::new(reqwest::Client::new())
.with(Cache(cache))
.with(IdempotentOnly(reqwest_retry::RetryTransientMiddleware::new_with_policy(policy)))
.build();
api::Client::new(api::ReqwestMiddlewareTransport::with_client(stack, base_url)).with_api_key("secret")
}
Each piece of that stack does one job and has limits:
| Piece | What it does | Limits |
|---|---|---|
RetryTransientMiddleware | It retries a lost connection, a 5xx, a 408 or a 429 with exponential backoff. | It ignores Retry-After: the backoff alone sets the wait. It does not tell methods apart, so on its own it sends a failed POST again. |
IdempotentOnly | It lets only GET, HEAD, OPTIONS, PUT and DELETE through to the retry. | None. |
Cache | It keeps responses as RFC 9111 allows and revalidates a stale one with If-None-Match or If-Modified-Since. A 304 comes back as the cached 200. | Only its 1.0 alpha builds on reqwest 0.13. |
A streamed upload cannot be sent twice. So retry middleware does not retry it.
ureq and the GlooTransport of the browser have no middleware stack. They are tower services, so tower layers wrap them. See your own transport.
Errors
A call returns Err(api::Error) when it gets no response the description declares:
| Variant | Meaning |
|---|---|
Transport | The request could not be sent or the connection broke off (connection or TLS for example). |
Encode | A parameter or the body could not be serialized. |
Decode | A documented response does not fit its schema. pointer says where. |
UnexpectedMedia | The status is declared but the response’s Content-Type is none that the description declares for it. |
NotModified | 304 Not Modified to a request that sent If-None-Match or If-Modified-Since. The operation declares no 304. The representation that the client holds is still current. |
UnexpectedStatus | A status that the operation declares neither as itself nor as a default. |
Invalid | An item of a request body still arriving breaks the description’s constraints. |
TooLarge | A body still arriving went past a limit in bytes: the max_body_bytes of the server. |
Every other variant that read a response carries its raw body.
Browser (WebAssembly)
The client compiles for wasm32-unknown-unknown and sends through the browser’s fetch:
- Depend on
gloo-netwith itshttpfeature under[target.'cfg(target_arch = "wasm32")'.dependencies]. Native builds then skip it, as the adapter compiles on wasm32 only. - Set
client = { adapters = ["gloo-net"] }andserver = false. - Build the client on
api::GlooTransport::new("/api").
Futures on wasm32 are not Send. A transport service of your own writes + api::MaybeSend instead of + Send on its futures, so it compiles for both targets.