apigenie-generator server axum
Experimental · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 not run yet · 2 features of the fixture not supported yet · Verification
Generate a Rust server crate on axum 0.8 from an OpenAPI document: a trait with an async method per operation, and a router that checks, decodes and validates requests before it calls them.
(experimental, outside the 1.0 compatibility promise)
server axumis new in 0.12.0, and the generated crate isn’t yet checked against requests in contract tests (conformance Level 3): the options and the output can still change.server axumsays so in its--helpand on the first line it prints, on the standard error. See the experimental commands.
Usage
apigenie-generator server axum [...OPTIONS] INPUT_FILE
Description
The generator writes a library crate for Rust 1.85 (edition 2024). It shares src/models.rs and
the types of its runtime with apigenie-generator client rust,
so a client and a server generated from the same document read and write values the same way.
| File | Contents |
|---|---|
Cargo.toml |
the package, its dependencies, and the feature internal when the document has operations marked x-internal: true |
src/lib.rs |
the modules, with Api, router, SecurityHandler, AcceptAnyCredentials, Credentials, Scheme, RequestContext and Problem re-exported |
src/server.rs |
the Api trait, a SCHEME_* constant per security scheme, and per operation its parameters struct, its body enum when it has several media types, its response enum and its handler; router |
src/models.rs |
the types of the component schemas the operations use, and of their inline schemas, with their Validate implementations |
src/internal.rs |
the response types and handlers of the operations marked x-internal: true, behind the cargo feature internal |
src/runtime/*.rs |
the request context, reading parameters and bodies, security, problem details, writing responses and streams, FilePart, Nullable<T>, DateTime, Date, Base64 and validation |
Cargo.toml depends on axum 0.8 (with multipart), serde 1, serde_json 1, futures 0.3, bytes 1,
time 0.3 and regex 1, and on uuid 1, url 2 and rust_decimal 1 when the document uses their
formats. Serve the router with axum::serve on a tokio runtime.
The examples on this page use the crate generated with -o carpet-express from the Carpet Express
fixture (OpenAPI 3.1 definition). Implement Api,
which has one method per operation, and serve router(api, security). This application also
depends on axum, tokio (with macros, net and rt-multi-thread), rust_decimal for Decimal,
and futures for the streams:
use std::sync::Arc;
use carpet_express::models::{Money, Rate, RateRequest, ShipmentId};
use carpet_express::runtime::ProblemDetails;
use carpet_express::server::{GetShipmentParams, GetShipmentResponse, QuoteRatesResponse};
use carpet_express::{Api, Credentials, RequestContext, Scheme, SecurityHandler, router};
use rust_decimal::Decimal;
struct Shipping;
impl Api for Shipping {
async fn quote_rates(&self, _ctx: RequestContext, body: RateRequest) -> QuoteRatesResponse {
// the body is decoded and validated: two addresses, at least one parcel, weights above 0
// in the units of the request
let weight: f64 = body.parcels.iter().map(|parcel| parcel.weight.value).sum();
QuoteRatesResponse::Ok(vec![Rate {
service: "dhl.express_worldwide".into(),
carrier: "dhl".into(),
total: Money { amount: Decimal::new(1290, 2), currency: "EUR".into() }, // "12.90"
transit_days: if weight > 30.0 { 3 } else { 1 },
service_name: None,
breakdown: None,
transit_time: None,
guaranteed: None,
valid_until: None,
}])
}
async fn get_shipment(
&self,
_ctx: RequestContext,
shipment_id: ShipmentId,
_params: GetShipmentParams,
) -> GetShipmentResponse {
GetShipmentResponse::NotFound(ProblemDetails {
r#type: Some("about:blank".into()),
title: Some("Not Found".into()),
status: Some(404),
detail: Some(format!("no shipment {shipment_id}")),
..ProblemDetails::default()
})
}
// ... a method per operation
}
struct Keys;
impl SecurityHandler for Keys {
async fn check(&self, _ctx: &RequestContext, _scheme: &Scheme, credentials: &Credentials, _scopes: &[&str]) -> bool {
matches!(credentials, Credentials::ApiKey(key) if key == "secret")
}
}
#[tokio::main]
async fn main() {
let app = axum::Router::new().nest("/v2", router(Arc::new(Shipping), Arc::new(Keys)));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Once it runs, a valid request reaches quote_rates, and the Decimal amount is written as a
JSON string:
curl -s -H 'X-Api-Key: secret' -H 'Content-Type: application/json' -d '{"origin":{"line1":"Hauptstr. 1","postalCode":"10115","city":"Berlin","countryCode":"DE"},"destination":{"line1":"1 Rue de Rivoli","postalCode":"75001","city":"Paris","countryCode":"FR"},"parcels":[{"weight":{"value":1.2,"unit":"kg"}}]}' localhost:8080/v2/rates
[{"service":"dhl.express_worldwide","carrier":"dhl","total":{"amount":"12.90","currency":"EUR"},"transitDays":1}]
The Api trait
Every operation is a method of Api, named after its operationId in snake case. It takes a
RequestContext, the path parameters, a struct with the query, header and cookie parameters when
the operation has any, and the body, all owned, and returns the response enum of the operation:
fn get_shipment(&self, ctx: RequestContext, shipment_id: ShipmentId, params: GetShipmentParams) -> impl Future<Output = GetShipmentResponse> + Send;
fn quote_rates(&self, ctx: RequestContext, body: RateRequest) -> impl Future<Output = QuoteRatesResponse> + Send;
The methods return impl Future + Send, so an implementation writes them as async fn,
without async-trait. Api is Send + Sync + 'static; the router holds it in an
Arc.
RequestContexthas themethod,uri,headersandextensionsof the request (connection info, values of middleware), the decoded query pairs (query()) and the media type of the body (media_type()).- The parameters struct, e.g.
GetShipmentParams, has a field per parameter, anOptionunless the parameter is required. Parameters described withcontentare read as JSON. - A body with one media type is its type (
RateRequest), anOptionwhen the body is optional. A body with several media types is an enum with a variant per media type, e.g.UpdateShipmentBody::MergePatch(ShipmentPatch)andUpdateShipmentBody::JsonPatch(JsonPatch). - JSON bodies are values of their types, JSON Lines bodies (
application/jsonl,application/x-ndjson, …)Vecs of the items of theiritemSchema,text/*bodiesString,application/x-www-form-urlencodedbodies structs read field by field with the styles of theirencoding, other media typesBytes. - Deprecated operations say so in their doc comment.
- Operations marked
x-internal: true(on the operation or its path item) are methods and routes compiled with the cargo featureinternal;internal_operationsgenerates them like the others or leaves them out.
Routing
router(api, security) returns an axum::Router with a route per path of the document, in its
order. Nest it to serve it below a path, e.g. the path of the server’s URL (/v2).
- Path parameters are read in their style (
simple,label,matrix). A segment with several parameters or with text around one (/labels/{labelId}.{extension}) is split; a request whose segment doesn’t match is answered with 404. GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONSandTRACEare routed with axum’s method filters, so axum answers a method the path doesn’t have with 405 andAllow. A path with aqueryoperation oradditionalOperations(OpenAPI 3.2, e.g.QUERY,COPY) is served by one handler that dispatches on the method, and answers the methods it doesn’t have with 405 and problem details.- Operations with servers of their own (on the operation or its path item) are routed at their path like the others.
Requests
A handler reads a request in this order, and answers the first failure with
RFC 9457 problem details (application/problem+json),
without calling the method:
- The security requirements of the operation, through the
SecurityHandler(401). - The path, query, header and cookie parameters, in their style and
explodemode (form,spaceDelimited,pipeDelimitedanddeepObjectquery parameters), and their constraints (400; 404 for a path segment that doesn’t match). - The media type of the body, against those of the document (415).
- The body, decoded and checked with
Validate(400; 413 for a body larger thanMAX_BODY_SIZE, 16 MiB).
For a body that doesn’t meet its schema, the errors member lists the failed checks with their
JSON pointers:
curl -s -H 'X-Api-Key: secret' -H 'Content-Type: application/json' -d '{"origin":{"line1":"Hauptstr. 1","postalCode":"10115","city":"Berlin","countryCode":"DE"},"destination":{"line1":"","postalCode":"75001","city":"Paris","countryCode":"FR"},"parcels":[]}' localhost:8080/v2/rates
{"type":"about:blank","title":"Bad Request","status":400,"detail":"Invalid body: /destination/line1: must be at least 1 characters long; /parcels: must have at least 1 items","errors":[{"detail":"must be at least 1 characters long","pointer":"/destination/line1"},{"detail":"must have at least 1 items","pointer":"/parcels"}]}
A parameter of the wrong type, a body of another media type and a request without credentials:
curl -s -H 'X-Api-Key: secret' 'localhost:8080/v2/shipments?limit=abc'
curl -s -H 'X-Api-Key: secret' -H 'Content-Type: text/csv' -d 'a,b' localhost:8080/v2/rates
curl -s -H 'Content-Type: application/json' -d '{}' localhost:8080/v2/rates
{"type":"about:blank","title":"Bad Request","status":400,"detail":"parameter 'limit': 'abc' isn't an integer"}
{"type":"about:blank","title":"Unsupported Media Type","status":415,"detail":"the body must be application/json"}
{"type":"about:blank","title":"Unauthorized","status":401,"detail":"the request has no valid credentials for the operation"}
Responses
A method returns an enum with a variant per documented status, which implements
axum::response::IntoResponse and writes the status, the Content-Type and the body:
pub enum GetTrackingEventsResponse {
OkJson(Vec<TrackingEvent>), // 200, application/json
OkEventStream(ItemStream<Event<TrackingEvent>>), // 200, text/event-stream
OkJsonl(ItemStream<TrackingEvent>), // 200, application/jsonl
NotFound(ProblemDetails), // 404, application/problem+json
}
- Variants are named after the reason phrase of the status (
Ok,Created,NotModified,NotFound), orStatus<code>for a status without one. A range isStatus5xx, thedefaultresponseDefault; both hold the status code first, written as 500 when it isn’t a valid one. - A status with several media types gets a variant per media type (
OkJson,OkPdf,OkEventStream,OkJsonl): the method picks one, e.g. from theAcceptheader inctx.headers. - A response without content is a variant without a value (
NoContent). - JSON bodies are written as JSON,
application/problem+jsonbodies areProblemDetailswhatever their schema,text/*bodiesString, other media typesBytes.
Streams
text/event-stream and JSON Lines responses (application/jsonl, application/x-ndjson, …)
hold an ItemStream<T>, a Pin<Box<dyn Stream<Item = T> + Send>>. Each item is written as it
arrives, until the stream ends. getTrackingEvents answers with JSON, server-sent events or JSON
Lines; this implementation sends one event:
use carpet_express::models::{ShipmentStatus, TrackingEvent};
use carpet_express::runtime::Event;
use carpet_express::server::{GetTrackingEventsParams, GetTrackingEventsResponse};
use futures::StreamExt;
impl Api for Shipping {
async fn get_tracking_events(
&self,
_ctx: RequestContext,
_shipment_id: ShipmentId,
_params: GetTrackingEventsParams,
) -> GetTrackingEventsResponse {
let event = TrackingEvent {
id: "evt_1".into(),
status: ShipmentStatus::InTransit,
occurred_at: "2026-11-04T09:30:00Z".parse().expect("an RFC 3339 time"),
description: Some("Departed the hub".into()),
carrier_status_code: None,
location: None,
estimated_delivery: None,
proof_of_delivery: None,
};
let tracking = Event { event: Some("tracking".into()), id: Some(event.id.clone()), ..Event::new(event) };
let events = futures::stream::iter([tracking]); // or the stream of a channel
GetTrackingEventsResponse::OkEventStream(events.boxed())
}
// ...
}
curl -s localhost:8080/v2/shipments/shp_8Yb2Kk1qP0wZcT3uXr5sN7aD/tracking-events
event: tracking
id: evt_1
data: {"id":"evt_1","status":"in_transit","description":"Departed the hub","occurredAt":"2026-11-04T09:30:00Z"}
- An
Event<T>has anevent, anidand aretry(milliseconds), written when they are set, and thedata, written as JSON.Tis thecontentSchemaof thedataproperty of theitemSchema(OpenAPI 3.2;x-itemSchemain 3.0 and 3.1 documents), or theitemSchemaitself without one. - JSON Lines items are written as JSON, one per line.
- Without
itemSchema, the items areserde_json::Valuevalues.
Multipart bodies
multipart/form-data bodies of object schemas are structs with a field per part, e.g.
UploadShipmentDocumentMultipartBody. Binary parts (format: binary, or contentMediaType in
3.1 and 3.2) are FilePart values with the bytes, the file name and the media type of the part,
arrays of them Vec<FilePart>. Object and array parts, and parts whose encoding has a JSON
contentType, are read as JSON and checked; other parts as text. A missing required part is
answered with 400. The parts are read in memory.
Security
The handler of an operation with security requirements finds the credentials of each scheme of
an alternative in the request, and calls the SecurityHandler with them:
pub trait SecurityHandler: Send + Sync + 'static {
fn check(&self, ctx: &RequestContext, scheme: &Scheme, credentials: &Credentials, scopes: &[&str])
-> impl Future<Output = bool> + Send;
}
| Scheme | Credentials |
|---|---|
apiKey in a header, the query or a cookie |
ApiKey(String) |
http basic |
Basic { username, password }, decoded |
http bearer, oauth2, openIdConnect |
Bearer(String), from Authorization: Bearer |
mutualTLS |
MutualTls: the application finds the client certificate in ctx.extensions |
- A request is authorized when every scheme of one alternative has credentials and
checkreturnstruefor them. Otherwise the handler answers 401; a scope check that fails is a 401 too. An operation withsecurity: [], or an empty alternative, needs no credentials. scheme.nameis the name of the scheme in the document;src/server.rshas a constant per scheme, e.g.SCHEME_API_KEY.scopesare those of the requirement.AcceptAnyCredentialsaccepts any credentials: for tests, and for applications that check them in a layer of their own.
Types
The types are those of client rust: structs with
serde derives, Option<T> for optional properties, Nullable<T> for nullable ones, enums for
string enums and for oneOf and anyOf, merged structs for allOf, and runtime::DateTime,
runtime::Date, uuid::Uuid, url::Url and rust_decimal::Decimal for the formats.
unknown_enum_values adds an Other(String) variant to string enums.
- A
stringwithformat: decimalis arust_decimal::Decimal, written as a JSON string and read from a string or a number. Anumberwithformat: decimalis anf64, a JSON number. - A
stringwithformat: binaryisbytes::Bytesas a request or response body,runtime::FilePartas a multipart part, andruntime::Base64inside a JSON value.
Validation
The types of src/models.rs implement Validate, which checks the constraints of its schema as listed for
client rust. The lengths and patterns of
decimal, uuid, uri and url values are checked on the text the crate writes for the decoded
value, not on the text of the request: "+12.90" and the JSON number 12.9 both pass the
pattern of Money.amount. The handlers check the parameters and the request bodies before they
call the methods; responses aren’t checked.
Extensions
| Extension | Effect |
|---|---|
x-rust-name |
name of the type of a schema |
x-rust-type |
Rust type of a schema, a path such as my_crate::Money, or a name type_mappings maps |
x-enum-varnames, x-enumNames |
names of the enum variants |
x-enum-descriptions |
doc comments of the enum variants |
x-apigenie.codegen.name |
name of the type of a component schema, when it has no x-rust-name |
x-apigenie.codegen.action-name |
name of the method of an operation without an operationId (with the default action_naming, which lists id first) |
x-apigenie.codegen.disabled |
true on an operation or its path item leaves the operation out |
x-internal |
true on an operation or its path item puts the operation behind the cargo feature internal (see internal_operations) |
x-defaultMapping |
defaultMapping of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn’t mapped |
x-itemSchema |
itemSchema of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a stream |
The extensions can live in an overlay for this target instead of in the document, e.g.
rust.overlay.yaml:
overlay: 1.0.0
info:
title: Rust types
version: 1.0.0
actions:
- target: $.components.schemas.Rate
update:
x-rust-name: Quote
- target: $.components.schemas.Money.properties.amount
update:
x-rust-type: my_crate::Amount
apigenie-generator server axum carpet-express.openapi-31.yaml --overlay rust.overlay.yaml -o carpet-express
Limitations
The features of the conformance fixture the server doesn’t support yet are listed under Verification. Beyond them:
- Links aren’t generated.
- A
decimal,uuidorurlvalue is validated after it is decoded: a JSON number is accepted for atype: string, format: decimalproperty, and thepatternand lengths apply to the text the crate writes (12.90, a lower-case UUID), not to the text received. - Response headers aren’t written: a variant holds the body only. Add headers with a middleware layer.
- A method returns one of the documented responses; there is no content negotiation, and responses aren’t checked against their schemas.
- Operations with servers of their own are served by the same router: the host and the path of their server aren’t checked.
- Request bodies and multipart parts are read in memory; only responses are streams.
Validatedoesn’t checkunevaluatedProperties, nor patterns using lookaround or backreferences, which the regex crate doesn’t support (a warning says so). It checksif/then/elseanddependentSchemasonly when their schemas userequiredand theconstandenumof properties, and skips the others.- Values of an
x-rust-typearen’t checked, and the generatedCargo.tomldoesn’t list the crate of the type: add the dependency after generating. - Schemas named like the prelude, serde or the runtime (
Result,Option,String,Vec,Validate, …) get numbered types, e.g.Result2, with a message saying so. - The input must be an OpenAPI 3.0, 3.1 or 3.2 document or a Swagger 2.0 document (see
Swagger 2.0 input); bundle documents
referencing other files with
apigenie bundle. An AsyncAPI document is refused with exit status 2.
Options
-c, –config
Path to the configuration file to use. See the “Configuration” section for more information.
–no-config
Doesn’t look for apigenie.yaml (or .apigenie.yaml) in the current directory and its parents
up to the root of the repository.
–overlay OVERLAY
Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the
extensions of the “Extensions” section. Can be repeated: the overlays apply in order, after those
listed under commands.generate.server_axum.overlay in the configuration file (with paths relative
to it). Warnings and errors about a value an overlay set point to the overlay.
–strict
Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated)
instead of a warning (OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.).
-o, –output
Directory where the crate is generated.
–package-name
Name of the crate in Cargo.toml. Defaults to the name of the output directory in lower case,
with _, . and spaces written as -, other characters dropped and at most 64 characters (api
when that isn’t a valid crate name).
–package-version
Version of the crate in Cargo.toml. Defaults to the info.version of the document.
-p, –property NAME=VALUE
Sets a generator option (see below), e.g. -p internal_operations=exclude. Options given on the
command line take precedence over the configuration file. Lists are comma-separated
(-p include_tags=Shipments,Rates) and mappings too (-p type_mappings=money=my_crate::Money).
–json
Prints the status of the run as one JSON document on the standard output, and nothing else there; see JSON output.
Exit status
| Status | When |
|---|---|
| 0 | The crate was generated. |
| 2 | The options, the configuration, an overlay or the input can’t be used, the output directory can’t be created, or the input is an AsyncAPI document. With --strict, also when an overlay action selects nothing. Nothing is generated. |
See the exit statuses of apigenie-generator.
Configuration
version: '1.0'
commands:
generate:
server_axum:
crate: carpet-express-server
internal_operations: include
unknown_enum_values: true
| Option | Type | Default | Description |
|---|---|---|---|
crate |
string | name of the output directory | Name of the crate in Cargo.toml: a letter, then letters, digits, - and _, at most 64 characters; also set by --package-name. |
version |
string | the document’s info.version |
Version of the crate in Cargo.toml, written as MAJOR.MINOR.PATCH from its leading numbers (v2.4 gives 2.4.0, a version without numbers 0.1.0); also set by --package-version. |
include_tags |
list of strings | Generates only the operations with one of these tags. | |
exclude_tags |
list of strings | Skips the operations with one of these tags. | |
skip_prune |
boolean | false |
Keeps the component schemas that no generated operation uses. |
internal_operations |
feature, include or exclude |
feature |
The operations marked x-internal: true (on the operation or its path): behind the cargo feature internal, generated like the others, or left out. |
unknown_enum_values |
boolean | false |
String enums get an Other(String) variant for the values the document doesn’t list. |
type_mappings |
map of strings | Rust types of string, integer and number formats or of x-rust-type names, by their paths, e.g. money: my_crate::Money. A component schema they apply to becomes an alias of the type. |
|
action_naming |
list of id, extension, url |
id, extension, url |
Where method names come from, in order of preference: the operationId, the x-apigenie action name, or the method and path. |
Verification
The codegen conformance suite runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, and Level 2 runs the language's type checker and linter; Level 3 isn't wired for this target. All targets.
This target's support tier is Experimental. It isn't run at every level yet. It is outside the 1.0 compatibility promise: its options and the shape of its output can change, or it can go away, in a minor release.
| Results | Level 1 | Level 2 | Level 3 |
|---|---|---|---|
| Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 2 not yet | ✓ pass (rustc 1.99.1 (58cf8f9c3 2026-10-13)) | not run yet |
| Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 2 not yet | runs before a release | not run yet |
Not supported yet, as the target's manifest says:
operations.callbacks(3.2, 3.1, 3.0): The server doesn't generate typed senders of callbacks yet; an application sends them with a client of its own.operations.webhooks(3.2, 3.1, 3.0): The server doesn't generate typed senders of webhooks yet; an application sends them with a client of its own.