Recipes
Each recipe is a whole setup that combines the pieces of the other pages. Each one is a test, so it matches the code.
Web server and CLI client
The examples/shop crate runs a server and a client for a small catalog of products against each other. Every example in this book is a test that runs on each change. So each example matches the code.
Its src/api is what cargo honig generate writes. Its src/supplier is a second module, a client for a book supplier: see Several APIs in one crate.
The description is openapi.yaml:
openapi: 3.2.0
info:
title: Catalog
version: 1.0.0
servers:
- url: https://shop.example.com/v1
security:
- apiKey: []
paths:
/products:
get:
operationId: listProducts
parameters:
- name: limit
in: query
schema: {type: integer, format: int32, maximum: 100}
- name: tags
in: query
style: form
explode: false
schema: {type: array, items: {type: string}}
responses:
'200':
description: A page of products
headers:
X-Next: {schema: {type: string}}
content:
application/json:
schema: {type: array, items: {$ref: '#/components/schemas/Product'}}
default:
description: Error
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
post:
operationId: createProduct
requestBody:
required: true
content:
application/json:
schema: {$ref: '#/components/schemas/Product'}
responses:
'201':
description: Created
content:
application/json:
schema: {$ref: '#/components/schemas/Product'}
default:
description: Error
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/products/{productId}:
get:
operationId: getProduct
parameters:
- name: productId
in: path
required: true
schema: {type: integer, format: int64}
responses:
'200':
description: A product
content:
application/json:
schema: {$ref: '#/components/schemas/Product'}
'404':
description: Not found
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
components:
securitySchemes:
apiKey: {type: apiKey, in: header, name: X-API-Key}
schemas:
Product:
oneOf:
- $ref: '#/components/schemas/Physical'
- $ref: '#/components/schemas/Digital'
discriminator:
propertyName: kind
mapping:
physical: '#/components/schemas/Physical'
digital: '#/components/schemas/Digital'
# Each branch fixes its tag, so a value matches exactly one: `oneOf` holds whatever the discriminator says.
Physical:
type: object
required: [kind, name]
properties:
kind: {const: physical}
name: {type: string}
fragile: {type: boolean}
sku: {type: string, pattern: '^[A-Z]{3}-[0-9]{4}$', description: Stock keeping unit}
Digital:
type: object
required: [kind, name]
properties:
kind: {const: digital}
name: {type: string}
downloads: {type: [integer, "null"], format: int32}
Error:
type: object
required: [code, message]
properties:
code: {type: integer, format: int32}
message: {type: string}
Server
The server implements the generated Api trait, which has one method per operation:
/// The catalog in memory. The ID of a product is its index.
#[derive(Default)]
pub struct Catalog(Mutex<Vec<types::Product>>);
impl Catalog {
fn products(&self) -> Result<MutexGuard<'_, Vec<types::Product>>, api::ApiError> {
self.0
.lock()
.map_err(|_| api::ApiError::new(api::http::StatusCode::INTERNAL_SERVER_ERROR, "catalog lock poisoned"))
}
}
impl api::Api for Catalog {
type Principal = ();
async fn list_products(
&self,
params: ops::list_products::Params,
_: &api::Context<'_>,
) -> Result<ops::list_products::Response, api::ApiError> {
let limit = params.limit.and_then(|n| usize::try_from(n).ok()).unwrap_or(usize::MAX);
let body = self.products()?.iter().take(limit).cloned().collect();
Ok(ops::list_products::Response::Ok { body, x_next: None })
}
async fn create_product(
&self,
params: ops::create_product::Params,
_: &api::Context<'_>,
) -> Result<ops::create_product::Response, api::ApiError> {
self.products()?.push(params.body.clone());
Ok(ops::create_product::Response::Created(params.body))
}
async fn get_product(
&self,
params: ops::get_product::Params,
_: &api::Context<'_>,
) -> Result<ops::get_product::Response, api::ApiError> {
let found = usize::try_from(params.product_id).ok().and_then(|i| self.products().ok()?.get(i).cloned());
Ok(match found {
Some(product) => ops::get_product::Response::Ok(product),
None => ops::get_product::Response::NotFound(types::Error::new(404, "no such product".to_owned())),
})
}
}
Serve it with axum in src/main.rs:
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
}
Client
The client has one method per operation. Each 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),
}
}
API server and SPA
A single-page app and its API share one port. Unknown paths under the API’s base path still get the API’s 404 in its error schema, so a client never receives the app’s HTML by mistake. rust-embed compiles the app’s folder into the binary, so the server ships as one file:
/// A web app and its API on one port. The API lives under its base path `/v1`, so an unknown `/v1/...` path gets a
/// `404` in the error schema. Every other path serves the app: a file of `dist` or else its `index.html`, so that the
/// app's own router handles the path. `dist` is compiled into the binary, so the server ships as one file.
#[derive(rust_embed::Embed)]
#[folder = "tests/v32_catalog/dist"]
struct Dist;
async fn app(uri: axum::http::Uri) -> axum::response::Response {
use axum::response::IntoResponse;
let path = uri.path().trim_start_matches('/');
match Dist::get(path).or_else(|| Dist::get("index.html")) {
Some(file) => {
([(axum::http::header::CONTENT_TYPE, file.metadata.mimetype().to_owned())], file.data).into_response()
}
None => axum::http::StatusCode::NOT_FOUND.into_response(),
}
}
fn web_app() -> axum::Router {
let api = api::Server::new(Catalog::default()).into_service();
axum::Router::new().nest_service("/v1", api).fallback(app)
}
Claims from an auth layer you already run
A JWT or session layer that you already run puts its claims in the request’s extensions. authenticate maps them to the principal of your Api:
/// What an auth layer that you already run puts in the extensions, such as the claims of a JWT. Its fields are its
/// own, not your principal.
#[derive(Clone)]
struct Claims {
sub: String,
}
/// A stand-in for that layer: it trusts `Authorization: Bearer <sub>`. A real one checks a signature.
fn claims_layer(mut req: axum::extract::Request) -> axum::extract::Request {
let sub = req.headers().get("authorization").and_then(|v| v.to_str().ok()?.strip_prefix("Bearer "));
if let Some(sub) = sub.map(str::to_owned) {
req.extensions_mut().insert(Claims { sub });
}
req
}
/// `authenticate` maps the claims to the principal of the `Api`. A request without claims is anonymous.
fn with_claims() -> axum::Router {
api::Server::new(super::auth::Server)
.authenticate(|req: &api::Request| {
let who = req.extensions().get::<Claims>().map(|claims| claims.sub.clone());
std::future::ready(Ok(who))
})
.into_axum()
.layer(tower::util::MapRequestLayer::new(claims_layer))
}
Errors of layers outside the server
A layer outside the server answers in its own format. Its answers go out in the error schema when they pass through errors(). Layers shows a fallback that does this. A layer that fails with an error, such as a timeout or a full queue, goes through axum’s HandleErrorLayer:
/// Layers outside the server that fail with an error, such as a timeout or a full queue. axum turns such an error
/// into a response with `HandleErrorLayer`. `errors()` renders it in the error schema of the description, so a
/// client decodes it as its typed error.
fn guarded(max_in_flight: usize) -> axum::Router {
let server = api::Server::new(Catalog::default());
let errors = server.errors();
server.into_axum().layer(
tower::ServiceBuilder::new()
.layer(axum::error_handling::HandleErrorLayer::new(move |e: tower::BoxError| {
let status = if e.is::<tower::timeout::error::Elapsed>() {
api::http::StatusCode::GATEWAY_TIMEOUT
} else {
api::http::StatusCode::SERVICE_UNAVAILABLE
};
std::future::ready(errors.response(status, e.to_string()))
}))
.load_shed()
.concurrency_limit(max_in_flight)
.timeout(Duration::from_secs(30)),
)
}
Middlewares
Layers outside the server, authenticate and layers inside it, in the order that a request passes them:
/// Every kind of layer in one server. A request passes them top to bottom.
fn full_stack() -> axum::Router {
api::Server::new(super::auth::Server)
// Inside the server, after routing and the check of the credentials that the description asks for. Their
// errors go out in the error schema.
.operation_layer(tower::timeout::TimeoutLayer::new(Duration::from_secs(10)))
.authenticate(|req: &api::Request| {
std::future::ready(Ok(req.extensions().get::<Claims>().map(|claims| claims.sub.clone())))
})
// After `authenticate`: this layer sees the principal.
.operation_layer(tower::filter::AsyncFilterLayer::new(|req: api::Request| {
let blocked = req.extensions().get::<String>().is_some_and(|who| who == "mallory");
let refusal = api::ApiError::new(api::http::StatusCode::FORBIDDEN, "blocked");
std::future::ready(if blocked { Err(refusal) } else { Ok(req) })
}))
.into_axum()
// Outside the server, on every request before routing. The last one added runs first.
.layer(tower::util::MapRequestLayer::new(claims_layer))
.layer(tower_http::cors::CorsLayer::permissive())
}
WebSockets
OpenAPI cannot describe a WebSocket. So honig generates nothing for one. Serve it as a plain axum route next to the generated routes. Share state through your own Arc:
/// The API of the catalog and a WebSocket route that the description does not declare. It answers each message with
/// how many products the catalog holds.
fn with_live_updates() -> axum::Router {
let catalog = Arc::new(Catalog::default());
let live = {
let catalog = Arc::clone(&catalog);
move |ws: WebSocketUpgrade| async move { ws.on_upgrade(move |socket| count_products(socket, catalog)) }
};
api::Server::new(catalog).into_axum().route("/v1/live", axum::routing::get(live))
}
async fn count_products(mut socket: WebSocket, catalog: Arc<Catalog>) {
while let Some(Ok(Message::Text(_))) = socket.recv().await {
let count = catalog.products().map_or(0, |products| products.len());
if socket.send(Message::Text(count.to_string().into())).await.is_err() {
break;
}
}
}