apigenie-generator client rust

Experimental · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 not run yet · Verification

Generate a Rust client crate on reqwest 0.12 and serde from an OpenAPI document: an async method per operation, returning an enum of the documented responses.

(experimental, outside the 1.0 compatibility promise) client rust is new in 0.12.0, and the generated crate isn’t yet checked against a live API (conformance Level 3): the options and the output can still change. client rust says so in its --help and on the first line it prints, on the standard error. See the experimental commands.

Usage

apigenie-generator client rust [...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 server axum, 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 Client, ClientBuilder and Error re-exported
src/client.rs DEFAULT_BASE_URL, Client::builder(), a ClientBuilder method per security scheme, and per operation its parameters struct, its response enum and its method
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 operations marked x-internal: true, behind the cargo feature internal
src/runtime/*.rs the client, its builder and credentials, Error, parameter encoding, streams, FilePart, ProblemDetails, Nullable<T>, DateTime, Date, Base64 and validation

Cargo.toml depends on reqwest 0.12 (without its default features, with rustls-tls), serde 1, serde_json 1, futures 0.3, bytes 1, thiserror 2, time 0.3 and regex 1, and on uuid 1, url 2 and rust_decimal 1 when the document uses their formats. reqwest runs on tokio: call the client from 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). This application, which also depends on tokio (with macros and rt-multi-thread), reqwest and, for the streams, futures, gets a shipment and downloads its label:

use std::time::Duration;

use carpet_express::client::{
    GetShipmentLabelParams, GetShipmentLabelResponse, GetShipmentParams, GetShipmentResponse,
};
use carpet_express::models::{LabelFormat, Shipment};
use carpet_express::{Client, Error};

#[tokio::main]
async fn main() -> Result<(), Error> {
    let client = Client::builder() // DEFAULT_BASE_URL; Client::with_base_url(url) for another one
        .api_key(std::env::var("CARPET_EXPRESS_API_KEY").unwrap_or_default())
        .http_client(reqwest::Client::builder().timeout(Duration::from_secs(30)).build()?)
        .build()?;
    let id = "shp_8Yb2Kk1qP0wZcT3uXr5sN7aD";
    match client.get_shipment(id, &GetShipmentParams::default()).await {
        Ok(GetShipmentResponse::Ok(Shipment::ParcelShipment(parcel))) => println!("{:?}", parcel.status),
        Ok(GetShipmentResponse::Ok(other)) => println!("{other:?}"), // a pallet or freight shipment
        Ok(GetShipmentResponse::NotModified) => {}
        Ok(GetShipmentResponse::NotFound(problem)) => println!("{:?}", problem.detail), // RFC 9457
        Err(Error::UnexpectedStatus { status, .. }) => println!("status {status}"),
        Err(error) => return Err(error), // transport, encoding, decoding or credentials
    }
    let params = GetShipmentLabelParams { format: Some(LabelFormat::Pdf), ..Default::default() };
    if let GetShipmentLabelResponse::OkPdf(pdf) = client.get_shipment_label(id, &params).await? {
        std::fs::write("label.pdf", &pdf).expect("label.pdf written");
    }
    Ok(())
}

Methods

Every operation is an async method of Client, named after its operationId in snake case. It takes the path parameters, a reference to a struct with the query, header and cookie parameters when the operation has any, and the body, and returns the response enum of the operation:

pub async fn get_shipment(&self, shipment_id: &str, params: &GetShipmentParams) -> Result<GetShipmentResponse, Error>
pub async fn get_pickup(&self, pickup_id: &Uuid) -> Result<GetPickupResponse, Error>
pub async fn quote_rates(&self, body: &RateRequest) -> Result<QuoteRatesResponse, Error>
  • Path parameters are &str for strings, values for integers, numbers and booleans, and references for the other types (&Uuid, an enum).
  • The parameters struct, e.g. GetShipmentParams, has a field per parameter, an Option unless the parameter is required. It implements Default when none is required.
  • An operation with several request media types gets a method per media type, named with the media type: update_shipment_merge_patch and update_shipment_json_patch, import_shipments_csv and import_shipments_jsonl. The one for application/json keeps the bare name (put_customs_declaration, next to put_customs_declaration_xml).
  • JSON bodies are &T, checked with Validate before they are sent; an optional body is an Option<&T>. JSON Lines bodies (application/jsonl, application/x-ndjson, …) are &[T] of the items of their itemSchema, each checked. text/* bodies are &str, other media types impl Into<reqwest::Body>.
  • application/x-www-form-urlencoded bodies are structs, checked and encoded field by field with the styles of their encoding (deepObject, delimited arrays, JSON fields).
  • Parameters are written in their style and explode mode: simple, label and matrix path parameters, form, spaceDelimited, pipeDelimited and deepObject query parameters, headers and cookies. Parameters described with content are sent as JSON. The header parameters Accept, Content-Type and Authorization are ignored, as OpenAPI requires.
  • Methods set the Accept header to the media types of the documented responses.
  • The query operations and the additionalOperations of OpenAPI 3.2 are sent with their method, e.g. QUERY or COPY.
  • Deprecated operations get #[deprecated(note = "the operation is deprecated")].
  • Operations marked x-internal: true (on the operation or its path item) are methods in src/internal.rs, compiled with the cargo feature internal; internal_operations includes them in src/client.rs or leaves them out.

Responses

A method returns an enum with a variant per documented status, holding the decoded body:

pub enum GetShipmentLabelResponse {
    OkPdf(Bytes),                      // 200, application/pdf
    OkPng(Bytes),                      // 200, image/png
    OkZpl(Bytes),                      // 200, application/x-zpl
    OkJson(LabelEnvelope),             // 200, application/json
    NotFound(ProblemDetails),          // 404, application/problem+json
    // ...
}
pub enum CreateShipmentResponse {
    Created(Shipment),                 // 201
    Accepted(Job),                     // 202
    // ...
    Status5xx(u16, ProblemDetails),    // 5XX, with the status code
}
  • Variants are named after the reason phrase of the status (Ok, Created, NotModified, NotFound), or Status<code> for a status without one. A range is Status5xx, the default response Default; both hold the status code first.
  • A status with several media types gets a variant per media type (OkJson, OkPdf, OkEventStream, OkJsonl), chosen by the Content-Type of the response. A media type the document doesn’t list is read as the last one.
  • A response without content is a variant without a value (NotModified).
  • JSON bodies are decoded and checked with Validate. application/problem+json bodies are ProblemDetails (type, title, status, detail, instance, and the other members in extensions), whatever their schema. text/* bodies are String, other media types Bytes.
  • Error statuses the document describes are variants, not errors.

The Error of a method is one of:

Variant When
InvalidRequest(String) A parameter can’t be written in its style, or the body doesn’t meet the constraints of its schema. Nothing is sent.
MissingCredentials(&'static str) The client has no credentials for any alternative of the operation’s security requirements, named by the operationId. Nothing is sent.
Transport(reqwest::Error) The request couldn’t be sent or the response read.
UnexpectedStatus { status, body } The response has a status the operation doesn’t describe, and it has no default response.
InvalidResponse(String) The body isn’t JSON of its type, or doesn’t meet the constraints of its schema.

Streams

text/event-stream and JSON Lines contents (application/jsonl, application/x-ndjson, …) are EventStream<T> and JsonLinesStream<T>, which implement futures::Stream and decode the items as they arrive. T comes from the itemSchema of the media type (OpenAPI 3.2; x-itemSchema in 3.0 and 3.1 documents). getTrackingEvents answers with JSON, server-sent events or JSON Lines:

use futures::StreamExt;

let params = GetTrackingEventsParams::default();
match client.get_tracking_events(id, &params).await? {
    GetTrackingEventsResponse::OkEventStream(mut events) => {
        while let Some(event) = events.next().await {
            let event = event?; // Event<TrackingEvent>: event, id, retry, and data decoded and checked
            println!("{:?} {:?}", event.event, event.data.status);
        }
    }
    GetTrackingEventsResponse::OkJsonl(mut events) => {
        while let Some(event) = events.next().await {
            println!("{:?}", event?.status); // TrackingEvent
        }
    }
    other => println!("{other:?}"), // the history as JSON, or 404
}
  • For server-sent events, T is the contentSchema of the data property of the itemSchema, or the itemSchema itself without one. Each Event<T> has the event (None for the default type), the id last received, the retry in milliseconds, and the data lines joined and decoded as JSON. Comments and events without data are skipped.
  • JSON Lines streams yield one T per line; blank lines are skipped.
  • Without itemSchema, the items are serde_json::Value values.
  • An item that isn’t valid JSON of T, or doesn’t meet its schema, is an Err(Error::InvalidResponse); the stream goes on with the next one.

Multipart bodies

multipart/form-data bodies of object schemas are structs with a field per part, e.g. UploadShipmentDocumentMultipartBody:

let body = UploadShipmentDocumentMultipartBody {
    file: FilePart::new(std::fs::read("invoice.pdf").expect("invoice.pdf read"))
        .with_file_name("invoice.pdf")
        .with_content_type("application/pdf"),
    kind: DocumentKind::CommercialInvoice,
    metadata: None,
    thumbnails: Vec::new(),
};
let response = client.upload_shipment_document(id, &body).await?;
  • Binary parts (format: binary, or contentMediaType in 3.1 and 3.2) are FilePart values, arrays of them Vec<FilePart>. A FilePart holds the bytes, a file name and a media type. Without a media type, the part is sent with the first contentType of its encoding, or its contentMediaType, or application/octet-stream.
  • Object and array parts, and parts whose encoding has a JSON contentType, are sent as JSON; other parts as text. Optional parts that are None are left out.

The body is built in memory.

Servers

DEFAULT_BASE_URL is the URL of the first server of the document, with the default values of its variables (http://localhost without servers): https://eu.api.carpetexpress.example/v2 for Carpet Express. Client::builder() sends requests there. Client::with_base_url(url) and ClientBuilder::new(url) send them to another URL. Operations with servers of their own (on the operation or its path item) are sent to the first of them; .operation_servers(false) sends every request to the base URL instead, e.g. to a test server or a proxy.

Security

Every security scheme of the document gets a ClientBuilder method setting its credentials, named after the scheme in snake case:

Scheme (name in the document) Method
apiKey in a header, the query or a cookie (apiKey) api_key(key)
http basic (basicAuth) basic_auth(username, password)
http bearer (bearerJwt) bearer_jwt(token), sent as a bearer token
oauth2, openIdConnect (oauth2) oauth2(token), sent as a bearer token, and oauth2_tokens(provider)
mutualTLS (mutualTLS) mutual_tls(identity), a reqwest::Identity

A request gets the credentials of the first alternative of its operation’s security requirements whose schemes all have credentials. An operation with security: [], or with an empty alternative ({}), gets none. Without such an alternative, the method returns Error::MissingCredentials.

  • oauth2_tokens takes a TokenProvider, an Arc<dyn Fn() -> Result<String, Error> + Send + Sync> called for every request: a token cache of the application. Obtaining and refreshing tokens is up to the caller.
  • mutual_tls sets the identity of the reqwest client the builder creates. With http_client, configure the identity on that client instead.
  • credential(scheme, Credential) sets the credentials of a scheme by its name, and default_header(name, value) a header sent with every request.

Clones of Client share the connection pool and the credentials. Its Debug output doesn’t show credentials.

Types

Schema Rust type
string String
string, format: date-time runtime::DateTime, a time::OffsetDateTime
string, format: date runtime::Date, a time::Date
string, format: byte or contentEncoding: base64 runtime::Base64, a Vec<u8>
string, format: binary bytes::Bytes in a response, impl Into<reqwest::Body> as a request body, runtime::FilePart as a multipart part, runtime::Base64 inside a JSON value
string, format: uuid uuid::Uuid
string, format: uri or url url::Url
string, format: decimal rust_decimal::Decimal, written as a JSON string and read from a string or a number
integer i64; i32, i16, i8, u8, u16, u32, u64 for the formats int32, int16, int8, uint8, uint16, uint32, uint64 and uint
number f64, format: decimal included (a JSON number); f32 for format: float
boolean bool
array Vec<T>; a tuple, e.g. (f64, f64), for prefixItems without items
object with properties a struct
object with only additionalProperties or patternProperties BTreeMap<String, T>
a schema without a type serde_json::Value
  • Optional properties are Option<T>, left out when None. Properties that can be null are Nullable<T> (Null or Value(T)), optional ones Option<Nullable<T>>, which tells absent, null and set values apart. Required properties that are readOnly or writeOnly are Option<T>, as they are absent from requests or responses.
  • Structs are Debug, Clone, PartialEq, Serialize and Deserialize, with the JSON names kept by #[serde(rename)]. additionalProperties: false adds #[serde(deny_unknown_fields)]; a schema of additionalProperties adds an additional_properties map. Types that contain themselves hold a Box.
  • String enums are Rust enums with a variant per value (OutForDelivery for out_for_delivery), as_str() and Display. With unknown_enum_values: true, an Other(String) variant takes the values the document doesn’t list. Other enums are newtypes (pub struct Dpi(pub i64)) whose values are checked.
  • oneOf and anyOf schemas are enums with a variant per member. With a discriminator, the value goes to the variant its property selects: through the mapping or the name of the schema; other values go to the defaultMapping variant (x-defaultMapping in 3.0 and 3.1 documents), or fail to decode. Without a discriminator, a oneOf value goes to the only variant it decodes into and meets the constraints of, an anyOf value to the first one.
  • allOf schemas are merged into one struct; an anyOf or oneOf whose members only list required properties (anyOf: [{required: [email]}, {required: [phone]}]) is checked by Validate.

Validation

The types of src/models.rs implement Validate: validate() returns the ValidationErrors of the constraints of its schema, each with the JSON pointer of the value. The checks cover the lengths and patterns of strings, the bounds and multipleOf of numbers, items, unique items, properties, pattern properties, enum, if/then/else, dependentRequired and dependentSchemas, and the email, idn-email, hostname, ipv4, ipv6, time, iri, uri-reference and iri-reference formats. Values of the date-time, date, uuid, uri, url and decimal formats are checked as they are decoded into their types. The lengths and patterns of decimal, uuid, uri and url strings are checked on the text the crate writes for the value, e.g. the pattern of Money.amount on "12.90". In a response, that is the text of the decoded value, not the text the server sent. The client checks request bodies before it sends them, and response bodies and stream items after it decodes them.

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 client rust carpet-express.openapi-31.yaml --overlay rust.overlay.yaml -o carpet-express

Limitations

The features of the conformance fixture the client doesn’t support yet are listed under Verification. Beyond them:

  • Callbacks, webhooks and links aren’t generated.
  • Response headers aren’t returned: a variant holds the body only.
  • The Accept header lists every documented media type of the operation; a method can’t ask for one of them.
  • allowReserved is ignored: reserved characters in query values are percent-encoded.
  • Parameters and multipart bodies aren’t checked against their schemas before they are sent.
  • Validate doesn’t check unevaluatedProperties, nor patterns using lookaround or backreferences, which the regex crate doesn’t support (a warning says so). It checks if/then/else and dependentSchemas only when their schemas use required and the const and enum of properties, and skips the others.
  • Values of an x-rust-type aren’t checked, and the generated Cargo.toml doesn’t list the crate of the type: add the dependency after generating.
  • Server URLs are used as written: a relative URL isn’t resolved, so give an absolute base URL with Client::with_base_url, and .operation_servers(false) when the operations have relative servers.
  • Bodies are read in memory, except streams; there are no retries or rate limiting beyond what the reqwest client does.
  • 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.client_rust.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:
    client_rust:
      crate: carpet-express-client
      internal_operations: exclude
      type_mappings:
        money: my_crate::Money
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, so that new server values don’t fail decoding.
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.

ResultsLevel 1Level 2Level 3
Release 0.12.0✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 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, 0 not yetruns before a releasenot run yet
Was this helpful?