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

Introduction

reflectapi: Define your web API in Rust, generate typed TypeScript, Python and Rust clients. Serve it with Axum, Cloudflare Workers or any HTTP server.

Why reflectapi?

reflectapi was built at Partly, where Rust services are called by TypeScript web apps and by other services. With new endpoints and type changes every day, hand-written clients kept drifting from the server. Generating them through OpenAPI did not fix it: across several generators, the clients were too often incompatible with what the server actually sent, and the workarounds (patching generated code, mixing generators, going back to hand-written clients for some routes) cost more than they saved.

The problem is the route through OpenAPI, not any one generator:

  • Type information is lost. Generics, enums with data, structured errors and module namespaces have no exact OpenAPI equivalent, so they are flattened or renamed on the way out.
  • Generators must handle all of HTTP, though an API call needs only a name, an input type and an output type, its errors included.
  • OpenAPI types are constraints, not definitions. A generator has to guess which type a set of validators describes, and that guess cannot be made reliably in general.

reflectapi skips that step. Its derive macros read the Rust types and their serde attributes into its own schema with nothing lost, and the clients are generated from that schema. A generated client function has the same name, input and output as the Rust handler it calls, and a change on the server shows up as a compile error in a TypeScript or Rust client. An OpenAPI document can still be written from the schema, for documentation and tools that need one.

The full story, with a live demo, is in the talk Reflect your Rust API into the world at Rust Forge 2025 in Wellington, New Zealand.

Core Philosophy

  1. Rust code first definition of the API interface
  2. Full respect for all serde attributes
  3. Extensible at many places

Where to go next

  • New to reflectapi: the Quick Start builds an API and calls it from TypeScript in a few minutes. Then read How It Works.
  • Choosing a tool: the README lists alternatives, such as utoipa, aide and OpenAPI generators, and when each fits.
  • Building a real API: the Concepts section covers errors, types, organising and evolving an API, and testing. The Reference section lists every attribute and how each client language behaves.
  • API reference: every type and function is on docs.rs.

Quick Start

Build a small API in Rust, serve it with axum, and call it from a generated TypeScript client.

Create a project

cargo new my-api
cd my-api
cargo add reflectapi --features builder,axum
cargo add serde --features derive
cargo add serde_json
cargo add tokio --features full
cargo add axum

Installation lists the other crate features.

Define the API

Replace src/main.rs:

use reflectapi::{Builder, Input, Output};
use serde::{Deserialize, Serialize};

/// A user of the system.
#[derive(Serialize, Output)]
struct User {
    id: u32,
    name: String,
    email: String,
}

#[derive(Deserialize, Input)]
struct CreateUserRequest {
    name: String,
    email: String,
}

async fn create_user(_state: (), req: CreateUserRequest, _headers: reflectapi::Empty) -> User {
    User { id: 1, name: req.name, email: req.email }
}

async fn get_user(_state: (), id: u32, _headers: reflectapi::Empty) -> Option<User> {
    (id == 1).then(|| User {
        id: 1,
        name: "Alice".to_string(),
        email: "alice@example.com".to_string(),
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (schema, routers) = Builder::new()
        .name("User API")
        .description("A simple user management API")
        .route(create_user, |route| {
            route.name("users.create").description("Create a new user")
        })
        .route(get_user, |route| {
            route.name("users.get").description("Get a user by ID")
        })
        .build()?;

    // The schema is what clients are generated from.
    std::fs::write("reflectapi.json", serde_json::to_string_pretty(&schema)?)?;

    let app = reflectapi::axum::into_router(
        (),
        routers,
        reflectapi::axum::RouterSettings::default(),
        |_name, router| router,
    );
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    axum::serve(listener, app).await?;
    Ok(())
}
  • A type the server returns derives Serialize and Output; a type it accepts derives Deserialize and Input. A type used both ways derives all four.
  • A handler takes the application state, the request input and the request headers. reflectapi::Empty means the route reads no headers.
  • Doc comments on types and fields, and each route's description, are carried into the generated clients.

How it works explains these pieces.

Run it

cargo run

The server writes reflectapi.json and listens on port 3000. Each route is a POST to its name:

curl -X POST localhost:3000/users.get -H 'content-type: application/json' -d '1'

On the Wire describes requests and responses in full.

Generate a TypeScript client

cargo binstall reflectapi-cli   # or: cargo install reflectapi-cli
mkdir -p clients/typescript
reflectapi codegen --language typescript --schema reflectapi.json --output clients/typescript/

Call the API

import { client } from "./clients/typescript/generated";

const c = client("http://localhost:3000");

const created = await c.users.create({ name: "Bob", email: "bob@example.com" }, {});
if (created.is_ok()) {
  console.log(created.unwrap_ok());
}

The client's types follow the Rust ones: change a field in Rust, regenerate, and the TypeScript compiler points at every call that needs updating.

Next

Installation

The crate

A server that defines and serves an API with axum needs:

cargo add reflectapi --features builder,axum

Add features for the third-party types your API uses, for example --features builder,axum,chrono,uuid. Without its feature, a type such as chrono::DateTime can't be part of an Input or Output type.

FeatureEnables
builderBuilder and the routers: defining an API
axumreflectapi::axum: serving the routes with axum (implies builder)
msgpackMessagePack request and response bodies beside JSON (implies builder)
codegenreflectapi::codegen: generating clients or OpenAPI from Rust code instead of the CLI
glob (default)Builder::glob_rename_types
chrono, chrono-tzchrono dates and times, chrono_tz::Tz
uuiduuid::Uuid
urlurl::Url
rust_decimalrust_decimal::Decimal
indexmapIndexMap and IndexSet
jsonserde_json::Value as an untyped value
rtThe runtime of generated Rust clients
reqwest, reqwest-middlewareA generated Rust client calling over reqwest, or reqwest-middleware
rt-sseStreaming routes in generated Rust clients

A crate holding a generated Rust client depends on reflectapi with rt, plus reqwest to make the calls and rt-sse if the API streams. See Generated clients.

The CLI

The reflectapi CLI generates clients from a schema file:

cargo binstall reflectapi-cli   # a prebuilt binary
cargo install reflectapi-cli    # or build it

Use the CLI release that matches the reflectapi crate that wrote the schema.

The Python runtime

Generated Python clients import the reflectapi-runtime package; see Generate a Python Client.

Generate a TypeScript Client from a Rust API Served with Axum

You have a web API in Rust, served with axum, and a TypeScript frontend or service that calls it. You want the TypeScript request and response types, and the functions that call each endpoint, generated from the Rust code instead of written and kept in sync by hand.

reflectapi does this. You declare the API in Rust: serde types, async handler functions, and a reflectapi::Builder that names the routes. The builder produces a schema and the routes. reflectapi::axum::into_router turns the routes into an axum Router, and the reflectapi CLI turns the schema into a typed TypeScript client.

reflectapi does not read existing axum handlers or extractors. Handlers have reflectapi's own signature and are registered with its Builder; axum is one way to serve them. The same API can also run on Cloudflare Workers or celld, or on any other HTTP server. If you want to keep axum-native handlers and document them, see the alternatives, such as utoipa and aide.

1. Add dependencies

cargo new my-api
cd my-api
cargo add reflectapi --features builder,axum
cargo add serde --features derive
cargo add serde_json
cargo add tokio --features full
cargo add axum

2. Define types and handlers

use reflectapi::{Builder, Input, Output};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Output)]
struct User {
    id: u32,
    name: String,
    email: String,
}

#[derive(Deserialize, Input)]
struct CreateUserRequest {
    name: String,
    email: String,
}

async fn create_user(_state: (), req: CreateUserRequest, _headers: reflectapi::Empty) -> User {
    User {
        id: 1,
        name: req.name,
        email: req.email,
    }
}

async fn get_user(_state: (), id: u32, _headers: reflectapi::Empty) -> Option<User> {
    (id == 1).then(|| User {
        id: 1,
        name: "Alice".to_string(),
        email: "alice@example.com".to_string(),
    })
}
  • Types the server returns derive Serialize and Output. Types it accepts derive Deserialize and Input. A type used both ways derives all four.
  • A handler takes the application state, the request body, and a struct of request headers. reflectapi::Empty means the route reads no headers.
  • A handler can return Result<T, E> to give the route a typed error; see Errors.
  • Serde attributes (rename, tag, flatten, default and so on) are reflected, so the generated types match what goes over the wire.

3. Build the schema and serve it with axum

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let builder = Builder::new()
        .name("User API")
        .description("A simple user management API")
        .route(create_user, |route| {
            route.name("users.create").description("Create a new user")
        })
        .route(get_user, |route| {
            route.name("users.get").description("Get a user by ID")
        });

    let (schema, routers) = builder.build()?;

    // The schema is the input to client generation.
    std::fs::write("reflectapi.json", serde_json::to_string_pretty(&schema)?)?;

    let app = reflectapi::axum::into_router(
        (),
        routers,
        reflectapi::axum::RouterSettings::default(),
        |_name, router| router,
    );

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    axum::serve(listener, app).await?;
    Ok(())
}
cargo run

Each route is served at POST /{name}: here POST /users.create and POST /users.get. The last argument of into_router is where to add tower middleware. Serving with axum covers routing, state, middleware and streaming.

4. Generate the TypeScript client

cargo install reflectapi-cli
mkdir -p clients/typescript
reflectapi codegen --language typescript --schema reflectapi.json --output clients/typescript/

This writes two files:

  • generated.ts: the request and response types and the client(base) function.
  • generated.transport.ts: the transport interface, for custom transports.

The files import nothing but each other. The default transport uses the global fetch, so it runs in browsers and in current Node.js.

5. Call the API from TypeScript

import { client } from "./clients/typescript/generated";

const c = client("http://localhost:3000");

// Each method takes the typed input and the typed request headers.
const created = await c.users.create(
  { name: "Bob", email: "bob@example.com" },
  {},
);
if (created.is_ok()) {
  console.log(created.unwrap_ok());
}

const user = (await c.users.get(1, {})).unwrap_ok();
console.log(user?.name);

A call returns a result instead of throwing: is_ok(), unwrap_ok(), and an Err that separates the route's typed error from network and server failures. See Generated Clients for errors, response headers, streaming and custom transports.

Keep the client in sync

Regenerate the client whenever the API changes. A common setup commits the schema and the generated files, and has CI regenerate them and fail on a difference, so an API change cannot merge without its client. See Generate the schema and clients at build time for doing this from a test, and build modes for building only the routes in the server binary.

The same schema also produces a Python client, a Rust client and an OpenAPI document; see Generated Clients.

Generate a Python Client from a Rust API

You have a web API written in Rust and Python code that calls it: scripts, tests, data jobs or another service. You want typed Python models and client methods generated from the Rust code, so the Python side does not hand-write request payloads and parse untyped JSON.

reflectapi does this. You declare the API in Rust with serde types, async handler functions and a reflectapi::Builder. The builder produces a schema, and the reflectapi CLI generates a Python package from it: Pydantic models for the request and response types, and an async client (optionally a sync one too) built on httpx.

Python output is stable, like the TypeScript and Rust clients; see Supported Outputs.

1. Define the API in Rust

use reflectapi::{Builder, Input, Output};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Output)]
struct User {
    id: u32,
    name: String,
    email: String,
}

#[derive(Deserialize, Input)]
struct CreateUserRequest {
    name: String,
    email: String,
}

async fn create_user(_state: (), req: CreateUserRequest, _headers: reflectapi::Empty) -> User {
    User {
        id: 1,
        name: req.name,
        email: req.email,
    }
}

async fn get_user(_state: (), id: u32, _headers: reflectapi::Empty) -> Option<User> {
    (id == 1).then(|| User {
        id: 1,
        name: "Alice".to_string(),
        email: "alice@example.com".to_string(),
    })
}

fn api() -> Builder<()> {
    Builder::new()
        .name("User API")
        .route(create_user, |route| route.name("users.create"))
        .route(get_user, |route| route.name("users.get"))
}

build() returns the schema and the routes. Write the schema to a file for client generation:

let (schema, routers) = api().build()?;
std::fs::write("reflectapi.json", serde_json::to_string_pretty(&schema)?)?;

Serve routers with axum, Cloudflare Workers or celld, or any other HTTP server. The TypeScript guide has a complete axum server.

2. Generate the Python client

cargo install reflectapi-cli
mkdir -p clients/python
reflectapi codegen \
  --language python \
  --schema reflectapi.json \
  --output clients/python/api_client/ \
  --python-sync

The output directory is a Python package named api_client. It contains the clients (AsyncClient always, Client with --python-sync) and a module for each Rust namespace of the reflected types. For a crate named my-api, the models above are in api_client.my_api. See Generated Clients for the full layout.

3. Install the runtime

Generated code imports reflectapi_runtime. Install the reflectapi-runtime release that matches the CLI that generated the client. It needs Python 3.12 or later.

pip install reflectapi-runtime

Make the generated api_client package importable: put it on the import path, or package it as part of your project.

4. Call the API

Async:

import asyncio

from api_client import AsyncClient
from api_client.my_api import CreateUserRequest


async def main() -> None:
    async with AsyncClient("http://localhost:3000") as client:
        created = await client.users.create(
            CreateUserRequest(name="Bob", email="bob@example.com")
        )
        print(created.value)

        found = await client.users.get(1)
        print(found.value)


asyncio.run(main())

Sync, when generated with --python-sync:

from api_client import Client
from api_client.my_api import CreateUserRequest

with Client("http://localhost:3000") as client:
    created = client.users.create(CreateUserRequest(name="Bob", email="bob@example.com"))
    print(created.value.name)

Each method returns an ApiResponse whose value is the validated response model. A 4xx or 5xx response raises ApplicationError, which carries the route's typed error when it declares one. Transport failures raise NetworkError or TimeoutError, and a response that does not match the model raises ValidationError. All four are exported by reflectapi_runtime.

Details worth knowing

How It Works

reflectapi treats an API as a set of named calls. Each call has:

  • a name, such as users.get;
  • an input: the request body;
  • an output: the response body;
  • an error: the response body when the call fails, sent with an HTTP status the error chooses;
  • headers: the request headers the call reads.

Everything else follows from these five. The URL path is the name, the method is POST, and the status says whether the body is the output or the error (On the Wire has the details). A generated client needs no more than that, so each route becomes a typed function: client.users.get(input, headers), returning the output or the error.

The flow

flowchart TD
  types["Types<br/>#35;[derive(Input, Output)]"] --> route["Builder::route"]
  handlers["Handlers<br/>async fn(state, input, headers)"] --> route
  route --> build[".build()"]
  build --> schema["Schema<br/>reflectapi.json"]
  build --> routers["Routers<br/>Vec#lt;Router#lt;S#gt;#gt;"]
  schema --> codegen["reflectapi codegen CLI<br/>or reflectapi::codegen"]
  codegen --> clients["TypeScript, Rust and Python clients<br/>OpenAPI document"]
  routers --> adapter["reflectapi::axum::into_router<br/>or reflectapi::dispatch::Dispatcher"]
  adapter --> server["HTTP server"]
  clients -. "call over HTTP" .-> server

One definition produces both sides: the schema, from which the clients are generated, and the routers that serve the routes. Both come from the same Rust types and handlers, so a client generated from the current schema matches the server.

Types

A type the server reads (a request body or request headers) derives Input next to serde's Deserialize. A type it writes (a response, an error, a stream item or response headers) derives Output next to Serialize. A type used both ways derives all four.

The derives read serde's attributes (rename, tag, flatten, default, skip_serializing_if and the rest), so the schema describes what serde actually reads and writes. Doc comments on types, fields and variants are carried into the generated clients.

A type is reflected separately as input and as output, because serde can treat the two directions differently. A field with #[serde(default)] is optional in a request; a field with #[serde(skip_serializing_if = "...")] may be missing from a response. The Attributes reference lists what reflectapi adds on top of serde.

Primitives, String, Option, Vec, maps, tuples and many library types (chrono, uuid, url and others, behind crate features) already implement both traits. reflectapi::Empty stands for "nothing": no input, no headers or no output. Types covers what can cross the API and how to bring in a type reflectapi doesn't know.

Handlers

A handler is an async function of three arguments:

#![allow(unused)]
fn main() {
type S = ();
type I = reflectapi::Empty;
type H = reflectapi::Empty;
type R = reflectapi::Empty;
async fn handler(state: S, input: I, headers: H) -> R
{ reflectapi::Empty {} }
}
  • state is the application state, cloned into every call. Make it cheap to clone, such as an Arc.
  • input is the deserialized request body.
  • headers is a struct whose fields are the request headers the route reads, named by their serde names, in lowercase. Use reflectapi::Empty for none. See Request Headers.
  • R is either the output, for a route that cannot fail, or Result<Output, Error>. These are the two forms IntoResult accepts. The error type implements StatusCode, which gives the HTTP status of its response. See Errors.

The handler must be Copy, Send and Sync, and its future Send: an async fn item works, as does a closure that captures nothing. Anything else it needs comes in through state.

A stream route's handler has the same arguments and returns Result<impl Stream<Item = T>, Error>. It is registered with Builder::stream_route and served as Server-Sent Events (Streaming Endpoints).

The builder

Builder collects the routes. Each route call takes a handler and a function that configures it through a RouteBuilder: its name, description, whether it is readonly, its tags and its deprecation. The configuration function is a plain fn, so its closure cannot capture variables.

#![allow(unused)]
fn main() {
use reflectapi::{Builder, Empty, Input, Output};
use serde::{Deserialize, Serialize};

/// A user of the system.
#[derive(Serialize, Output)]
struct User {
    id: u32,
    name: String,
}

#[derive(Deserialize, Input)]
struct GetUserRequest {
    id: u32,
}

#[derive(Serialize, Output, reflectapi::StatusCode)]
enum GetUserError {
    /// No user has this id.
    #[reflectapi(status = 404)]
    NotFound,
}

#[derive(Deserialize, Input)]
struct AuthHeaders {
    authorization: String,
}

async fn get_user(
    _state: (),
    request: GetUserRequest,
    _headers: AuthHeaders,
) -> Result<User, GetUserError> {
    match request.id {
        1 => Ok(User { id: 1, name: "Alice".into() }),
        _ => Err(GetUserError::NotFound),
    }
}

async fn health_check(_state: (), _input: Empty, _headers: Empty) -> Empty {
    Empty {}
}

let (schema, routers) = Builder::new()
    .name("Users")
    .route(get_user, |b| {
        b.name("users.get")
            .description("Get a user by id")
            .readonly(true)
    })
    .route(health_check, |b| b.name("health.check"))
    .build()
    .expect("a valid API");

let names: Vec<&str> = schema.functions().map(|f| f.name()).collect();
assert_eq!(names, ["users.get", "health.check"]);

let get = schema.functions().next().unwrap();
assert!(get.readonly());
assert!(get.error_type.is_some());
assert!(get.input_headers().is_some());

// A route that can't fail has no error type, and `Empty` is no input.
let health = schema.functions().nth(1).unwrap();
assert!(health.error_type.is_none());
assert!(health.input_type().is_none());

// One router per builder; `extend` and `nest` add more.
assert_eq!(routers.len(), 1);
}

build() checks the definition and returns the schema and the routers, or every problem it found as BuildErrors. A server that doesn't need the schema at runtime can build the routers alone; see build modes.

A readonly route is served on GET as well as POST. The schema records the flag, but the generated clients call every route with POST.

A larger API is split across several builders, combined with Builder::nest and Builder::extend, and can sit under a base path set with Builder::path, which applies to the routes added after it. See Organising a Larger API.

Names become namespaces

The route name is both the URL path and the client function. Dots split it into namespaces: users.get is client.users.get(...) in TypeScript, Python and Rust, and admin.users.get nests one level deeper. A - in a name becomes _ in the clients, so pets.get-first is client.pets.get_first(...).

The schema

The schema is the API without the code: the routes, with their names, descriptions and flags, and every type they use. It serializes to JSON, and is usually written to a reflectapi.json file:

fn main() -> Result<(), Box<dyn std::error::Error>> {
let (schema, _) = reflectapi::Builder::<()>::new().build()?;
std::fs::write("reflectapi.json", serde_json::to_string_pretty(&schema)?)?;
Ok(())
}

The reflectapi CLI generates clients from that file:

reflectapi codegen --language typescript --schema reflectapi.json --output clients/typescript/

The same generators are available in Rust as reflectapi::codegen, behind the codegen feature, for generating clients from a build step or a test without the CLI (example). Generated Clients describes each language's output, and Keep the client in sync how to check the generated files in CI.

Serving

The routers are framework-independent. An adapter puts them on an HTTP server:

All of them serve the same wire format.

On the Wire

This page shows the HTTP requests and responses of a reflectapi API: enough to call it with curl, write a client by hand, configure a proxy in front of it, or debug what a generated client sends. The examples are captured from the demo server in reflectapi-demo, with the date and content-length headers left out.

The axum adapter and reflectapi::dispatch::Dispatcher answer the same way. To serve the API from another HTTP server, see the contract an integration implements.

Requests

URL

A route is at {path}/{name}. The name is the route's full name, dots included. The path is empty unless one is set: with Builder::path for every route of a builder, which Builder::nest prepends to the routes of the builders nested in it, or with RouteBuilder::path for one route. So pets.create is at /pets.create, and under Builder::path("/api") at /api/pets.create.

A query string is ignored: the input comes from the body only.

Method

Every route accepts POST. A route marked readonly(true) accepts GET as well, and with axum HEAD, which returns the GET response's status and headers without a body. The generated clients always use POST.

Another method gets 405 Method Not Allowed with an empty body and an allow header. A path with no route gets 404 from axum.

$ curl -i -X GET localhost:3000/pets.create
HTTP/1.1 405 Method Not Allowed
allow: POST

$ curl -i -X PUT localhost:3000/pets.list
HTTP/1.1 405 Method Not Allowed
allow: GET,HEAD,POST

Dispatcher doesn't answer HEAD: it gets 405, with allow: GET,POST for a readonly route. See the contract.

Body

The body is the route's input, serialized by serde. An empty body is read as an empty object, {}, so a GET without a body works for a route whose input is reflectapi::Empty or a struct whose fields all have defaults. A GET with a body is read like a POST.

Content type

The content-type header picks the format of the request body, and the response uses the same one:

content-typeFormat
application/json, or no content-typeJSON
application/msgpackMessagePack, with the msgpack feature. Structs are maps keyed by field name.
anything else415 Unsupported Media Type

A charset parameter other than utf-8 is also refused with 415. accept is ignored. Stream routes accept JSON only, and answer MessagePack with 415. The generated clients send JSON.

curl -d sends content-type: application/x-www-form-urlencoded unless told otherwise, so pass the JSON content type:

$ curl -i localhost:3000/pets.create -H 'authorization: password' \
    -d '{"name":"Bobby","kind":{"type":"dog","breed":"Labrador"}}'
HTTP/1.1 415 Unsupported Media Type

unsupported content-type: application/x-www-form-urlencoded

Headers

A route reads the request headers named by the fields of its headers type, by their serde names (Request Headers). Name them in lowercase: HTTP header names are case-insensitive, and reflectapi matches the lowercase form.

  • A field that is not an Option is a required header. Without it, the request is refused with 400 before the handler runs.
  • Each value is passed to the field's type as a string, so a field must be a string on the wire: String, a unit-variant enum, or a type such as uuid::Uuid or chrono::DateTime. A number or bool field fails with 400 whenever its header is sent.
  • If a header appears more than once, the first value is read.
  • The handler is given only the headers it declares. Others, such as cookies or a proxy's headers, are dropped before it runs.

Responses

Success

A successful call is 200 OK, with the output serialized in the request's format. reflectapi::Empty is {}, and an Option output that is None is null.

$ curl -i localhost:3000/pets.create -H 'content-type: application/json' \
    -H 'authorization: password' \
    -d '{"name":"Bobby","kind":{"type":"dog","breed":"Labrador"}}'
HTTP/1.1 200 OK
content-type: application/json

{}

$ curl -i localhost:3000/pets.list -H 'authorization: password'
HTTP/1.1 200 OK
content-type: application/json

{"items":[{"name":"Bobby","kind":{"type":"dog","breed":"Labrador"},"updated_at":"2024-01-01T00:00:00Z"}],"cursor":"255"}

The second request is a GET: pets.list is readonly, and its input's fields are all optional.

The route's error

When the handler returns Err, the response has the status the error's StatusCode implementation gives, and the error serialized in the request's format, as serde writes it:

$ curl -i localhost:3000/pets.create -H 'content-type: application/json' \
    -H 'authorization: password' \
    -d '{"name":"Bobby","kind":{"type":"dog","breed":"Labrador"}}'
HTTP/1.1 409 Conflict
content-type: application/json

"Conflict"

$ curl -i localhost:3000/pets.create -H 'content-type: application/json' \
    -H 'authorization: password' -d '{"name":"","kind":{"type":"bird"}}'
HTTP/1.1 422 Unprocessable Entity
content-type: application/json

{"InvalidIdentity":{"message":"Name is required"}}

The error can add response headers, such as retry-after, with StatusCode::response_headers. They cannot replace content-type or traceparent. An error that says 200 is sent as 500, since a client would otherwise read it as the output.

The status tells a client which type the body has: a 2xx body is the output, and an error status means the body may be the route's error. It may also come from reflectapi itself or from a proxy, so clients check that it decodes. The TypeScript and Rust clients treat any 5xx as a server failure rather than the route's error; the Python client tries to decode the route's error for every status from 400 up, 5xx included. Errors covers choosing statuses and how each client exposes them.

Statuses reflectapi sends

Some responses come from reflectapi itself, before or after the handler. Their body is a plain-text message for people, not the route's error type:

StatusWhenBody
400 Bad RequestThe body or the headers could not be deserialized into the route's typesFailed to parse request body: ... or Failed to parse request headers: ..., with no content-type
404 Not FoundNo route has the path (axum)empty
405 Method Not AllowedThe route exists but does not accept the methodempty, with an allow header
415 Unsupported Media TypeThe content type or charset isn't supported, or a stream route got MessagePackthe reason, with no content-type, or text/plain for a stream route
500 Internal Server ErrorThe output or the error failed to serializetext/plain
$ curl -i localhost:3000/pets.create -H 'content-type: application/json' \
    -H 'authorization: password' -d '{"name":"x"}'
HTTP/1.1 400 Bad Request

Failed to parse request body: missing field `kind` at line 1 column 12, received: b"{\"name\":\"x\"}"

$ curl -i localhost:3000/pets.list -H 'content-type: application/json' -d '{}'
HTTP/1.1 400 Bad Request

Failed to parse request headers: missing field `authorization`

The 400 message includes the request body as received.

These are why a route's error can't use 400, 405 or 415 when it derives StatusCode: a client couldn't tell the route's answer from reflectapi's (see A route's error). Servers and proxies in front of the API add their own, such as 413 for a body that is too large or 502 from a gateway.

Response headers

reflectapi sets:

  • content-type, the request's format, on a success or the route's error;
  • traceparent, copied from the request when it has one, on a success or the route's error (not on a stream that opened);
  • the headers of the route's error, if any.

Headers declared with Builder::response_headers are a description for clients, not something reflectapi sends: they come from the error's response_headers, from middleware, or from infrastructure in front of the server (Response Headers). content-length and other transport headers are the HTTP server's.

Streams

A stream route is called like any other: POST (or GET if readonly), a JSON body and its headers. If the handler returns an error, the response is that error, as for any route. Otherwise the response is 200 OK with content-type: text/event-stream and cache-control: no-cache, and its body is a stream of Server-Sent Events:

$ curl -i -N localhost:3000/pets.cdc-events -H 'authorization: password'
HTTP/1.1 200 OK
content-type: text/event-stream
cache-control: no-cache
transfer-encoding: chunked

data: {"name":"Max","kind":{"type":"cat","lives":9},"updated_at":"2024-01-01T00:00:00Z"}

data: {"name":"Max","kind":{"type":"cat","lives":9},"age":3,"updated_at":"2024-01-01T00:00:00Z"}

  • Each item is one event: a data: line with the item as JSON, then a blank line. There is no event: or retry: field.
  • An item the handler wraps in reflectapi::Event has an id: line before its data. A route can declare the last-event-id request header to resume after the last id a client saw (Streaming Endpoints).
  • With keep-alive on, a stream that has sent nothing for the interval gets a comment, a line with only :, then a blank line (Keep idle streams open).
  • There is no end-of-stream event: the stream ends when the response ends. An item that fails to serialize ends it too.

reflectapi::dispatch::sse_event writes one event:

#![allow(unused)]
fn main() {
use reflectapi::{dispatch::sse_event, Event};

let item = r#"{"name":"Max"}"#.to_string();
assert_eq!(sse_event(&Event { id: None, data: item.clone() }), "data: {\"name\":\"Max\"}\n\n");
assert_eq!(sse_event(&Event::new(7, item)), "id: 7\ndata: {\"name\":\"Max\"}\n\n");
}

A stream can't be served as MessagePack, and the schema describes only the item type: the event ids and the comments are not part of it.

Check it in-process

Dispatcher answers exactly as the axum adapter does, so a test can check a route's wire behaviour without a server:

use http::{HeaderMap, Method, StatusCode};
use reflectapi::dispatch::{Dispatcher, Reply};
use reflectapi::{Builder, Empty, Input, Output};

#[derive(serde::Deserialize, Input)]
struct ListRequest {
    #[serde(default)]
    limit: Option<u8>,
}

#[derive(serde::Serialize, Output)]
struct Page {
    items: Vec<String>,
}

async fn list(_state: (), request: ListRequest, _headers: Empty) -> Page {
    let items = vec!["Bobby".to_string(), "Max".to_string()];
    let limit = request.limit.unwrap_or(u8::MAX) as usize;
    Page { items: items.into_iter().take(limit).collect() }
}

/// Sends one request and returns the status, the `content-type` or `allow`
/// header, and the body.
async fn call(
    dispatcher: &Dispatcher<()>,
    method: Method,
    path: &str,
    content_type: &str,
    body: &str,
) -> (StatusCode, String, String) {
    let mut headers = HeaderMap::new();
    headers.insert("content-type", content_type.parse().unwrap());
    let Some(Reply::Complete { status, headers, body }) = dispatcher
        .dispatch((), &method, path, &headers, body.to_owned().into())
        .await
    else {
        panic!("not a complete reply");
    };
    let header = headers
        .get("content-type")
        .or(headers.get("allow"))
        .map(|value| value.to_str().unwrap().to_owned())
        .unwrap_or_default();
    (status, header, String::from_utf8(body.to_vec()).unwrap())
}

#[tokio::main]
async fn main() {
    let (_schema, routers) = Builder::new()
        .path("/api")
        .route(list, |b| b.name("pets.list").readonly(true))
        .build()
        .unwrap();
    let dispatcher = Dispatcher::new(routers);
    let json = "application/json";

    assert_eq!(
        call(&dispatcher, Method::POST, "/api/pets.list", json, r#"{"limit":1}"#).await,
        (StatusCode::OK, json.into(), r#"{"items":["Bobby"]}"#.into()),
    );
    // A readonly route answers GET; no body reads as `{}`.
    assert_eq!(
        call(&dispatcher, Method::GET, "/api/pets.list", json, "").await,
        (StatusCode::OK, json.into(), r#"{"items":["Bobby","Max"]}"#.into()),
    );
    assert_eq!(
        call(&dispatcher, Method::DELETE, "/api/pets.list", json, "").await,
        (StatusCode::METHOD_NOT_ALLOWED, "GET,POST".into(), "".into()),
    );
    let (status, _, _) = call(&dispatcher, Method::POST, "/api/pets.list", json, "[").await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    let (status, _, _) = call(&dispatcher, Method::POST, "/api/pets.list", "text/plain", "").await;
    assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
    // No route at this path: the server's own 404, or its other routes.
    assert!(dispatcher
        .dispatch((), &Method::POST, "/pets.list", &HeaderMap::new(), Default::default())
        .await
        .is_none());
}

Errors

A route's errors are part of its type, like its input and output. A handler returns Result<O, E>; E is reflected into the schema, and every generated client gives the caller E as a typed value, kept apart from network and server failures.

A route's error

The error type derives Serialize and Output, like any type the server returns, and implements StatusCode, which gives the HTTP status of its response. For an enum, derive it and give each variant its status:

use reflectapi::{Builder, Input, Output, StatusCode};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Input)]
struct PetsCreateRequest {
    name: String,
}

#[derive(Serialize, Output)]
struct Pet {
    name: String,
}

#[derive(Serialize, Output, StatusCode)]
enum PetsCreateError {
    /// A pet of that name exists.
    #[reflectapi(status = 409)]
    Conflict { name: String },
    /// The name is empty.
    #[reflectapi(status = 422)]
    InvalidName,
    /// A failure the client can't act on.
    #[reflectapi(output_skip, status = 500)]
    InternalError,
}

async fn pets_create(
    _state: (),
    request: PetsCreateRequest,
    _headers: reflectapi::Empty,
) -> Result<Pet, PetsCreateError> {
    if request.name.is_empty() {
        return Err(PetsCreateError::InvalidName);
    }
    if request.name == "Rex" {
        return Err(PetsCreateError::Conflict { name: request.name });
    }
    Ok(Pet { name: request.name })
}

fn main() -> Result<(), reflectapi::BuildErrors> {
let (schema, _routers) = Builder::new()
    .route(pets_create, |b| b.name("pets.create"))
    .build()?;

// The route's error type is in the schema, without `InternalError`.
let function = schema.functions().next().unwrap();
let error_type = function.error_type.as_ref().unwrap().name();
let error = schema.output_types().get_type(error_type).unwrap();
let variants: Vec<_> = error.as_enum().unwrap().variants().map(|v| v.name()).collect();
assert_eq!(variants, ["Conflict", "InvalidName"]);
Ok(())
}
  • The response body is the error serialized by serde, as a successful output is: {"Conflict":{"name":"Rex"}}, or "InvalidName".
  • #[reflectapi(transparent)] on a variant with one field answers with that field's status and headers, for an error type shared by several routes.
  • StatusCode::response_headers adds headers to the error's response, such as retry-after.
  • A struct error, or any type the derive doesn't fit, implements StatusCode by hand.

The derive refuses, as it compiles, a status that a client would not read as the route's error: 1xx to 3xx; the 4xx that reflectapi or the server send themselves, such as 400; and every 5xx, except 500 on a variant named InternalError that is output_skip. A client takes any 5xx as the server's failure, so InternalError is left out of the schema: the server can still return it, and clients see it as a server failure, not a typed error. A route's error has the full rules and an example of transparent with response_headers. A hand-written impl StatusCode isn't checked; if it gives 200, reflectapi answers 500 instead.

Routes that can't fail

A handler that returns its output directly, not a Result, has no error type. So does one that returns Result<O, reflectapi::Infallible>. Neither has an error_type in the schema:

use reflectapi::{Builder, Empty, Infallible};

async fn health(_: (), _: Empty, _: Empty) -> Empty {
    Empty {}
}

async fn version(_: (), _: Empty, _: Empty) -> Result<String, Infallible> {
    Ok("1.0.0".into())
}

fn main() -> Result<(), reflectapi::BuildErrors> {
let (schema, _) = Builder::new()
    .route(health, |b| b.name("health"))
    .route(version, |b| b.name("version"))
    .build()?;
assert!(schema.functions().all(|f| f.error_type.is_none()));
Ok(())
}

Use reflectapi::Infallible, not std::convert::Infallible, which doesn't implement StatusCode. The clients of such a route still report network and server failures, the same way as for other routes.

Errors reflectapi returns

Some responses come from reflectapi, not the handler: 400 for a body or headers that don't deserialize into the route's types, 405 for a method the route doesn't take, 415 for a content type it doesn't speak, and 500 for an output or error that fails to serialize. Their body is a plain-text message, not the route's error type, so clients report them as failures, not typed errors. Statuses reflectapi sends lists them with their bodies.

In the generated clients

Each client keeps the route's typed error apart from other failures: no response, a 5xx, or a body that isn't the expected type. The examples use the error above.

TypeScript

A call returns a CallResult, which doesn't throw. On failure it holds an Err: err() is the route's error, or undefined when the failure is something else, which other_err() then holds.

import { client, match } from "./generated";

const c = client("http://localhost:3000");
const result = await c.pets.create({ name: "Rex" }, {});
if (result.is_ok()) {
  console.log(result.unwrap_ok().name);
} else {
  const err = result.unwrap_err();
  const routeError = err.err();
  if (routeError === undefined) {
    // no response, a 5xx, or a body that isn't JSON
    console.error(err.status_code(), err.other_err());
  } else {
    console.log(
      match(routeError, {
        Conflict: ({ name }) => `${name} exists`,
        InvalidName: () => "give the pet a name",
      }),
    );
  }
}

match takes one handler per variant of an externally tagged enum (serde's default). For an internally tagged error, #[serde(tag = "kind")], switch on routeError.kind instead.

Any 4xx with a JSON body is taken as the route's error, and its shape isn't checked (except for open enums), so a JSON error from a proxy in front of the server arrives in err() as well; status_code() tells which response it was. See Client Libraries for the rest of Result and Err, and for reading them in a query library's retry callback.

Rust

A generated method returns Result<O, reflectapi::rt::Error<E, C::Error>> (rt::Error), where E is the generated error type and C::Error is the transport's error, reqwest::Error for the built-in transport:

use reflectapi::rt::Error;
mod types {
    // As generated from the server's `PetsCreateError`.
    #[derive(Debug, serde::Deserialize)]
    pub enum PetsCreateError {
        Conflict { name: String },
        InvalidName,
    }
}
use types::PetsCreateError;

fn describe(error: Error<PetsCreateError, reqwest::Error>) -> String {
    match error {
        Error::Application(PetsCreateError::Conflict { name }) => format!("{name} exists"),
        Error::Application(PetsCreateError::InvalidName) => "give the pet a name".into(),
        Error::Network(error) => format!("no response: {error}"),
        Error::Protocol { info, stage } => format!("unexpected response: {info} ({stage})"),
        Error::Server(status, _body) => format!("server failed with {status}"),
    }
}

fn main() {
assert_eq!(
    describe(Error::Application(PetsCreateError::InvalidName)),
    "give the pet a name",
);
}
  • Application: a non-5xx response whose body deserializes into E.
  • Network: the transport failed; there is no response.
  • Protocol: the request couldn't be serialized, or a response couldn't be decoded, including a 4xx whose body isn't E, such as reflectapi's 400.
  • Server: a 5xx, with its status and body.

Python

A call returns an ApiResponse, whose value is the output. Failures raise exceptions from reflectapi_runtime, all subclasses of ApiError:

from reflectapi_runtime import ApplicationError, NetworkError, ValidationError

from api_client.my_api import PetsCreateErrorConflictVariant, PetsCreateRequest

try:
    response = await client.pets.create(PetsCreateRequest(name="Rex"))
    print(response.value.name)
except ApplicationError as e:
    error = e.typed_error  # a PetsCreateError, or None
    if error is None:
        print("request failed:", e.status_code, e.error_data)
    elif isinstance(error.root, PetsCreateErrorConflictVariant):
        print(f"{error.root.name} exists")
    elif error.root == "InvalidName":
        print("give the pet a name")
    else:
        print("unexpected error:", error.root)
except NetworkError as e:  # TimeoutError is a NetworkError
    print("no response:", e)
except ValidationError as e:
    print("unexpected response:", e)
  • ApplicationError: any response with status 400 or above, 5xx included. typed_error is the body validated into the route's error model, or None when it doesn't validate; error_data is the parsed JSON body, or None when it isn't JSON.
  • NetworkError and its subclass TimeoutError: no response.
  • ValidationError: a successful response whose body doesn't match the output model.

The error model is a Pydantic RootModel: its root is the variant, a string for a unit variant or a generated model for one with fields.

Adding a variant

Adding a variant to a route's error changes its generated type. In TypeScript and Rust, code that handles every variant stops compiling when the client is regenerated, and points at each place that needs the new case. Say the server adds #[reflectapi(status = 404)] OwnerNotFound to PetsCreateError. The TypeScript match above fails to type-check:

error TS2345: Argument of type '{ Conflict: ...; InvalidName: ...; }' is not
assignable to parameter of type ...
  Property 'OwnerNotFound' is missing in type '{ Conflict: ...; InvalidName: ...; }'

and the Rust match fails with error[E0004]: non-exhaustive patterns, naming the Error::Application(PetsCreateError::OwnerNotFound) case. Python has no such check: keep a branch for variants you don't handle.

Clients built before the change don't know the new variant. When the server returns it, a Rust client reports a Protocol error, a Python client an ApplicationError with typed_error set to None, and a TypeScript match throws. To let clients that are already deployed receive variants added later, mark the error enum #[reflectapi(open)]. Evolving an API covers which changes are safe for deployed clients.

Types

A type can cross the API when it implements Input, for values the server reads, or Output, for values it writes. Your own types derive them next to serde's derives. reflectapi implements them for the standard types below and, behind crate features, for common library types. This page covers what can be used, how it appears in the generated clients, and what to do with a type reflectapi doesn't know.

Your own types

Structs and enums derive Input, Output or both. The derives read serde's attributes, so the schema describes the JSON serde reads and writes.

mod model {
    use serde::Serialize;

    /// One page of a list.
    #[derive(Serialize, reflectapi::Output)]
    pub struct Page<T> {
        pub items: Vec<T>,
        pub next_cursor: Option<String>,
    }

    #[derive(Serialize, reflectapi::Output)]
    pub struct Pet {
        pub name: String,
    }
}

async fn pets_list(
    _: (),
    _: reflectapi::Empty,
    _: reflectapi::Empty,
) -> model::Page<model::Pet> {
    model::Page { items: vec![], next_cursor: None }
}

fn main() -> Result<(), reflectapi::BuildErrors> {
let (schema, _) = reflectapi::Builder::new()
    .route(pets_list, |b| b.name("pets.list"))
    .build()?;

// Types are named by their Rust module path.
let page = schema
    .output_types()
    .types()
    .find(|t| t.name().ends_with("::model::Page"))
    .unwrap();
assert_eq!(page.parameters().map(|p| p.name()).collect::<Vec<_>>(), ["T"]);
Ok(())
}
  • Generic types stay generic: the clients get Page<T> (Page[T] in Python), used as Page<Pet>. The derive bounds each type parameter by Input or Output. It doesn't support lifetime or const generic parameters.
  • A type's name in the schema is its Rust module path and name, such as my_api::model::Pet. The module path becomes a namespace in each client: my_api.model.Pet in TypeScript, types::my_api::model::Pet in Rust and the api_client.my_api.model package in Python. Organising a Larger API shows how to rename them.
  • Doc comments on types, fields and variants are carried into the clients.

Standard types

RustTypeScript
u8 to u128, i8 to i128, usize, isize, NonZeroU8 to NonZeroU128number
f32, f64number
boolboolean
String, char, PathBuf; &'static str as output onlystring
Option<T>T | null
Vec<T>, HashSet<T>, BTreeSet<T>Array<T>
[T; N]FixedSizeArray<T, N>, an array of length N
HashMap<K, V>, BTreeMap<K, V>Record<K, V>
tuples of 1 to 12 elements[A, B, ...]
()null
Box<T>, Arc<T> (with serde's rc feature), Cell<T>, RefCell<T>, Mutex<T>, RwLock<T>T
std::time::Duration{ secs: number, nanos: number }, as serde writes it

The Rust client uses the same Rust types. The Python client uses the matching built-in types (int, float, str, list, dict, tuple, None), Path for paths and timedelta for Duration.

A JavaScript number holds integers exactly only up to 253. A u64 or i64 field whose values can go beyond that loses precision in a TypeScript client. Send such values as strings: serialize the field as a string and describe it as one with a type override.

Library types

Enable a feature of the reflectapi crate to use the types of another crate:

FeatureTypesTypeScript
chronoDateTime<Utc>, DateTime<Local>, DateTime<FixedOffset>, NaiveDateTime, NaiveDate, NaiveTimestring
chrono-tzchrono_tz::Tzstring
uuiduuid::Uuidstring
urlurl::Urlstring
rust_decimalrust_decimal::Decimalstring
jsonserde_json::Value; serde_json::Map as a mapany
indexmapIndexMap<K, V>, IndexSet<T>, as maps and setsRecord<K, V>, Array<T>
cargo add reflectapi --features builder,chrono,uuid

The Rust client uses the same types, so a crate that includes it needs the same libraries. The Python client uses datetime and date for chrono's dates and UUID for uuid::Uuid.

Enums

Serde's enum representations are reflected, and each client's type matches the JSON. For this enum:

enum Shape {
    Circle { radius: f64 },
    Empty,
}
use serde_json::to_string as json;
#[derive(serde::Serialize)] enum External { Circle { radius: f64 }, Empty }
#[derive(serde::Serialize)] #[serde(tag = "type")] enum Internal { Circle { radius: f64 }, Empty }
#[derive(serde::Serialize)] #[serde(tag = "t", content = "c")] enum Adjacent { Circle { radius: f64 }, Empty }
#[derive(serde::Serialize)] #[serde(untagged)] enum Untagged { Circle { radius: f64 }, Empty }
fn main() {
let _ = (Shape::Circle { radius: 1.0 }, Shape::Empty);
assert_eq!(json(&External::Circle { radius: 1.0 }).unwrap(), r#"{"Circle":{"radius":1.0}}"#);
assert_eq!(json(&External::Empty).unwrap(), r#""Empty""#);
assert_eq!(json(&Internal::Circle { radius: 1.0 }).unwrap(), r#"{"type":"Circle","radius":1.0}"#);
assert_eq!(json(&Internal::Empty).unwrap(), r#"{"type":"Empty"}"#);
assert_eq!(json(&Adjacent::Circle { radius: 1.0 }).unwrap(), r#"{"t":"Circle","c":{"radius":1.0}}"#);
assert_eq!(json(&Adjacent::Empty).unwrap(), r#"{"t":"Empty"}"#);
assert_eq!(json(&Untagged::Circle { radius: 1.0 }).unwrap(), r#"{"radius":1.0}"#);
assert_eq!(json(&Untagged::Empty).unwrap(), "null");
}
Serde attributeJSONTypeScript
none (externally tagged){"Circle":{"radius":1.0}}, "Empty"{ Circle: { radius: number } } | "Empty"
#[serde(tag = "type")]{"type":"Circle","radius":1.0}, {"type":"Empty"}{ type: "Circle", radius: number } | { type: "Empty" }
#[serde(tag = "t", content = "c")]{"t":"Circle","c":{"radius":1.0}}, {"t":"Empty"}{ t: "Circle", c: { radius: number } } | { t: "Empty" }
#[serde(untagged)]{"radius":1.0}, null{ radius: number } | null

The Rust client's enum has the same serde attributes. Python gets a model per variant and a union of them.

  • rename, rename_all and the other serde attributes on variants and fields are reflected too.
  • An enum whose responses may gain variants can be marked #[reflectapi(open)], so that clients keep values with unfamiliar tags; see Enum evolution.
  • A unit enum that serde writes as numbers, for example with the serde_repr crate, needs #[reflectapi(discriminant)], so that clients use its discriminants (1 | 2 in TypeScript) instead of its variant names.

Newtypes

A tuple struct with one field, struct UserId(u64), is written by serde as its field, and so is a struct marked #[serde(transparent)]. The clients alias it: type UserId = number in TypeScript and pub type UserId = u64 in Rust; Python uses int in its place. The server keeps the distinct type; the clients see the inner one. Inline newtypes removes the alias names from the clients too.

One type, two shapes

A type is reflected once as input and once as output, and the two can differ:

  • a field can be optional in a request (#[serde(default)]) but always present in a response;
  • #[serde(skip_deserializing)] or #[reflectapi(input_skip)] leaves a field out of the input, and #[serde(skip_serializing)] or #[reflectapi(output_skip)] out of the output;
  • #[reflectapi(input_type = "...")] and #[reflectapi(output_type = "...")] describe a field as a different type in each direction.
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, reflectapi::Input, reflectapi::Output)]
struct User {
    /// Set by the server.
    #[serde(skip_deserializing)]
    id: u64,
    name: String,
}

async fn users_create(_: (), user: User, _: reflectapi::Empty) -> User {
    User { id: 1, ..user }
}

fn main() -> Result<(), reflectapi::BuildErrors> {
let (schema, _) = reflectapi::Builder::new()
    .route(users_create, |b| b.name("users.create"))
    .build()?;

let fields = |types: &reflectapi::Typespace| {
    let user = types.types().find(|t| t.name().ends_with("::User")).unwrap();
    user.as_struct().unwrap().fields().map(|f| f.name().to_owned()).collect::<Vec<_>>()
};
assert_eq!(fields(schema.input_types()), ["name"]);
assert_eq!(fields(schema.output_types()), ["id", "name"]);
Ok(())
}

When the two shapes differ, the clients have two types, in input and output namespaces: User becomes input.User, which the client sends, and output.User, which it receives. A type whose shapes are the same stays one type. Missing fields and null has the rules for which fields are required in each direction.

Option and reflectapi::Option

std::option::Option<T> has two states, a value or null. In a request, a missing field also reads as None, so the server can't tell "not sent" from null. For a partial update, where leaving a field out means "keep it" and null means "clear it", use reflectapi::Option<T>, which has three: Undefined, None and Some(T).

#![allow(unused)]
fn main() {
#[derive(serde::Serialize, serde::Deserialize, reflectapi::Input)]
struct PetPatch {
    #[serde(default, skip_serializing_if = "reflectapi::Option::is_undefined")]
    age: reflectapi::Option<u8>,
}

let patch: PetPatch = serde_json::from_str("{}").unwrap();
assert!(patch.age.is_undefined());
let patch: PetPatch = serde_json::from_str(r#"{"age":null}"#).unwrap();
assert!(patch.age.is_none());
let patch: PetPatch = serde_json::from_str(r#"{"age":3}"#).unwrap();
assert_eq!(patch.age, reflectapi::Option::Some(3));

let undefined = PetPatch { age: reflectapi::Option::Undefined };
assert_eq!(serde_json::to_string(&undefined).unwrap(), "{}");
}

Reading needs #[serde(default)]: without it a missing field reads as None. Writing needs skip_serializing_if: without it Undefined is written as null. A request type the server only reads needs just #[serde(default)]; this example, read and written, needs both. The clients keep the three states: the field is age?: number | null | undefined in TypeScript, a reflectapi::Option<u8> in Rust, and a Python model sends only the fields that were set. See Missing fields and explicit null.

Empty and Infallible

reflectapi::Empty is a struct with no fields, {} on the wire. Use it for a route with no input, no output or no request headers. A request with an empty body is read as {}, so an Empty input accepts it. () is null on the wire instead.

reflectapi::Infallible is the error type of a route that can't fail. See Errors.

#![allow(unused)]
fn main() {
assert_eq!(serde_json::to_string(&reflectapi::Empty {}).unwrap(), "{}");
assert_eq!(serde_json::to_string(&()).unwrap(), "null");
}

Types reflectapi doesn't know

A type that implements neither trait, such as std::net::IpAddr, can't be used as it is. Tell reflectapi which known type has the same JSON.

For a field, override its type. Serde writes an IpAddr as a string:

#[derive(serde::Serialize, reflectapi::Output)]
struct Server {
    #[reflectapi(type = "String")]
    address: std::net::IpAddr,
    #[reflectapi(type = "Vec::<String>")]
    fallbacks: Vec<std::net::IpAddr>,
}
fn main() {
    let _ = Server { address: [127, 0, 0, 1].into(), fallbacks: vec![] };
}
  • type sets both directions; input_type and output_type set one.
  • The string is a Rust type path. A generic type needs the turbofish: "Vec::<String>", not "Vec<String>".
  • reflectapi doesn't check that serde writes what the override says. If they differ, the clients are wrong.

For a type of your own whose serde implementation is written by hand, put the override on the type: it is reflected as the given type, under its own name. Serde's #[serde(into = "...")], from and try_from are followed the same way, with no override needed:

use serde::{Deserialize, Serialize};

/// A version, written as "1.2".
#[derive(Clone, Serialize, Deserialize, reflectapi::Input, reflectapi::Output)]
#[serde(into = "String", try_from = "String")]
struct Version {
    major: u32,
    minor: u32,
}

impl From<Version> for String {
    fn from(v: Version) -> String {
        format!("{}.{}", v.major, v.minor)
    }
}

impl TryFrom<String> for Version {
    type Error = String;

    fn try_from(s: String) -> Result<Self, String> {
        let (major, minor) = s.split_once('.').ok_or("expected major.minor")?;
        let number = |s: &str| s.parse().map_err(|_| format!("not a number: {s}"));
        Ok(Version { major: number(major)?, minor: number(minor)? })
    }
}

async fn version(_: (), v: Version, _: reflectapi::Empty) -> Version {
    v
}

fn main() -> Result<(), reflectapi::BuildErrors> {
let (schema, _) = reflectapi::Builder::new()
    .route(version, |b| b.name("version"))
    .build()?;
let version = schema
    .output_types()
    .types()
    .find(|t| t.name().ends_with("::Version"))
    .unwrap();
let field = version.as_struct().unwrap().fields().next().unwrap();
assert_eq!(field.type_ref().name(), "std::string::String");
Ok(())
}

The TypeScript client gets type Version = string. With a hand-written Serialize, #[reflectapi(type = "String")] on the struct does the same.

Input and Output can also be implemented by hand. The simplest implementation returns another type's reflection:

#![allow(unused)]
fn main() {
/// A temperature, written as a number.
struct Celsius(f64);

impl serde::Serialize for Celsius {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.0.serialize(serializer)
    }
}

impl reflectapi::Output for Celsius {
    fn reflectapi_output_type(schema: &mut reflectapi::Typespace) -> reflectapi::TypeReference {
        f64::reflectapi_output_type(schema)
    }
}
}

Unlike an override, this gives the type no name of its own: clients see an f64. The orphan rule applies: a trait from reflectapi can be implemented only for a type of your own crate, so use an override for a field of a type from another crate.

Organising a Larger API

A small API fits in one Builder. A larger one is easier to keep as a builder per module, combined into one API. This page covers how names in your Rust code become names in the generated clients, and the builder methods that shape them.

A builder per module

Each module defines its types, its handlers and a function returning its builder. The root builder combines them:

use reflectapi::Builder;

#[derive(Clone, Default)]
pub struct AppState;

mod pets {
    use super::AppState;
    use reflectapi::{Builder, Empty};

    #[derive(serde::Serialize, reflectapi::Output)]
    pub struct Pet {
        pub name: String,
    }

    async fn list(_: AppState, _: Empty, _: Empty) -> Vec<Pet> {
        Vec::new()
    }

    pub fn api() -> Builder<AppState> {
        Builder::new()
            .name("pets")
            .route(list, |b| b.name("pets.list").readonly(true))
    }
}

mod admin {
    use super::AppState;
    use reflectapi::{Builder, Empty};

    #[derive(serde::Serialize, reflectapi::Output)]
    pub struct Stats {
        pub pets: u64,
    }

    async fn stats(_: AppState, _: Empty, _: Empty) -> Stats {
        Stats { pets: 0 }
    }

    pub fn api() -> Builder<AppState> {
        Builder::new()
            .name("admin")
            .path("/admin")
            .tag("internal")
            .route(stats, |b| b.name("admin.stats"))
    }
}

pub fn api() -> Builder<AppState> {
    Builder::new()
        .name("Pet store")
        .path("/api")
        .nest(pets::api())
        .nest(admin::api())
      .rename_types("rust_out::", "petstore::")
        .rename_types("petstore::", "myapi::")
}

fn main() {
let (schema, routers) = api().build().unwrap();

let urls: Vec<String> = schema
    .functions()
    .map(|f| format!("{}/{}", f.path(), f.name()))
    .collect();
assert_eq!(urls, ["/api/pets.list", "/api/admin/admin.stats"]);

let types: Vec<&str> = schema.output_types().types().map(|t| t.name()).collect();
assert!(types.contains(&"myapi::pets::Pet"));
assert!(types.contains(&"myapi::admin::Stats"));

let names: Vec<&str> = routers.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, ["Pet store", "pets", "admin"]);

let app = reflectapi::axum::into_router(AppState, routers, Default::default(), |name, router| {
    match name.as_str() {
        // A smaller request body limit for the admin module only.
        "admin" => router.layer(axum::extract::DefaultBodyLimit::max(64 * 1024)),
        _ => router,
    }
});
let _: axum::Router = app;
}
  • Builder::path sets the base path of the routes added after it, so call it before route. A route's own RouteBuilder::path replaces its builder's path; it is not appended to it.
  • nest merges another builder and prepends this builder's path to its routes. extend merges it without changing paths. Both take its types, its validators and any errors it recorded.
  • Each merged builder becomes its own router, named by its name. build returns the root's router first, then one per merged builder. into_router passes each name to its callback, so middleware can differ per module.
  • A builder's name doesn't prefix its routes' names. Give each route its full dotted name, as admin.stats above.
  • Combine the module builders in the root directly. Today nest and extend take only the other builder's own routes into the routers: the routes it had merged from a third builder stay in the schema but are not served.

Route names become client namespaces

A route's name is the name of its client method, and the dots group methods into namespaces. With the API above, a TypeScript client calls client.pets.list(...) and client.admin.stats(...), and the Rust and Python clients use the same paths. Every segment nests: a.b.c is client.a.b.c(...) in all three. A - in a name becomes _, so pets.get-first is get_first. Python clients from earlier releases grouped names differently; the old paths still work, as deprecated aliases that warn when used.

The name is also part of the URL: a route is served at {path}/{name}, here /api/pets.list. Renaming a route or changing a builder's path moves it, and deployed clients still call the old URL. See Evolving an API.

Type names come from module paths

A reflected type is named by its Rust path, crate included: petstore::pets::Pet. The generated clients turn the path into namespaces:

Clientmyapi::pets::Pet becomes
TypeScriptmyapi.pets.Pet, in nested namespace blocks
Rusttypes::myapi::pets::Pet, in nested modules
PythonPet in the subpackage myapi.pets of the client package

So the module layout of your server is the layout of your clients. Keep types in the module they belong to, and rename the prefix you don't want clients to see. rename_types takes either a module prefix ending in ::, which it replaces (an empty replacement removes it), or a full type name, which it renames. The demo renames its crate, reflectapi_demo::, to myapi::. With the default glob feature, glob_rename_types matches type names against a glob instead and replaces their whole module path.

  • A rename applies to the types already in the schema. Call it after the routes and nest calls that bring the types in, and after response_headers.
  • A rename that matches no type is a build error, which catches a stale pattern after a module moves. allow_redundant_renames(true), called before the rename, turns it off.
  • Renames don't check for collisions. Two types renamed to the same name produce a schema with both under one name, so keep the result unique.
  • Type names are not on the wire. Moving or renaming a type changes the generated code, not what deployed clients send or receive.

A type that is sent and received with different shapes gets separate input and output modules in the clients, such as myapi.pets.input.Pet. See Types.

Inline newtypes

A #[serde(transparent)] struct is sent as its one field, but clients still get a named type for it, for example type PetId = string in TypeScript. fold_transparent_types replaces each of them with the type it wraps:

#![allow(unused)]
fn main() {
use reflectapi::{Builder, Empty};

#[derive(serde::Deserialize, reflectapi::Input)]
#[serde(transparent)]
pub struct PetId(String);

async fn get(_: (), _: PetId, _: Empty) -> Option<String> {
    None
}

let (schema, _) = Builder::<()>::new()
    .route(get, |b| b.name("pets.get"))
    .fold_transparent_types()
    .build()
    .unwrap();

let input = schema.functions().next().unwrap().input_type.as_ref().unwrap();
assert_eq!(input.name, "std::string::String");
assert!(!schema.input_types().types().any(|t| t.name().ends_with("PetId")));
}

Like rename_types, it applies to the types already in the schema.

Project rules

validate adds a check that build runs on the finished schema. build fails with every error the checks return, alongside its own. Validators of nested builders run too.

#![allow(unused)]
fn main() {
use reflectapi::{Builder, Empty, Schema, ValidationError, ValidationPointer};

fn routes_are_described(schema: &Schema) -> Vec<ValidationError> {
    schema
        .functions()
        .filter(|f| f.description().is_empty())
        .map(|f| {
            ValidationError::new(
                ValidationPointer::Function(f.name().into()),
                "add a description".into(),
            )
        })
        .collect()
}

async fn check(_: (), _: Empty, _: Empty) -> Empty {
    Empty {}
}

let errors = Builder::<()>::new()
    .route(check, |b| b.name("health.check"))
    .validate(routes_are_described)
    .build()
    .err()
    .unwrap();
assert_eq!(errors.to_string(), "health.check: add a description\n");
}

Validators run only where the schema is built: a DispatchOnly build skips them. See build modes.

Tags and partial clients

Builder::tag tags the routes added after it, and RouteBuilder::tag tags one route; untag removes a tag. A parent's tags don't apply to the builders it nests. Tags are in the schema, and the OpenAPI document lists them on each operation.

reflectapi codegen takes --include-tags and --exclude-tags (comma-separated). A route is kept when it has any included tag (or no --include-tags is given) and none of the excluded ones. Only --language openapi applies them today: the TypeScript, Rust and Python generators accept the flags and generate every route. The demo uses them to leave its internal routes out of the published OpenAPI document:

reflectapi codegen --language openapi --schema reflectapi.json \
  --output openapi/ --exclude-tags internal

For a client that covers only part of the API, build a second root builder that nests only those modules, and write its schema next to the full one. Each module's api() function can be called as often as needed.

Sharing types with Rust clients

A Rust client may already depend on a crate that defines some of the API's types, such as a crate of shared models. --shared-modules (Rust only, comma-separated) leaves the types whose names start with one of the given prefixes out of the generated code, and the generated code refers to them by their schema name:

reflectapi codegen --language rust --schema reflectapi.json \
  --output clients/rust/ --shared-modules petstore_models::
  • The match is a plain prefix of the type name. End the prefix with :: so petstore_models:: doesn't also match petstore_models_v2::.
  • The schema name must resolve in the client crate, so don't rename those types with rename_types: petstore_models::Pet needs the client crate to depend on petstore_models.
  • The shared types are used as they are, so they need the serde traits the client uses: Serialize for request types, Deserialize for response types.

Evolving an API

A generated client is compiled against one version of the schema, and keeps running after the server changes: in a browser tab left open, an app on a phone, or a service deployed on its own schedule. This page lists which server changes such clients survive, and how to make the others safely.

Two directions matter:

  • Old client, new server: the server is deployed first, and clients generated before the change keep calling it. This is the usual case.
  • New client, old server: a regenerated client reaches a server that doesn't have the change yet, during a rollout or a rollback.

What clients tolerate

Generated clients ignore response fields they don't know. Python models are generated with extra="ignore", the Rust client's serde types ignore unknown fields, and the TypeScript client doesn't check a response's fields at runtime. A server built with reflectapi ignores unknown request fields too, unless the type has #[serde(deny_unknown_fields)].

A missing field is another matter. A Python model rejects a response without a field it requires, and so does Rust for a field that isn't an Option. TypeScript checks a response only on routes that can return an open enum or a #[serde(other)] fallback; elsewhere the field is undefined where its type says it's present. The server answers a request missing a required field with 400.

Type names are not on the wire: the JSON holds field names, variant tags and values. Moving a type to another module or renaming it only changes the generated code. A route is called at {path}/{name}, so its name and its builder's path are on the wire.

Changes at a glance

ChangeOld client, new serverNew client, old server
Add a response fieldSafeBreaks where the new client requires the field
Add an optional request fieldSafeSafe, but the old server ignores the value
Add a required request fieldBreaks: 400Safe, but the old server ignores the value
Remove a response fieldBreaks where the old client requires the fieldSafe
Remove a request fieldSafe: the server ignores itBreaks if the old server requires it
Rename a field, keeping its serde nameSafeSafe
Add a response enum variantBreaks when sent, unless the enum is open or has a fallbackSafe
Add a request enum variantSafeBreaks when sent: 400
Add a routeSafe404 when called
Remove or rename a route, or change its path404 when calledSafe
Rename or move a typeSafeSafe

"Breaks" for a response means a Python client raises a validation error (for an error response, an ApplicationError whose typed_error is None), a Rust client returns a protocol error, and a TypeScript client usually hands the caller a value its types don't describe. Changing a field's type breaks whenever a value of one type doesn't decode as the other.

Adding fields

A new response field is safe for deployed clients. Deploy the server before clients that rely on it.

A new request field must be optional for the clients that don't send it: an Option<T>, which a missing key leaves None, or a field with #[serde(default)]. Generated clients then let callers leave it out, and a request from a client generated before the change still decodes:

use reflectapi::dispatch::{Dispatcher, Reply};

#[derive(serde::Deserialize, reflectapi::Input)]
struct CreatePetRequest {
    name: String,
    // Added after clients shipped.
    #[serde(default)]
    tags: Vec<String>,
    nickname: Option<String>,
}

async fn create(_: (), request: CreatePetRequest, _: reflectapi::Empty) -> String {
    request.name
}

#[tokio::main]
async fn main() {
let (schema, routers) = reflectapi::Builder::<()>::new()
    .route(create, |b| b.name("pets.create"))
    .build()
    .unwrap();

// Clients generated from the new schema may leave the new fields out...
let request = schema
    .input_types()
    .types()
    .find(|t| t.name().ends_with("CreatePetRequest"))
    .and_then(|t| t.as_struct())
    .unwrap();
let optional: Vec<&str> = request.fields().filter(|f| !f.required).map(|f| f.name()).collect();
assert_eq!(optional, ["tags", "nickname"]);

// ...and a request from a client generated before them still succeeds.
let reply = Dispatcher::new(routers)
    .dispatch(
        (),
        &http::Method::POST,
        "/pets.create",
        &http::HeaderMap::new(),
        r#"{"name":"Rex"}"#.into(),
    )
    .await;
assert!(matches!(reply, Some(Reply::Complete { status, .. }) if status == 200));
}

Without #[serde(default)], the same request gets 400 for the missing tags. See Missing fields and null for how defaults, Option and reflectapi::Option map to required and nullable fields in each direction.

Generated Rust types don't derive Default unless the type asks for it with #[reflectapi(derive(Default))], so Rust code that builds a request with a struct literal must add the new field after regenerating.

Removing and renaming fields

To rename a field in Rust without changing the wire, keep its old name with #[serde(rename = "...")]. Neither deployed nor regenerated clients notice: clients name a field after its serde name, and use the Rust identifier only when the serde name can't be one.

To remove a response field, deprecate it first:

#![allow(unused)]
fn main() {
#[derive(serde::Serialize, reflectapi::Output)]
struct Pet {
    name: String,
    #[deprecated(note = "Use `name`.")]
    #[reflectapi(sunset = "2027-01-01")]
    title: String,
}

#[allow(deprecated)]
async fn get(_: (), _: reflectapi::Empty, _: reflectapi::Empty) -> Pet {
    Pet { name: "Rex".into(), title: "Rex".into() }
}

let (schema, _) = reflectapi::Builder::<()>::new()
    .route(get, |b| b.name("pets.get"))
    .build()
    .unwrap();
let files = reflectapi::codegen::typescript::generate(schema, &Default::default()).unwrap();
assert!(files["generated.ts"].contains("title?: string"));
}

The server still sends title, but clients generated from now on treat it as optional: title?: string in TypeScript, an Option in Rust, and None when missing in Python. Once the clients generated before the deprecation are gone, removing the field breaks nothing. This applies to named fields of types used only in responses. A type also used in requests keeps the field required, and so does a type a client decodes by trying alternatives: an untagged enum, an enum with an untagged variant, or the type of a flattened Option field.

To remove a request field, first make it optional, so new clients can stop sending it, then remove it once the clients that require it are gone. The server ignores the field if an old client still sends it.

Deprecations covers declaring the release, the dates and the note, and what each client shows. A sunset date is an announcement: reflectapi doesn't know which clients are still deployed.

Adding enum variants

A client generated from a closed response enum can't decode a variant it doesn't know. Mark the enum #[reflectapi(open)], or give it a #[serde(other)] unit variant, before you need to add variants: clients generated after that accept unknown tags as an explicit unknown case or as the fallback. Clients generated earlier don't. See Enum evolution for the attribute and Handling unfamiliar enum variants for client code.

The server decodes a request enum with serde, so it rejects a variant it doesn't know with 400, unless the enum has a #[serde(other)] variant. Generated request enums stay closed, so a client sends only the variants it was generated with: a new request variant is safe once every server has it.

A route's error is a response type, so the same applies to a new error variant. See Errors for what a client does with an error it can't decode.

Adding, removing and renaming routes

A new route is safe for deployed clients. A removed or renamed route answers 404 to the clients that still call it, so deprecate it first and keep it until they are gone. To rename one, register the same handler under both names, with the old one deprecated; the demo does this for pets.delete:

#![allow(unused)]
fn main() {
async fn pets_remove(_: (), _: reflectapi::Empty, _: reflectapi::Empty) {}
let builder = reflectapi::Builder::<()>::new()
    .route(pets_remove, |b| b.name("pets.remove"))
    .route(pets_remove, |b| {
        b.name("pets.delete")
            .deprecation_note("Use pets.remove instead.")
            .sunset("2027-01-01")
    });
let (schema, _) = builder.build().unwrap();
assert_eq!(schema.functions().count(), 2);
}

Changing a builder's path or a route's name moves the route in the same way. See Organising a Larger API.

Keeping clients in sync

Generate the schema and the clients from the server's code, commit them, and have CI regenerate them and fail on a difference. Generate the schema and clients at build time shows a test that does it. Every API change then shows up in review as a diff of the committed schema and clients, next to the code that caused it. Use the table above to check that diff.

A TypeScript or Rust client compiled in the same repository fails to build when a change breaks the code that calls it. That catches breaks in the code you have, not in clients already deployed.

Testing

An API built with reflectapi is plain Rust: async handler functions, serde types and a Builder. Each part can be tested on its own, most of it without a server or a network:

The examples on this page test this API:

use std::sync::{Arc, Mutex};

use reflectapi::{Builder, Input, Output};
use serde::{Deserialize, Serialize};

#[derive(Default)]
pub struct Store {
    names: Mutex<Vec<String>>,
}

#[derive(Serialize, Output)]
pub struct User {
    pub id: u32,
    pub name: String,
}

#[derive(Deserialize, Input)]
pub struct UsersCreateRequest {
    pub name: String,
}

#[derive(Deserialize, Input)]
pub struct UsersGetRequest {
    pub id: u32,
}

#[derive(Debug, Serialize, Output, reflectapi::StatusCode)]
pub enum UsersGetError {
    #[reflectapi(status = 404)]
    NotFound,
}

pub async fn users_create(
    state: Arc<Store>,
    request: UsersCreateRequest,
    _headers: reflectapi::Empty,
) -> User {
    let mut names = state.names.lock().unwrap();
    let id = names.len() as u32;
    names.push(request.name.clone());
    User { id, name: request.name }
}

pub async fn users_get(
    state: Arc<Store>,
    request: UsersGetRequest,
    _headers: reflectapi::Empty,
) -> Result<User, UsersGetError> {
    let names = state.names.lock().unwrap();
    let name = names.get(request.id as usize).ok_or(UsersGetError::NotFound)?;
    Ok(User { id: request.id, name: name.clone() })
}

pub fn api() -> Builder<Arc<Store>> {
    Builder::new()
        .name("Users")
        .route(users_create, |b| b.name("users.create").description("Create a user"))
        .route(users_get, |b| {
            b.name("users.get").description("Get a user by id").readonly(true)
        })
}
fn main() {}

Handlers

A handler is an async function of the state, the input and the request headers. Call it directly:

// Doctests are not built as tests: run `#[tokio::test]` functions with `#[tokio::main]`.
mod tokio { pub use ::tokio::*; pub use ::tokio::main as test; }
use std::sync::{Arc, Mutex};
use reflectapi::{Builder, Input, Output};
use serde::{Deserialize, Serialize};
#[derive(Default)]
pub struct Store { names: Mutex<Vec<String>> }
#[derive(Serialize, Output)]
pub struct User { pub id: u32, pub name: String }
#[derive(Deserialize, Input)]
pub struct UsersCreateRequest { pub name: String }
#[derive(Deserialize, Input)]
pub struct UsersGetRequest { pub id: u32 }
#[derive(Debug, Serialize, Output, reflectapi::StatusCode)]
pub enum UsersGetError {
    #[reflectapi(status = 404)]
    NotFound,
}
pub async fn users_create(state: Arc<Store>, request: UsersCreateRequest, _headers: reflectapi::Empty) -> User {
    let mut names = state.names.lock().unwrap();
    let id = names.len() as u32;
    names.push(request.name.clone());
    User { id, name: request.name }
}
pub async fn users_get(state: Arc<Store>, request: UsersGetRequest, _headers: reflectapi::Empty) -> Result<User, UsersGetError> {
    let names = state.names.lock().unwrap();
    let name = names.get(request.id as usize).ok_or(UsersGetError::NotFound)?;
    Ok(User { id: request.id, name: name.clone() })
}
#[tokio::test]
async fn get_finds_a_created_user() {
    let state = Arc::new(Store::default());
    let request = UsersCreateRequest { name: "Ada".into() };
    let created = users_create(state.clone(), request, reflectapi::Empty {}).await;

    let request = UsersGetRequest { id: created.id };
    let found = users_get(state.clone(), request, reflectapi::Empty {}).await;
    assert_eq!(found.unwrap().name, "Ada");

    let missing = users_get(state, UsersGetRequest { id: 7 }, reflectapi::Empty {}).await;
    let error = missing.err().unwrap();
    assert!(matches!(error, UsersGetError::NotFound));
    assert_eq!(
        reflectapi::StatusCode::status_code(&error),
        http::StatusCode::NOT_FOUND
    );
}
fn main() { get_finds_a_created_user(); }

This tests the logic, and the status each error is answered with. It skips what happens on the wire: decoding the request, encoding the response, and the request headers the handler is given.

Routes

reflectapi::dispatch::Dispatcher routes a request to the handlers of the built API the same way the axum adapter does, without a server: give it the method, the path, the headers and the body, and it returns the reply. See Integrating Other Servers for what it answers.

// Doctests are not built as tests: run `#[tokio::test]` functions with `#[tokio::main]`.
mod tokio { pub use ::tokio::*; pub use ::tokio::main as test; }
use std::sync::{Arc, Mutex};
use reflectapi::{Builder, Input, Output};
use serde::{Deserialize, Serialize};
#[derive(Default)]
pub struct Store { names: Mutex<Vec<String>> }
#[derive(Serialize, Output)]
pub struct User { pub id: u32, pub name: String }
#[derive(Deserialize, Input)]
pub struct UsersCreateRequest { pub name: String }
#[derive(Deserialize, Input)]
pub struct UsersGetRequest { pub id: u32 }
#[derive(Debug, Serialize, Output, reflectapi::StatusCode)]
pub enum UsersGetError {
    #[reflectapi(status = 404)]
    NotFound,
}
pub async fn users_create(state: Arc<Store>, request: UsersCreateRequest, _headers: reflectapi::Empty) -> User {
    let mut names = state.names.lock().unwrap();
    let id = names.len() as u32;
    names.push(request.name.clone());
    User { id, name: request.name }
}
pub async fn users_get(state: Arc<Store>, request: UsersGetRequest, _headers: reflectapi::Empty) -> Result<User, UsersGetError> {
    let names = state.names.lock().unwrap();
    let name = names.get(request.id as usize).ok_or(UsersGetError::NotFound)?;
    Ok(User { id: request.id, name: name.clone() })
}
pub fn api() -> Builder<Arc<Store>> {
    Builder::new()
        .name("Users")
        .route(users_create, |b| b.name("users.create").description("Create a user"))
        .route(users_get, |b| b.name("users.get").description("Get a user by id").readonly(true))
}
use reflectapi::dispatch::{Dispatcher, Reply};

#[tokio::test]
async fn get_answers_404_for_an_unknown_user() {
    let (_schema, routers) = api().build().unwrap();
    let dispatcher = Dispatcher::new(routers);

    let reply = dispatcher
        .dispatch(
            Arc::new(Store::default()),
            &http::Method::POST,
            "/users.get",
            &http::HeaderMap::new(),
            r#"{"id":7}"#.into(),
        )
        .await
        .expect("a route at /users.get");

    let Reply::Complete { status, body, .. } = reply else {
        panic!("users.get is not a stream route");
    };
    assert_eq!(status, http::StatusCode::NOT_FOUND);
    assert_eq!(body, r#""NotFound""#);
}
fn main() { get_answers_404_for_an_unknown_user(); }
  • Each route is at {path}/{name}. dispatch returns None for a path with no route, and a 405 reply for a method the route does not accept.
  • A body without a content-type header is read as JSON. A body or headers that don't decode get a 400 reply, with the serde error in the body.
  • Pass the request headers the route reads in the HeaderMap; the handler is given only those.
  • A stream route replies with Reply::Stream: collect its items, each an Ok of an Event whose data is the serialized item.
  • The routers of a DispatchOnly build, which a server may use (see build modes), dispatch the same way.

Through axum

Middleware added in the callback of reflectapi::axum::into_router, such as authentication, runs only in the axum router. To test it too, send requests to the router with tower::ServiceExt::oneshot. It needs tower 0.5 with its util feature as a dev-dependency:

// Doctests are not built as tests: run `#[tokio::test]` functions with `#[tokio::main]`.
mod tokio { pub use ::tokio::*; pub use ::tokio::main as test; }
use std::sync::{Arc, Mutex};
use reflectapi::{Builder, Input, Output};
use serde::{Deserialize, Serialize};
#[derive(Default)]
pub struct Store { names: Mutex<Vec<String>> }
#[derive(Serialize, Output)]
pub struct User { pub id: u32, pub name: String }
#[derive(Deserialize, Input)]
pub struct UsersCreateRequest { pub name: String }
#[derive(Deserialize, Input)]
pub struct UsersGetRequest { pub id: u32 }
#[derive(Debug, Serialize, Output, reflectapi::StatusCode)]
pub enum UsersGetError {
    #[reflectapi(status = 404)]
    NotFound,
}
pub async fn users_create(state: Arc<Store>, request: UsersCreateRequest, _headers: reflectapi::Empty) -> User {
    let mut names = state.names.lock().unwrap();
    let id = names.len() as u32;
    names.push(request.name.clone());
    User { id, name: request.name }
}
pub async fn users_get(state: Arc<Store>, request: UsersGetRequest, _headers: reflectapi::Empty) -> Result<User, UsersGetError> {
    let names = state.names.lock().unwrap();
    let name = names.get(request.id as usize).ok_or(UsersGetError::NotFound)?;
    Ok(User { id: request.id, name: name.clone() })
}
pub fn api() -> Builder<Arc<Store>> {
    Builder::new()
        .name("Users")
        .route(users_create, |b| b.name("users.create").description("Create a user"))
        .route(users_get, |b| b.name("users.get").description("Get a user by id").readonly(true))
}
use tower::ServiceExt;

#[tokio::test]
async fn get_answers_404_for_an_unknown_user() {
    let (_schema, routers) = api().build().unwrap();
    let app = reflectapi::axum::into_router(
        Arc::new(Store::default()),
        routers,
        reflectapi::axum::RouterSettings::default(),
        |_name, router| router, // add the server's middleware here
    );

    let request = http::Request::post("/users.get")
        .header("content-type", "application/json")
        .body(axum::body::Body::from(r#"{"id":7}"#))
        .unwrap();
    let response = app.oneshot(request).await.unwrap();

    assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
    assert_eq!(body, r#""NotFound""#);
}
fn main() { get_answers_404_for_an_unknown_user(); }

Build the router in a function that the server and the tests share, so the tests run the server's middleware.

Generated clients

Rust

The generated Rust client sends its requests through a transport, any Clone type that implements reflectapi::rt::Client. A transport that dispatches to the routes calls the API in-process: the request goes through the client's serialization, the routes and the client's deserialization, with no server.

// Doctests are not built as tests: run `#[tokio::test]` functions with `#[tokio::main]`.
mod tokio { pub use ::tokio::*; pub use ::tokio::main as test; }
mod server {
    use std::sync::{Arc, Mutex};
    use reflectapi::{Builder, Input, Output};
    use serde::{Deserialize, Serialize};
    #[derive(Default)]
    pub struct Store { names: Mutex<Vec<String>> }
    #[derive(Serialize, Output)]
    pub struct User { pub id: u32, pub name: String }
    #[derive(Deserialize, Input)]
    pub struct UsersCreateRequest { pub name: String }
    #[derive(Deserialize, Input)]
    pub struct UsersGetRequest { pub id: u32 }
    #[derive(Debug, Serialize, Output, reflectapi::StatusCode)]
    pub enum UsersGetError {
        #[reflectapi(status = 404)]
        NotFound,
    }
    pub async fn users_create(state: Arc<Store>, request: UsersCreateRequest, _headers: reflectapi::Empty) -> User {
        let mut names = state.names.lock().unwrap();
        let id = names.len() as u32;
        names.push(request.name.clone());
        User { id, name: request.name }
    }
    pub async fn users_get(state: Arc<Store>, request: UsersGetRequest, _headers: reflectapi::Empty) -> Result<User, UsersGetError> {
        let names = state.names.lock().unwrap();
        let name = names.get(request.id as usize).ok_or(UsersGetError::NotFound)?;
        Ok(User { id: request.id, name: name.clone() })
    }
    pub fn api() -> Builder<Arc<Store>> {
        Builder::new()
            .name("Users")
            .route(users_create, |b| b.name("users.create").description("Create a user"))
            .route(users_get, |b| b.name("users.get").description("Get a user by id").readonly(true))
    }
}
use server::{api, Store};
/// The output of `reflectapi codegen --language rust` for the API.
mod users_client {
    #![allow(dead_code, unexpected_cfgs, unused_imports)]
    pub use interface::Interface;
    pub use reflectapi::rt::*;
    pub mod interface {
        #[derive(Debug)]
        pub struct Interface<C: reflectapi::rt::Client + Clone> {
            pub users: UsersInterface<C>,
            client: C,
        }
        impl<C: reflectapi::rt::Client + Clone> Interface<C> {
            pub fn new(client: C) -> Self {
                Self { users: UsersInterface::new(client.clone()), client }
            }
        }
        #[derive(Debug)]
        pub struct UsersInterface<C: reflectapi::rt::Client + Clone> {
            client: C,
        }
        impl<C: reflectapi::rt::Client + Clone> UsersInterface<C> {
            pub fn new(client: C) -> Self {
                Self { client }
            }
            /// Create a user
            pub async fn create(
                &self,
                input: super::types::my_api::UsersCreateRequest,
                headers: reflectapi::Empty,
            ) -> Result<super::types::my_api::User, reflectapi::rt::Error<reflectapi::Empty, C::Error>>
            {
                reflectapi::rt::__request_impl(&self.client, "/users.create", input, headers).await
            }
            /// Get a user by id
            pub async fn get(
                &self,
                input: super::types::my_api::UsersGetRequest,
                headers: reflectapi::Empty,
            ) -> Result<
                super::types::my_api::User,
                reflectapi::rt::Error<super::types::my_api::UsersGetError, C::Error>,
            > {
                reflectapi::rt::__request_impl(&self.client, "/users.get", input, headers).await
            }
        }
    }
    pub mod types {
        pub mod my_api {
            #[derive(Debug, serde::Deserialize)]
            pub struct User {
                pub id: u32,
                pub name: std::string::String,
            }
            #[derive(Debug, serde::Serialize)]
            pub struct UsersCreateRequest {
                pub name: std::string::String,
            }
            #[derive(Debug, serde::Deserialize, serde::Serialize)]
            pub enum UsersGetError {
                NotFound,
            }
            impl std::fmt::Display for UsersGetError {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    write!(f, "{}", reflectapi::rt::error_to_string(self))
                }
            }
            impl std::error::Error for UsersGetError {}
            #[derive(Debug, serde::Serialize)]
            pub struct UsersGetRequest {
                pub id: u32,
            }
        }
    }
}
use std::sync::Arc;

use futures_util::StreamExt;
use reflectapi::dispatch::{sse_frames, Dispatcher, Reply};
use reflectapi::rt::{Request, Response, Url};

/// A transport that dispatches requests to the routes, in-process.
#[derive(Clone)]
struct InProcess<S: Send + 'static> {
    dispatcher: Arc<Dispatcher<S>>,
    state: S,
    base_url: Url,
}

impl<S: Send + 'static> InProcess<S> {
    fn new(routers: Vec<reflectapi::Router<S>>, state: S) -> Self {
        Self {
            dispatcher: Arc::new(Dispatcher::new(routers)),
            state,
            // Required by the trait, and unused.
            base_url: "http://localhost".parse().unwrap(),
        }
    }
}

impl<S: Clone + Send + 'static> reflectapi::rt::Client for InProcess<S> {
    type Error = String;

    fn base_url(&self) -> &Url {
        &self.base_url
    }

    async fn request(&self, request: Request) -> Result<Response<String>, String> {
        let reply = self
            .dispatcher
            .dispatch(
                self.state.clone(),
                &http::Method::POST,
                &request.path,
                &request.headers,
                request.body,
            )
            .await
            .ok_or_else(|| format!("no route at {}", request.path))?;
        Ok(match reply {
            Reply::Complete { status, headers, body } => Response {
                status,
                headers,
                body: Box::pin(futures_util::stream::once(async { Ok(body) })),
            },
            // A stream route: its items as Server-Sent Events, as a server sends them.
            Reply::Stream(items) => Response {
                status: http::StatusCode::OK,
                headers: http::HeaderMap::new(),
                body: Box::pin(sse_frames(items).map(|frame| frame.map(Into::into))),
            },
        })
    }
}

use users_client::types::my_api::{UsersCreateRequest, UsersGetError, UsersGetRequest};

#[tokio::test]
async fn get_finds_a_created_user() {
    let (_schema, routers) = api().build().unwrap();
    let client = users_client::Interface::new(InProcess::new(routers, Arc::new(Store::default())));

    let request = UsersCreateRequest { name: "Ada".into() };
    let created = client.users.create(request, reflectapi::Empty {}).await.unwrap();

    let request = UsersGetRequest { id: created.id };
    let found = client.users.get(request, reflectapi::Empty {}).await.unwrap();
    assert_eq!(found.name, "Ada");

    let missing = client.users.get(UsersGetRequest { id: 7 }, reflectapi::Empty {}).await;
    assert!(matches!(
        missing,
        Err(reflectapi::rt::Error::Application(UsersGetError::NotFound))
    ));
}
fn main() { get_finds_a_created_user(); }

To test against the server as it runs, with its axum middleware, serve it on a free local port and use the built-in reqwest transport:

// Doctests are not built as tests: run `#[tokio::test]` functions with `#[tokio::main]`.
mod tokio { pub use ::tokio::*; pub use ::tokio::main as test; }
mod server {
    use std::sync::{Arc, Mutex};
    use reflectapi::{Builder, Input, Output};
    use serde::{Deserialize, Serialize};
    #[derive(Default)]
    pub struct Store { names: Mutex<Vec<String>> }
    #[derive(Serialize, Output)]
    pub struct User { pub id: u32, pub name: String }
    #[derive(Deserialize, Input)]
    pub struct UsersCreateRequest { pub name: String }
    #[derive(Deserialize, Input)]
    pub struct UsersGetRequest { pub id: u32 }
    #[derive(Debug, Serialize, Output, reflectapi::StatusCode)]
    pub enum UsersGetError {
        #[reflectapi(status = 404)]
        NotFound,
    }
    pub async fn users_create(state: Arc<Store>, request: UsersCreateRequest, _headers: reflectapi::Empty) -> User {
        let mut names = state.names.lock().unwrap();
        let id = names.len() as u32;
        names.push(request.name.clone());
        User { id, name: request.name }
    }
    pub async fn users_get(state: Arc<Store>, request: UsersGetRequest, _headers: reflectapi::Empty) -> Result<User, UsersGetError> {
        let names = state.names.lock().unwrap();
        let name = names.get(request.id as usize).ok_or(UsersGetError::NotFound)?;
        Ok(User { id: request.id, name: name.clone() })
    }
    pub fn api() -> Builder<Arc<Store>> {
        Builder::new()
            .name("Users")
            .route(users_create, |b| b.name("users.create").description("Create a user"))
            .route(users_get, |b| b.name("users.get").description("Get a user by id").readonly(true))
    }
}
use server::{api, Store};
/// The output of `reflectapi codegen --language rust` for the API.
mod users_client {
    #![allow(dead_code, unexpected_cfgs, unused_imports)]
    pub use interface::Interface;
    pub use reflectapi::rt::*;
    pub mod interface {
        #[derive(Debug)]
        pub struct Interface<C: reflectapi::rt::Client + Clone> {
            pub users: UsersInterface<C>,
            client: C,
        }
        impl<C: reflectapi::rt::Client + Clone> Interface<C> {
            pub fn new(client: C) -> Self {
                Self { users: UsersInterface::new(client.clone()), client }
            }
        }
        #[derive(Debug)]
        pub struct UsersInterface<C: reflectapi::rt::Client + Clone> {
            client: C,
        }
        impl<C: reflectapi::rt::Client + Clone> UsersInterface<C> {
            pub fn new(client: C) -> Self {
                Self { client }
            }
            /// Create a user
            pub async fn create(
                &self,
                input: super::types::my_api::UsersCreateRequest,
                headers: reflectapi::Empty,
            ) -> Result<super::types::my_api::User, reflectapi::rt::Error<reflectapi::Empty, C::Error>>
            {
                reflectapi::rt::__request_impl(&self.client, "/users.create", input, headers).await
            }
            /// Get a user by id
            pub async fn get(
                &self,
                input: super::types::my_api::UsersGetRequest,
                headers: reflectapi::Empty,
            ) -> Result<
                super::types::my_api::User,
                reflectapi::rt::Error<super::types::my_api::UsersGetError, C::Error>,
            > {
                reflectapi::rt::__request_impl(&self.client, "/users.get", input, headers).await
            }
        }
    }
    pub mod types {
        pub mod my_api {
            #[derive(Debug, serde::Deserialize)]
            pub struct User {
                pub id: u32,
                pub name: std::string::String,
            }
            #[derive(Debug, serde::Serialize)]
            pub struct UsersCreateRequest {
                pub name: std::string::String,
            }
            #[derive(Debug, serde::Deserialize, serde::Serialize)]
            pub enum UsersGetError {
                NotFound,
            }
            impl std::fmt::Display for UsersGetError {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    write!(f, "{}", reflectapi::rt::error_to_string(self))
                }
            }
            impl std::error::Error for UsersGetError {}
            #[derive(Debug, serde::Serialize)]
            pub struct UsersGetRequest {
                pub id: u32,
            }
        }
    }
}
use std::sync::Arc;

use reflectapi::rt::{ReqwestClient, Url};
use users_client::types::my_api::{UsersCreateRequest, UsersGetRequest};

/// Serves the API on a free local port, and returns its URL.
async fn serve(state: Arc<Store>) -> Url {
    let (_schema, routers) = api().build().unwrap();
    let app = reflectapi::axum::into_router(
        state,
        routers,
        reflectapi::axum::RouterSettings::default(),
        |_name, router| router,
    );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let url = format!("http://{}", listener.local_addr().unwrap());
    tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    url.parse().unwrap()
}

#[tokio::test]
async fn get_finds_a_created_user_over_http() {
    let url = serve(Arc::new(Store::default())).await;
    let transport = ReqwestClient::try_new(reqwest::Client::new(), url).unwrap();
    let client = users_client::Interface::new(transport);

    let request = UsersCreateRequest { name: "Ada".into() };
    let created = client.users.create(request, reflectapi::Empty {}).await.unwrap();

    let request = UsersGetRequest { id: created.id };
    let found = client.users.get(request, reflectapi::Empty {}).await.unwrap();
    assert_eq!(found.name, "Ada");
}
fn main() { get_finds_a_created_user_over_http(); }

A generated client crate with its reqwest feature also has Interface::try_new(reqwest::Client, Url); see Client Libraries.

TypeScript

client() takes a base URL or a transport: any object with the request(request): Promise<Response> method of the Client interface in generated.transport.ts. A fake transport tests code that calls the API without a server. The Response returned only needs status, headers.get and body, so the global Response of fetch works:

import { strict as assert } from "node:assert";
import { test } from "node:test";

import { client } from "./generated";
import type { Client, Request } from "./generated.transport";

/** Answers every request with `status` and `body`, and keeps the requests. */
function fakeServer(status: number, body: unknown) {
  const requests: Request[] = [];
  const transport: Client = {
    async request(request) {
      requests.push(request);
      return new Response(JSON.stringify(body), {
        status,
        headers: { "content-type": "application/json" },
      });
    },
  };
  return { transport, requests };
}

test("get finds a user", async () => {
  const server = fakeServer(200, { id: 0, name: "Ada" });

  const user = (await client(server.transport).users.get({ id: 0 }, {})).unwrap_ok();

  assert.equal(user.name, "Ada");
  assert.equal(server.requests[0]?.path, "/users.get");
});

test("get reports an unknown user", async () => {
  const server = fakeServer(404, "NotFound");

  const result = await client(server.transport).users.get({ id: 7 }, {});

  assert.equal(result.unwrap_err().err(), "NotFound");
});

Python

The generated clients take a transport in their client argument: an httpx.Client (httpx.AsyncClient for AsyncClient), or any object with a request method that takes a reflectapi_runtime.transport.Request and returns a Response (an async method for AsyncClient):

import json

import pytest
from reflectapi_runtime import ApplicationError
from reflectapi_runtime.transport import Request, Response

from api_client import Client
from api_client.my_api import UsersGetRequest


class FakeServer:
    """Answers every request with `status` and `body`, and keeps the requests."""

    def __init__(self, status: int, body: object) -> None:
        self.status = status
        self.body = json.dumps(body).encode()
        self.requests: list[Request] = []

    def request(self, request: Request) -> Response:
        self.requests.append(request)
        return Response(
            status=self.status,
            headers={"content-type": "application/json"},
            body=self.body,
        )


def test_get_finds_a_user() -> None:
    server = FakeServer(200, {"id": 0, "name": "Ada"})
    client = Client("http://test", client=server)

    user = client.users.get(UsersGetRequest(id=0)).value

    assert user.name == "Ada"
    assert server.requests[0].path == "/users.get"


def test_get_reports_an_unknown_user() -> None:
    client = Client("http://test", client=FakeServer(404, "NotFound"))

    with pytest.raises(ApplicationError) as raised:
        client.users.get(UsersGetRequest(id=7))
    assert raised.value.status_code == 404
  • Streaming methods send through httpx directly, so they need an httpx client. To fake one, give it an httpx.MockTransport: Client("http://test", client=httpx.Client(transport=httpx.MockTransport(handle))).
  • To stub the client itself, reflectapi_runtime.testing.create_api_response(value) wraps a model in the ApiResponse a method returns, with status 200 unless given status_code. reflectapi codegen --python-testing also writes testing.py into the package, with a create_<type>_response function for each type.

The schema and the generated clients

Commit the schema and the generated clients, and have CI regenerate them and fail on a difference, so an API change cannot merge without its clients. Generate the schema and clients at build time does this from a test; CI then runs the tests and git diff --exit-code. The diff of a pull request then shows what each client gains or loses, next to the Rust change that caused it.

reflectapi's own tests take snapshots instead, with insta: insta::assert_json_snapshot!(schema) for the schema, and insta::assert_snapshot! for the code each generator writes. Compile the committed clients in CI too, with the projects that use them.

Build-time checks

Some mistakes are caught before a test runs:

  • The derives reject invalid attributes as the crate compiles, such as #[reflectapi(hidden)] on a tuple field, a malformed deprecation date (Deprecations), or a status a route's error must not give (A route's error).
  • Builder::route requires its handler's input, output, error and headers types to implement the reflectapi traits, so a type that doesn't is a compile error.
  • Builder::build returns BuildErrors for what it checks at run time: an invalid request header name, malformed route deprecation dates, invalid response headers, sse_keep_alive on a route that isn't a stream route, #[serde(flatten)] on a reflectapi::Option field, a rename_types pattern that matches no type, and the errors of custom validators.

Builder::validate adds a custom validator: a function of the schema that returns the problems it finds. Use it for the API's own conventions:

use std::sync::{Arc, Mutex};
use reflectapi::{Builder, Input, Output};
use serde::{Deserialize, Serialize};
#[derive(Default)]
pub struct Store { names: Mutex<Vec<String>> }
#[derive(Serialize, Output)]
pub struct User { pub id: u32, pub name: String }
#[derive(Deserialize, Input)]
pub struct UsersCreateRequest { pub name: String }
#[derive(Deserialize, Input)]
pub struct UsersGetRequest { pub id: u32 }
#[derive(Debug, Serialize, Output, reflectapi::StatusCode)]
pub enum UsersGetError {
    #[reflectapi(status = 404)]
    NotFound,
}
pub async fn users_create(state: Arc<Store>, request: UsersCreateRequest, _headers: reflectapi::Empty) -> User {
    let mut names = state.names.lock().unwrap();
    let id = names.len() as u32;
    names.push(request.name.clone());
    User { id, name: request.name }
}
pub async fn users_get(state: Arc<Store>, request: UsersGetRequest, _headers: reflectapi::Empty) -> Result<User, UsersGetError> {
    let names = state.names.lock().unwrap();
    let name = names.get(request.id as usize).ok_or(UsersGetError::NotFound)?;
    Ok(User { id: request.id, name: name.clone() })
}
use reflectapi::{Schema, ValidationError, ValidationPointer};

/// Every route needs a description, for the generated clients' documentation.
fn every_route_has_a_description(schema: &Schema) -> Vec<ValidationError> {
    schema
        .functions()
        .filter(|function| function.description().is_empty())
        .map(|function| {
            ValidationError::new(
                ValidationPointer::Function(function.name().to_string()),
                "the route has no description".into(),
            )
        })
        .collect()
}

pub fn api() -> Builder<Arc<Store>> {
    Builder::new()
        .name("Users")
        .route(users_create, |b| b.name("users.create").description("Create a user"))
        .route(users_get, |b| b.name("users.get")) // no description
        .validate(every_route_has_a_description)
}

#[test]
fn the_api_builds() {
    if let Err(errors) = api().build() {
        panic!("{errors}");
    }
}
fn main() {
    let errors = api().build().err().expect("users.get has no description");
    assert_eq!(errors.to_string(), "users.get: the route has no description\n");
}

Here the_api_builds fails with users.get: the route has no description.

Validators and the other schema checks run only when the API is built WithSchema. A server that builds it DispatchOnly skips them (see build modes), so keep a test that builds it WithSchema, such as the_api_builds above or the test that generates the clients.

Attributes Reference

ReflectAPI provides #[reflectapi(...)] attributes that control how Rust types are reflected into the schema and generated clients.

Struct / Enum Level

AttributeDescription
#[reflectapi(derive(...))]Forward additional derive traits to the generated Rust client type.
#[reflectapi(open)]Make a tagged enum open in generated responses: retain unfamiliar tags and raw JSON in an explicit unknown case. Request types stay closed.
#[reflectapi(distinct)]Keep a newtype, or a one-field #[serde(transparent)] struct, a type of its own in generated clients, so one ID can't be passed where another is expected. The wire is unchanged.
#[reflectapi(discriminant)]Reflect a fieldless enum serialized as its numbers (for example with serde_repr) by its discriminants, so clients use 1 | 2 instead of variant names.
#[reflectapi(type = "T")]Reflect the type as T, under its own name, in both directions: for a type whose serde implementation is written by hand. A generic T needs the turbofish: "Vec::<String>".
#[reflectapi(input_type = "T")], #[reflectapi(output_type = "T")]The same, for one direction only.

Distinct types

Rust keeps struct UserId(Uuid) and struct SessionId(Uuid) apart, but on the wire both are the UUID they wrap, and a client generated from them would otherwise see two plain strings. #[reflectapi(distinct)] keeps them apart in clients too:

#[derive(serde::Serialize, serde::Deserialize, reflectapi::Input, reflectapi::Output)]
#[reflectapi(distinct)]
pub struct UserId(pub uuid::Uuid);
  • TypeScript: UserId is a branded type, __Distinct<uuid.Uuid, "myapp::UserId">.
    • A plain string isn't a UserId, and a SessionId isn't either, but a UserId is still usable as a string.
    • Values from responses are UserIds already. Make one for a request with the constructor generated beside it, myapp.UserId("..."), which returns its argument unchanged.
    • __Wire<T> is T with each distinct type replaced by the value it wraps.
  • Rust: the client's UserId is a newtype, pub struct UserId(pub uuid::Uuid), where an ordinary newtype becomes a type alias.
  • OpenAPI: UserId is a component of its own, an allOf of the type it wraps, so its name survives.
  • Python: UserId is NewType("UserId", UUID), so a type checker such as pyright or mypy refuses a plain UUID or a SessionId where a UserId belongs. Make one with UserId(value), which returns value; at runtime it is the UUID.
    • NewType needs a class, so this applies to a non-generic distinct type around a string, number, UUID, date, path or IP address. Any other distinct type, such as one around an Option, a list, a timestamp or a model, or a generic one, is written as the type it wraps, as an ordinary newtype is.

Only a newtype or a one-field transparent struct can be distinct, and not one whose schema comes from a type override. Making a type distinct changes its clients' types, so callers that passed plain values need the constructor. Schema::fold_transparent_types leaves distinct types in place.

Enum evolution

An enum marked #[reflectapi(open)] tells generated clients to accept future response variants while preserving their content:

#[derive(serde::Serialize, reflectapi::Output)]
#[serde(tag = "kind")]
#[reflectapi(open)]
enum PetKind {
    Dog { breed: String },
    Bird,
}

This response-only type needs Serialize to send values and Output to describe them in the schema. Request-only types use Deserialize and Input. Add all four derives only when the same type is used in both directions; an open enum's generated request type still stays closed.

Serde controls the wire representation (kind in this example). ReflectAPI's open attribute controls how generated clients handle future response tags.

A response such as {"kind":"Fox","nocturnal":true} becomes an explicit unknown value. A known Dog missing breed still fails decoding. Rust clients get an Unknown { tag, raw } variant (with a suffix if that variant name is already taken). Python clients get an unknown model with .tag and .raw. TypeScript clients get a branded UnknownEnum, detected with isUnknownEnum; its tag and raw value are available under the exported unknownEnum symbol. The same policy applies to nested models, application errors, and SSE items. See handling unfamiliar enum variants for client-side examples. Rust retains Serde's surrounding container rules: an optional flattened enum can become None when its contents fail validation. Use a required flattened field when invalid content must produce a decoding error.

Open enums support external string/single-key-object tags, internal tags, and adjacent tags. Untagged enums and untagged variants are rejected because an overlapping future shape cannot be reliably distinguished from a known shape. Numeric #[reflectapi(discriminant)] enums and output type overrides cannot be combined with open. Directly flattened open enums must use internal or adjacent tags. Codegen rejects flattened external open enums because a future variant key cannot be distinguished from a newly added parent field. An external open enum used as a regular field inside a flattened struct remains supported. An object with a flattened open or declared-fallback enum cannot flatten another enum. Use named fields for additional enums so each unknown case has its own discriminator, payload, and client representation.

This attribute changes client decoding, not server Serde behavior. Requests use separate closed generated types, and the current wire variants in OpenAPI are unchanged. Existing SDKs need regeneration to acquire the new policy; enabling it does not change already distributed SDKs.

Without open, a declared #[serde(other)] unit variant is preserved in the generated response clients. An unfamiliar valid tag maps to that unit variant, discarding its original tag and content. This is supported for internally and adjacently tagged enums, and for externally tagged enums whose variants are all units, which are plain strings on the wire. Adjacent unit variants accept only absent or null content, and external ones only a bare tag or {"tag": null}, matching Serde. Missing/non-string tags and malformed known variants remain errors for ordinary enum fields. A directly flattened internal fallback also preserves Serde's integer variant identifiers: an index selects the declared variant, or the fallback when it is out of range. Open enums always require string tags.

Declaring both open and #[serde(other)] is rejected. Choose the existing unit fallback when unfamiliar tags should map to that declared variant, or open when clients should retain the unfamiliar tag and raw JSON. Neither policy widens generated request types.

Field Level

Type Override

AttributeDescription
#[reflectapi(type = "T")]Override the reflected type for both input and output schemas.
#[reflectapi(input_type = "T")]Override the reflected type for the input schema only.
#[reflectapi(output_type = "T")]Override the reflected type for the output schema only.

A generic type in an override needs the turbofish: type = "Vec::<String>", not "Vec<String>".

Missing fields and null

Field presence is directional. For a named field value: Option<String> without other Serde attributes, the server accepts a missing request key as None, but serializes a response with "value": null. Generated request types therefore allow omission; generated response types require the key. When these contracts differ, a Rust type used in both directions gets separate input and output models. Tuple elements retain their required positions. Presence inference applies to resolved option wrappers, including Option<T> and standard pointer wrappers; an unresolved generic field value: T keeps its declared contract even if one use substitutes Option<U>.

#[serde(default)] allows a missing input field. A custom deserializer (deserialize_with or with) requires the key unless a default is declared; a custom serializer alone does not change input presence. #[serde(skip_serializing_if = "...")] allows omission on output. A #[serde(flatten)] field has no key of its own, so neither attribute applies to it: its fields are optional as a group exactly when its type is an Option.

For reflectapi::Option<T>, a missing input becomes None without a default; #[serde(default)] instead supplies Undefined. A custom default function supplies whatever that function returns. To preserve all three states on the server, use #[serde(default, skip_serializing_if = "reflectapi::Option::is_undefined")]. Client-side omission and explicit null remain separate wire states.

These rules are resolved before field transforms, so an explicit make_required override remains authoritative. Arbitrary custom codecs may change the wire type; use a reflected type override to describe that type. Previously exported schema JSON keeps its recorded required flags: re-export the schema to obtain the corrected input contract.

Transform

AttributeDescription
#[reflectapi(transform = "path::to::fn")]Apply a field transformation callback for both schemas. Signature: fn(&mut Field, &Typespace).
#[reflectapi(input_transform = "path::to::fn")]Apply a field transformation callback for input only.
#[reflectapi(output_transform = "path::to::fn")]Apply a field transformation callback for output only.

The transform callback receives &mut Field and can modify any field metadata — type, required, hidden, etc. It runs after type references are resolved.

ReflectAPI ships with built-in transforms in the reflectapi::transforms module:

  • reflectapi::transforms::fallback_recursively — unwraps transparent wrappers (e.g. Arc<T> → T)
  • reflectapi::transforms::make_required — makes a field required: Option<T> → required T, reflectapi::Option<T> → required Option<T> (nullable but not omittable). For non-Option types, marks the field as required without changing the type.
  • reflectapi::transforms::make_nonnullable — makes a field non-nullable: Option<T> → T, reflectapi::Option<T> → T (keeps optionality, removes nullability). No-op for non-Option types.
  • reflectapi::transforms::make_required_and_nonnullable — makes a field both required and non-nullable: Option<T> → required T, reflectapi::Option<T> → required T. For non-Option types, marks the field as required without changing the type.

Note: In reflectapi, "required" and "non-nullable" are distinct concepts. A field can be:

  • Required + non-nullable (T, required) — must be present, cannot be null
  • Required + nullable (Option<T>, required) — must be present, can be null
  • Optional + nullable (reflectapi::Option<T>) — can be omitted or null
  • Optional + non-nullable (T, not required) — can be omitted, but if present cannot be null

make_required removes the "can be omitted" (undefined) state. make_nonnullable removes the "can be null" state. make_required_and_nonnullable removes both.

Example: Controlling requiredness and nullability in the schema

A field may use an Option wrapper at the Rust level (e.g., because a middleware populates it before your handler runs) but you want generated clients to see a different contract.

#[derive(serde::Deserialize, reflectapi::Input)]
struct MyRequest {
    /// In Rust this is `Option<String>` (populated by middleware),
    /// but clients see it as a required `String` field.
    #[serde(default)]
    #[reflectapi(input_transform = "reflectapi::transforms::make_required")]
    pub tenant_id: Option<String>,
}

#[derive(serde::Deserialize, reflectapi::Input)]
struct PatchRequest {
    /// In Rust this is `reflectapi::Option<String>` (populated by middleware),
    /// but clients see it as a required `Option<String>` (nullable, not omittable).
    #[serde(default)]
    #[reflectapi(input_transform = "reflectapi::transforms::make_required")]
    pub correlation_id: reflectapi::Option<String>,

    /// In Rust this is `reflectapi::Option<String>`,
    /// but clients see it as an optional `String` (can be omitted, but not null).
    #[serde(default)]
    #[reflectapi(input_transform = "reflectapi::transforms::make_nonnullable")]
    pub display_name: reflectapi::Option<String>,

    /// In Rust this is `reflectapi::Option<String>`,
    /// but clients see it as a required `String` (must be present, cannot be null).
    #[serde(default)]
    #[reflectapi(input_transform = "reflectapi::transforms::make_required_and_nonnullable")]
    pub user_id: reflectapi::Option<String>,
}

Visibility

AttributeDescription
#[reflectapi(skip)]Exclude the field entirely from the schema. The field's type does not need to implement Input/Output. Equivalent to setting both input_skip and output_skip.
#[reflectapi(input_skip)]Exclude the field from the input schema only.
#[reflectapi(output_skip)]Exclude the field from the output schema only.
#[reflectapi(hidden)]Keep the field in the schema (marked "hidden": true) but exclude it from generated clients, documentation, and OpenAPI specs. Useful for header fields that the server needs at runtime but clients should not see.

skip vs hidden

Both attributes remove a field from generated clients. The key difference:

  • skip removes the field from the schema entirely. The field's type is never reflected, so it does not need to implement Input or Output. Use this for internal bookkeeping fields whose types are not part of your API.

  • hidden keeps the field in the schema JSON (marked with "hidden": true) but excludes it from generated clients, documentation, and OpenAPI specs. The type must still implement the relevant trait. Use this for fields that are functionally required by server-side infrastructure — for example, a middleware or a proxy layer that populates the field / header before deserialization — but should not appear in client interfaces.

When to use hidden over skip: The field stays in the schema JSON so that server-side tooling (the axum adapter, middleware, or custom infrastructure) can inspect the full type structure at runtime. If nothing on the server needs the field's schema metadata, prefer skip.

Neither skip nor hidden affects serde serialization. For output types, serde will still serialize a hidden field onto the wire — hidden only controls what generated code and documentation show. If a field must never appear in responses, use #[serde(skip_serializing)] instead.

Please note that neither skip nor hidden prevent a malicious client from sending the fields in a request. A middleware may overwrite it or reject or validate as needed. It is up to the specific implementation of your server.

Example: hidden header field

#[derive(serde::Deserialize, reflectapi::Input)]
pub struct MyHeaders {
    /// Visible to clients — they must provide this
    pub authorization: String,

    /// Not visible to the generated clients and documentation
    /// Expected to be populated by a proxy or server-side middleware.
    #[reflectapi(hidden)]
    #[serde(default)]
    pub x_internal_request_id: String,
}

#[serde(default)] on skipped and hidden fields

When a field is excluded from generated clients (via skip, input_skip, or hidden), clients will not send it. Whether you add #[serde(default)] is your choice and depends on your deployment:

  • With #[serde(default)]: If the field is absent, serde fills the default value. The request succeeds even if no proxy or middleware populates the field. Use this for optional metadata (trace IDs, correlation IDs) where absence is acceptable.

  • Without #[serde(default)]: If the field is absent, deserialization fails with a protocol error. Use this for fields that a proxy or middleware is expected to inject — a missing value means the infrastructure is misconfigured, and you want to reject the request loudly rather than proceed silently with a zero-value.

Deprecation

AttributeDescription
#[reflectapi(deprecated_since = "YYYY-MM-DD")]Date the field was deprecated. Requires #[deprecated].
#[reflectapi(sunset = "YYYY-MM-DD")]Date after which the field may be removed. Requires #[deprecated].

The release in Rust's #[deprecated(since = "..")] is kept as well. See Deprecations.

Restrictions

#[reflectapi(hidden)] cannot be used on unnamed (tuple) struct or enum variant fields. Hiding a positional element would shift indices in generated clients, breaking wire compatibility. Use hidden only on named fields.

Enum Variant Level

AttributeDescription
#[reflectapi(skip)]Exclude the variant from the schema entirely.
#[reflectapi(input_skip)]Exclude the variant from the input schema only.
#[reflectapi(output_skip)]Exclude the variant from the output schema only.
#[reflectapi(deprecated_since = "YYYY-MM-DD")]Date the variant was deprecated. Requires #[deprecated].
#[reflectapi(sunset = "YYYY-MM-DD")]Date after which the variant may be removed. Requires #[deprecated].
#[reflectapi(status = 404)]With #[derive(reflectapi::StatusCode)]: the status a route's error is answered with when it is this variant. See A route's error.
#[reflectapi(transparent)]With #[derive(reflectapi::StatusCode)]: the variant has one field, whose status and headers it is answered with.

A route's error

A route's error implements reflectapi::StatusCode: the status its response has, and, with response_headers, the headers the response adds, none by default. For an enum, derive it, giving each variant its status, or taking the status and headers of its one field:

#[derive(serde::Serialize, reflectapi::Output, reflectapi::StatusCode)]
enum PetsInsertError {
    /// The owner doesn't exist: change the request.
    #[reflectapi(status = 404)]
    OwnerNotFound,
    /// A pet of that name exists.
    #[reflectapi(status = 409)]
    Conflict { name: String },
    /// The payment provider asked us to wait: try again after `after_secs`.
    #[reflectapi(transparent)]
    TryAgain(RetryAfter),
    /// A failure the client can't act on.
    #[reflectapi(output_skip, status = 500)]
    InternalError,
}

The derive refuses, as it compiles, a status a route's error must not give:

  • 1xx, 2xx and 3xx, which a client takes for an answer, or acts on (follows a redirect, caches a 301);
  • 400, 405 and 415, which reflectapi answers itself, for a body or headers it can't decode, a method a route doesn't take, or a content type it doesn't speak;
  • 408, 413, 414 and 431, the transport's or the server's, for a request a route never sees;
  • every 5xx but 500, a gateway's or the server's own; and 500 on any variant but one named InternalError, which must be output_skip: a client takes any 5xx as the server's failure, not the route's error, so it has no place in the schema.

A transparent variant's status is its field's, known as it runs, and isn't checked.

A type of the app's own that implements StatusCode gives a variant its status and headers through transparent: RetryAfter above is an app's own "try again after", 429 with the wait in retry-after, and in its body for a typed client:

#[derive(serde::Serialize, reflectapi::Output)]
struct RetryAfter {
    after_secs: u64,
}

impl reflectapi::StatusCode for RetryAfter {
    fn status_code(&self) -> http::StatusCode {
        http::StatusCode::TOO_MANY_REQUESTS
    }

    fn response_headers(&self) -> http::HeaderMap {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::RETRY_AFTER, self.after_secs.into());
        headers
    }
}

Deprecations

Mark a route, field or enum variant deprecated to tell client authors to move off it. Optionally say which release deprecated it, the date it was deprecated, and the date after which it may be removed (its sunset). Use a release, dates, or both, whichever fits your API's deprecation policy. Generated clients flag uses of deprecated items, and the OpenAPI spec carries the release and dates for tooling such as breaking-change checkers.

Declaring

Fields and variants use Rust's #[deprecated], whose since is the release, with dates in #[reflectapi(...)]:

#[derive(serde::Deserialize, reflectapi::Input)]
pub struct DrawRequest {
    #[deprecated(since = "2.3.0", note = "Use `shape` instead.")]
    #[reflectapi(deprecated_since = "2026-10-01", sunset = "2026-11-01")]
    pub radius: Option<f64>,
    pub shape: Shape,
}

#[derive(serde::Deserialize, reflectapi::Input)]
pub enum Shape {
    Circle { radius: f64 },
    #[deprecated(note = "Use `Circle` instead.")]
    #[reflectapi(sunset = "2026-11-01")]
    Ellipse { a: f64, b: f64 },
}

Routes are deprecated on the builder:

builder.route(draw_v1, |b| {
    b.name("shapes.draw_v1")
        .deprecation_note("Use shapes.draw instead.")
        .deprecated_in("2.3.0")
        .deprecated_since("2026-10-01")
        .sunset("2026-11-01")
})

The release is free-form: a crate version, an API version or anything else, kept verbatim. Dates are YYYY-MM-DD, and the sunset can't be before the deprecation date. The derive macros reject a bad date, or a date on an item without #[deprecated], at compile time; Builder::build rejects bad route dates.

#[deprecated(since = "..")] is always the release, even when it looks like a date. Calendar dates come only from #[reflectapi(deprecated_since = "..", sunset = "..")] and the builder. Clippy's deprecated_semver lint, deny by default, rejects a since that isn't a semver version, so a release named another way needs #[allow(clippy::deprecated_semver)].

What clients see

Each target renders one message built from the release, the dates and the note, for example Deprecated in 2.3.0, since 2026-10-01; removal after 2026-11-01. Use shapes.draw instead. Without a release or dates, the message is the note.

TargetRoutesFieldsVariants
OpenAPIdeprecated: true, x-deprecated-in, x-deprecated-since, x-sunset on the operationthe same on the property, header parameter or response headerthe same on the variant's schema
Rust#[deprecated(note = "...")] on the methodon the fieldon the variant
TypeScript@deprecated ... on the methodon the propertyon the union member, and on the tag key of an externally tagged variant with fields
Python@typing_extensions.deprecated(...) on the method, plus a DeprecationWarning when calledField(deprecated=...), so Pydantic warns when the field is readnot marked

A marker doesn't always produce an editor or type-checker warning:

  • TypeScript: editors flag a deprecated method or property. A variant is flagged only when it is externally tagged and has fields, through its tag key: value.Ellipse is struck through. On unit, numeric and internally tagged variants, and on adjacently tagged and untagged ones, the @deprecated comment sits before a union member, which TypeScript doesn't treat as a deprecated symbol, so it's documentation only.
  • Fields: only named fields are marked outside Rust. In OpenAPI, TypeScript and Python, a deprecated field of a tuple struct or newtype, or a deprecated #[serde(flatten)] field, is not marked (TypeScript's comment on a tuple element is documentation only). Deprecate the inner named fields instead.

The Python decorator uses category=None, so it only informs type checkers: pyright (with reportDeprecated) and mypy (with --enable-error-code deprecated) report call sites, and the method body emits the runtime warning.

A deprecated named field of a type that appears only in responses is also optional in clients generated while it is deprecated (?: in TypeScript, Option in Rust, a None default in Python), so those clients keep working once the field is removed. A type that is also read by the server keeps the field required. See Removing and renaming fields.

x-sunset follows the convention oasdiff uses for a deprecated item's earliest removal date.

What a sunset means

A sunset is the date you announce, not a check that removal is safe. reflectapi doesn't know which clients are deployed or whether they still use the item, and clients generated before the deprecation carry no warning at all. Before removing an item, confirm from your own traffic or client inventory that nothing still depends on it.

Client Generation

reflectapi can generate client code from a reflected schema JSON file.

Supported Outputs

OutputStatusNotes
TypeScriptStableTwo generated files: API surface + transport contract
RustStableSingle generated file
PythonStablePackage-style output with real namespace submodules

The same schema also produces an OpenAPI 3.1 document, which describes the API rather than calling it:

reflectapi codegen --language openapi --schema reflectapi.json --output openapi/

reflectapi doc open reflectapi.json serves that document with Redoc at http://localhost:8080, and a server can build and serve it itself; see The schema. The document describes the currently declared wire shapes, so it does not include the unknown case that generated clients add for open enums. Use the generated clients where one exists for your language, and the OpenAPI document for other languages, documentation and tools that read OpenAPI. --include-tags and --exclude-tags currently filter the OpenAPI output only; see Tags and partial clients.

Workflow

  1. Define your API server using reflectapi derives and the builder API.
  2. Write the schema JSON from your Rust application.
  3. Run reflectapi codegen for the target language.
  4. Commit or consume the generated client code from your application.

The CLI defaults to reflectapi.json if --schema is omitted. The demo project uses that filename. If your application writes a different filename such as reflectapi-schema.json, pass that path explicitly.

--output is a directory, created if needed, unless its last part is the name of a generated file, such as generated.ts: then the file is written there, with any sibling files beside it.

# Generate TypeScript client -> clients/typescript/generated.ts
#                          and clients/typescript/generated.transport.ts
cargo run --bin reflectapi -- codegen \
  --language typescript \
  --schema reflectapi.json \
  --output clients/typescript/

# Generate Python client -> clients/python/api_client/__init__.py,
# clients/python/api_client/_client.py, and namespace packages such as
# clients/python/api_client/myapi/model/
cargo run --bin reflectapi -- codegen \
  --language python \
  --schema reflectapi.json \
  --output clients/python/api_client/ \
  --python-sync

# Generate Rust client -> clients/rust/generated.rs
cargo run --bin reflectapi -- codegen \
  --language rust \
  --schema reflectapi.json \
  --output clients/rust/

If you installed the CLI separately, replace cargo run --bin reflectapi -- with reflectapi.

Output Shape

The generators do not all emit the same file layout:

OutputFiles written by the generator
TypeScriptgenerated.ts, generated.transport.ts
Rustgenerated.rs
PythonA package directory containing __init__.py, generated.py, _client.py, _rebuild.py, and namespace package files

The demo repository includes extra project scaffolding around some generated clients, but that scaffolding is not produced by reflectapi codegen itself.

Missing fields and explicit null

Input and output types follow the server's directional Serde contract. A plain named Option<T> input field may be omitted, while an output field that is always serialized remains required and nullable. Types used in both directions may therefore generate separate input and output models. See Missing fields and null for defaults, custom codecs and transforms.

Generated Python models with omittable fields preserve omission in direct model_dump() / model_dump_json() calls using ReflectapiPartialModel. Python requests omit fields the caller has not set (exclude_unset=True) and send explicitly supplied None as JSON null. This applies recursively to nested models, including models inside lists and dictionaries, and uses wire aliases. Unset non-null Pydantic defaults are omitted too; pass the value explicitly to send it. For example, an optional nullable field can be left out with Request(), or sent as null with Request(value=None). Generated fields with known non-nullable primitive or container types reject explicit null. Opaque aliases and custom codecs may require server-side validation.

Rust named optional nullable request fields use reflectapi::Option<T>: Undefined omits the key, None sends null, and Some(value) sends the value. After regenerating, update affected field initializers that previously used std::option::Option<T>. Output-only nullable fields keep their existing types.

Language Behavior

TypeScript

  • Emits two files alongside each other: generated.ts (the API surface — types, functions, the client(base) factory) and generated.transport.ts (the transport contract — Request, Response, Headers, Client, RequestOptions, ClientInstance). The split keeps the bare DTO names from shadowing the DOM globals of the same name when imported from generated.ts. Custom transports import from ./generated.transport.

  • Uses generated TypeScript types and function wrappers.

  • Response enums with #[reflectapi(open)] include a branded UnknownEnum. isUnknownEnum(value) narrows it; value[unknownEnum] holds tag and raw without occupying any wire field names. Generated match calls handle it with the exported [unknownEnum] handler key or an otherwise fallback. Known values keep their wire shape. Runtime decoding is enabled for responses/errors that reach an open enum or #[serde(other)], including nested values and SSE items.

  • Uses a fetch-based default client implementation.

  • Ordinary response paths parse JSON without runtime schema validation. Paths that reach an open enum or declared fallback use generated decoders. These check known payload shapes against the generated TypeScript types; they do not validate every Rust-specific constraint, such as UUID syntax for a field represented as a TypeScript string. A known tag is never reclassified as an unknown case when its payload fails those checks.

  • Supports custom client implementations via the generated client interface. A custom transport's Headers.get(name) must match names case-insensitively, as fetch's does: declared response headers are looked up by their lowercase names.

  • Calls return a CallResult, a Result that also carries the HTTP response: status_code(), the API's declared response headers via headers(), and all of them via raw_headers(). The response may come from the server or from a proxy or rate limiter in front of it; all three are undefined for network failures and aborts.

  • Failed calls hold an Err. err.err() holds the endpoint's typed error (non-5xx responses with a JSON body); anything else, such as a 5xx, a non-JSON body or a network failure, is in err.other_err(). Err has the same status_code(), headers() and raw_headers(). Result.unwrap_ok() throws an Error whose cause is the Err, so code that only sees the thrown error, such as a query library's retry callback, can still classify it:

    retry: (failureCount, error) => {
      if (failureCount >= 2 || !(error.cause instanceof Err)) return false;
      const status = error.cause.status_code();
      // no response at all, rate limited, or upstream unavailable
      return status === undefined || status === 429 || status >= 502;
    }
    

Python

  • Generates Pydantic-based models and client code.
  • Generates an async client by default.
  • Adds a sync client only when --python-sync is passed.
  • Emits reflected Rust namespaces as real Python packages. generated.py is kept as a temporary compatibility facade inside the package.
  • Each namespace exposes its types under short, ergonomic names (order.Item). When a namespace defines a type whose short name clashes with a top-level type of the same name (e.g. both a root IfConflictOnUpdate and a nomatches::IfConflictOnUpdate), the namespace keeps the short name bound to the imported top-level type and exposes its own type under a disambiguated, namespace-prefixed name (nomatches.NomatchesIfConflictOnUpdate). This keeps one Python class per logical type so model.<X> resolves consistently.
  • Raises ApplicationError for a route's error; see Errors.
  • Groups routes at every . of their name, as TypeScript and Rust do: orders.items.list is client.orders.items.list. Paths from earlier releases, which split a name at its first _, remain as deprecated aliases that warn when used.
  • Uses reflectapi_runtime for client base classes and runtime helpers. Install the reflectapi-runtime release that matches the CLI that generated the client: generated code can call helpers an older runtime doesn't have.
  • Models describe the wire in their JSON schemas (model_json_schema(), and FastAPI's OpenAPI), in both validation and serialization mode. Externally tagged enums, structs with a flattened enum, and open enums show what serde writes, not the Python fields that hold it.
  • Open response enum wrappers include a generated unknown model with .tag and .raw. Unknown values serialize to their original wire JSON. Known values still validate normally; #[serde(other)] without open maps to the declared unit fallback instead.

Rust

  • Generates typed async client methods.
  • Integrates with reflectapi::rt::Client. The transport carries the base URL (Client::base_url); the per-request Request DTO carries only path, headers, and body — same shape as TypeScript and Python.
  • Built-in transports: reflectapi::rt::ReqwestClient (a thin wrapper around reqwest::Client + base URL) and the type alias ReqwestMiddlewareClient for reqwest_middleware::ClientWithMiddleware.
  • Generated Interface<C> exposes:
    • Interface::new(client: C) — generic, takes any Client impl.
    • Interface::try_new(reqwest::Client, base_url) -> Result<Self, UrlParseError> — convenience constructor that hides the ReqwestClient adapter for the most common case. Available when the generated crate enables its own reqwest feature (which should re-export reflectapi/reqwest).
  • Supports optional tracing instrumentation through --instrument.
  • Generates serde-compatible types and request helpers for JSON-based transport.
  • Open response enums have a generated Unknown { tag, raw } variant and tag-first deserialization. Ordinary #[serde(other)] output variants keep that attribute. Unknown open error variants serialize to their original JSON for diagnostics.

Handling Unfamiliar Enum Variants

An enum declared with #[reflectapi(open)] keeps known cases typed and adds an explicit unknown case to generated responses. Handle it before reading known variant fields. The following snippets assume the generated PetKind and related types are imported from their generated namespace.

Rust uses a normal enum match:

match pet_kind {
    PetKind::Dog { breed } => println!("Dog: {breed}"),
    PetKind::Bird => println!("Bird"),
    PetKind::Unknown { tag, raw } => println!("New kind {tag}: {raw}"),
}

Python exposes the variant through the generated model's .root:

variant = pet_kind.root
if isinstance(variant, PetKindUnknown):
    print(variant.tag, variant.raw)
elif isinstance(variant, PetKindDog):
    print(variant.breed)
else:
    print("Bird")

TypeScript narrows the union with the helper exported from generated.ts:

import { isUnknownEnum, unknownEnum } from "./generated";

if (isUnknownEnum(petKind)) {
  console.log(petKind[unknownEnum].tag, petKind[unknownEnum].raw);
} else if (petKind.kind === "Dog") {
  console.log(petKind.breed);
} else {
  console.log("Bird");
}

Generated unknown names get a suffix when they would conflict with a declared variant or another generated type. For externally tagged and unit enum unions in TypeScript, match accepts an unknown handler under the exported [unknownEnum] symbol; it is separate from a real wire variant named Unknown. That handler receives { tag, raw } directly. An otherwise handler receives the original value and can use isUnknownEnum to narrow it.

raw is the parsed JSON value, rather than the original response bytes. Python and TypeScript unknown cases serialize back to their retained wire value. Rust does the same when serde::Serialize is requested through #[reflectapi(derive(serde::Serialize))]; responses otherwise derive only Deserialize by default. TypeScript stores its metadata under non-enumerable symbols so JSON.stringify keeps wire fields intact. For a directly flattened enum, Rust and Python expose a typed enum field and retain the remaining enum JSON; TypeScript keeps the flat object and retains the whole original object in value[unknownEnum].raw.

A declared #[serde(other)] uses its unit fallback instead and discards the unfamiliar tag and payload. It cannot be combined with open. Neither policy adds an unknown case to generated requests. See the attribute reference for representation restrictions and migration requirements.

Streaming Endpoints

Endpoints registered with Builder::stream_route produce a stream of items rather than a single response. The wire format is Server-Sent Events: each item is sent as a data: <json>\n\n event. Errors raised before the stream opens are returned as a normal HTTP 4xx/5xx response, not as SSE events. There is no end-of-stream marker: a stream ends when the connection closes. A server can keep a quiet stream open through proxies with SSE comment lines (see Serving with axum); every generated client ignores them.

A stream can give its events ids, so that it can be resumed: the handler yields each item wrapped in reflectapi::Event, usually with an id the item already carries, and the event is sent with the standard SSE id: field before its data:. A route that declares the last-event-id request header gets the id of the last event the client received, when the client, or a server or proxy resuming the stream for it, sends one, and continues after it. The schema, and so every generated client, shows only the item:

#[derive(serde::Deserialize, reflectapi::Input)]
struct Headers {
    #[serde(rename = "last-event-id")]
    last_event_id: Option<String>,
}

async fn pets_events(
    state: AppState,
    _: reflectapi::Empty,
    headers: Headers,
) -> Result<impl Stream<Item = reflectapi::Event<PetEvent>>, Error> {
    let events = state.events_after(headers.last_event_id.as_deref());
    Ok(events.map(|event: PetEvent| reflectapi::Event::new(event.seq, event)))
}

The id is a reflectapi::EventId. Integers and uuid::Uuid convert to one as is; a string goes through EventId::new, which returns an error if it contains a line break or NUL, as such an id cannot be sent. Generated clients read the ids but do not yet send Last-Event-ID when they reconnect.

OutputStreaming client surface
TypeScriptMethod returns Promise<Result<AsyncIterable<Item>, Err<Error>>>; consume with for await.
RustMethod returns reflectapi::rt::StreamResponse<Item, AppError, NetError>. The outer Result reports init failures (application or network); inner items report per-item transport/decode failures only — application errors cannot occur after the stream is open. Requires the rt-sse Cargo feature on the reflectapi dependency.
PythonMethod returns AsyncApiStream[Item] on the async client and ApiStream[Item] on the sync client: iterators that also expose the response's metadata and declared headers once iteration starts. Init 4xx/5xx raise ApplicationError (with the typed error_model if declared); per-event problems raise NetworkError / TimeoutError / ValidationError and terminate the iterator without a leaked socket.
OpenAPIOperation is described with text/event-stream response content.

Request Headers

A route reads request headers through its third argument, a struct whose fields' serde names are the header names. Its handler is given only those headers. A #[serde(flatten)] field gives its type's fields as headers too, at any depth, so headers that several routes read can be declared once and flattened into each route's own. The flattened type must be a struct with named fields, possibly in an Option or a Box; the builder refuses any other, whose keys can't be headers:

/// Headers every route of the API reads.
#[derive(serde::Deserialize, reflectapi::Input)]
struct CommonHeaders {
    #[serde(rename = "x-request-id")]
    request_id: Option<String>,
}

/// `pets.update`'s headers: its own, and the common ones.
#[derive(serde::Deserialize, reflectapi::Input)]
struct PetsUpdateHeaders {
    authorization: String,
    #[serde(flatten)]
    common: CommonHeaders,
}

async fn pets_update(
    state: AppState,
    request: PetsUpdateRequest,
    headers: PetsUpdateHeaders, // given `authorization` and `x-request-id`
) -> Result<Pet, PetsUpdateError> { … }

The flattened field's type can be a type parameter, so one headers type can wrap each route's own, and a route with none of its own takes it alone:

/// The common headers, and the route's own flattened in.
#[derive(serde::Deserialize, reflectapi::Input)]
struct WithCommon<T = reflectapi::Empty> {
    #[serde(rename = "x-request-id")]
    request_id: Option<String>,
    #[serde(flatten)]
    route: T,
}

#[derive(serde::Deserialize, reflectapi::Input)]
struct PetsUpdateHeaders {
    authorization: String,
}

async fn pets_update(
    state: AppState,
    request: PetsUpdateRequest,
    headers: WithCommon<PetsUpdateHeaders>, // given `x-request-id` and `authorization`
) -> Result<Pet, PetsUpdateError> {
    let token = &headers.route.authorization;
    …
}

async fn pets_list(
    state: AppState,
    request: PetsListRequest,
    headers: WithCommon, // given `x-request-id` alone
) -> Result<Vec<Pet>, PetsListError> { … }

Generated clients send the flattened headers as the route's own: a call to pets.update takes x-request-id and authorization side by side, and OpenAPI lists both as its header parameters.

Response Headers

Some response headers matter to callers: a request ID to quote in a support ticket, or retry-after from a rate limiter. Declare them on the builder as a struct with one Option<T> field per header. T must be a string on the wire, because the header's value is deserialized into it the same way request headers are: String, a unit-variant enum, a newtype over one, or a type such as uuid::Uuid, chrono::DateTime or url::Url. Numbers, booleans and collections aren't supported. The field's serde name is the header name and must be lowercase:

#[derive(serde::Serialize, reflectapi::Output)]
struct ResponseHeaders {
    /// Request ID to quote when reporting a problem
    #[serde(rename = "x-request-id")]
    request_id: Option<String>,
    /// Seconds, or an HTTP date, after which to retry
    #[serde(rename = "retry-after")]
    retry_after: Option<String>,
}

let builder = reflectapi::Builder::new()
    .response_headers::<ResponseHeaders>()
    .route(handler, |b| b.name("pets.list"));

The headers apply to successful and failed responses alike. Declaring a header doesn't mean the server sends it: it may be added by infrastructure in front of the server, and clients read it from whatever response arrived. A route's error can set headers, such as a retry-after, through StatusCode::response_headers (see A route's error); a successful response's come from that infrastructure.

A builder's declaration applies to every route of the builder that doesn't declare its own, whether added before or after the call, including the routes of builders merged in with nest or extend that have no declaration of their own. Routes that already declare response headers keep them. Use RouteBuilder::response_headers to declare a different set for one route. As with routes, call rename_types after declaring response headers so the rename applies to the headers type.

A header that appears more than once is read as its values joined with , . set-cookie can't be read that way (cookie dates contain commas, and browsers don't expose it to scripts), so don't declare it.

In TypeScript, the declared headers are typed on the CallResult and Err returned by a call. Code that only sees a thrown error, such as a query library's retry callback, gets the Err as cause with its headers type erased, so cast it to the generated headers type:

retryDelay: (failureCount, error) => {
  const headers =
    error.cause instanceof Err
      ? (error.cause as Err<unknown, ResponseHeaders>).headers()
      : undefined;
  const seconds = headers?.["retry-after"] ? Number(headers["retry-after"]) : NaN;
  // Retry-After may also be an HTTP date; fall back to exponential backoff
  return Number.isFinite(seconds)
    ? seconds * 1000
    : Math.min(1000 * 2 ** failureCount, 30_000);
}
OutputResponse headers
TypeScriptheaders() on the CallResult and on its Err returns the declared headers: each has the field's generated type or is null when that header is absent; headers() itself is undefined when no response arrived. Open enum headers decode unfamiliar strings into UnknownEnum; ordinary enum headers retain the existing unvalidated string behavior. raw_headers() returns all response headers, untyped, for ones the API doesn't declare, such as cf-ray from a CDN. result.map(...) keeps the response; map_err returns a plain Result.
PythonApiResponse.headers and ApiError.headers (including ValidationError when the response body is invalid) hold the declared headers validated into the generated model; a field is None when its header is absent or its value doesn't validate. headers is None when the API declares none or no response arrived. All headers, untyped, are in .metadata.headers. Streaming methods return an ApiStream / AsyncApiStream whose headers and metadata are set once iteration starts.
RustThe headers struct is generated as a type, but the client doesn't populate it yet. The generated method signatures of routes with declared headers will change when it does.
OpenAPIDocumented as optional headers on the operation's 200 and default responses.

Shared Characteristics

The generated clients all aim to provide:

  • Types derived from the Rust-reflected schema
  • Function wrappers with generated documentation
  • Structured handling of application errors versus transport/protocol failures
  • Good IDE support through generated type information

They do not currently all provide the same runtime validation guarantees or the same runtime transport abstractions, so those details should be considered language-specific.

Serving with axum

reflectapi::axum::into_router turns the routers of a built API into an axum Router. Use it for a native server on tokio.

Dependencies

cargo add reflectapi --features builder,axum
cargo add axum
cargo add tokio --features full

reflectapi's axum feature does not enable axum's default features. Your own axum dependency enables what your server uses: its defaults include tokio and http1, which axum::serve needs.

Mount the routes

let (schema, routers) = api().build()?;

let settings = reflectapi::axum::RouterSettings::default();
let app = reflectapi::axum::into_router(app_state, routers, settings, |name, router| {
    // Called once per router: `name` is the name of the builder that defined it,
    // including builders merged with `Builder::extend` and `Builder::nest`.
    router.layer(tower_http::trace::TraceLayer::new_for_http())
});

let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
axum::serve(listener, app).await?;
  • Every route is mounted at POST {path}/{name}, and readonly routes at GET {path}/{name} as well (axum also answers HEAD for them, without a body). Another method gets 405 Method Not Allowed with an allow header (POST, or GET,HEAD,POST); an unknown path gets 404. See On the Wire for bodies, headers and statuses.
  • The callback receives each router with its name, so middleware can differ per API module: authentication for one, a different timeout for another. See A builder per module.
  • app_state is cloned into every handler call. Use cheap clones, such as an Arc.
  • Stream routes respond with Server-Sent Events, one data: event per item, with an id: for items the route wraps in reflectapi::Event. An error returned before the stream opens is a normal HTTP error response.

Keep idle streams open

Proxies and load balancers close a connection that sends nothing for a while, often after 60 to 120 seconds. A stream route that only emits on change is then reconnected over and over, and each reconnect repeats the handler's connect work. into_router can write an SSE comment (: and a blank line) whenever a stream has sent nothing for an interval:

use std::time::Duration;
use reflectapi::axum::RouterSettings;

let settings = RouterSettings::default()
    .sse_keep_alive(Duration::from_secs(15), tokio::time::sleep);
let app = reflectapi::axum::into_router(app_state, routers, settings, |_name, router| router);
  • The interval restarts after every event and every comment, so a busy stream carries no extra bytes.
  • Clients that follow the SSE spec ignore comments, and every generated client does; the schema is unchanged.
  • It is off by default. 15 seconds is well inside common proxy timeouts.
  • reflectapi depends on no async runtime, so you pass the timer: tokio::time::sleep on tokio.
  • The default is set where the server is assembled, because the interval depends on the proxies in front of a deployment, and the same route definitions may be served in several places. Leave it off when a proxy in front already sends heartbeats.

A stream route that needs a different interval, or none, sets its own in the Builder. It overrides the server's default, and Duration::ZERO turns keep-alive off for that route:

builder.stream_route(watch_jobs, |b| {
    b.name("jobs.watch").sse_keep_alive(Duration::from_secs(5))
})
  • The route's interval changes only how it is served: the schema and the generated clients are the same. Setting it on a route that isn't a stream route is a build error.
  • Serving needs a timer for it. RouterSettings::sse_keep_alive provides one along with the default; to keep alive only the routes that ask, pass just the timer with RouterSettings::default().sse_timer(tokio::time::sleep). into_router panics if a route sets an interval and there is no timer, and RouterSettings::default() has none.

The schema

build() returns the schema next to the routes. Write it out for client generation, or serve it, for example as OpenAPI:

let openapi = reflectapi::codegen::openapi::Spec::from(&schema); // `codegen` feature
let app = app.route("/openapi.json", axum::routing::get(|| async { axum::Json(openapi) }));

A server that doesn't need the schema at runtime can build the routes alone: api::<reflectapi::DispatchOnly>().build()? returns the same routers, without reflecting any type, and into_router accepts them. Generate the schema at build time instead. See build modes.

Serving with celld and Cloudflare Workers

A reflectapi API can run in a Cloudflare-compatible Worker, on Cloudflare Workers or on celld, written in Rust with workers-rs and compiled to WebAssembly. The Worker runtime is the HTTP server, so axum is not used: the reflectapi::dispatch::Dispatcher routes requests, and the adapter on this page connects it to workers-rs.

Dependencies

[lib]
crate-type = ["cdylib", "rlib"] # rlib: the native build step below links the crate

[dependencies]
reflectapi = { version = "...", default-features = false, features = ["builder", "json"] }
worker = "0.8"
http = "1"
futures-util = "0.3"

# Generating the schema and clients happens natively, at build time.
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
reflectapi = { version = "...", features = ["builder", "json", "codegen"] }

[profile.release]
lto = true
codegen-units = 1
# Not `strip = true` (the same as "symbols"): wasm-bindgen then fails with
# "externref table required for catch wrappers". `strip = "debuginfo"` is fine.

Build with worker-build --release, as for any workers-rs Worker.

Define the API

Write the definition once, generic over the build mode: the Worker builds it with DispatchOnly, so no schema is built or linked into the wasm, and the build step builds it with WithSchema.

pub fn api<M: reflectapi::BuildMode>() -> reflectapi::Builder<Ctx, M> {
    reflectapi::Builder::default()
        .name("Routing agent")
        .stream_route(prompt, |b| b.name("agent.prompt"))
}

Handlers, their futures and their streams must be Send, but values backed by JavaScript objects (storage, bindings, fetch responses) are not. A Worker runs on one thread, so marking them Send is sound: wrap state in worker::send::SendWrapper, futures in worker::send::SendFuture, and streams in the SendStream from the adapter below.

pub type Ctx = worker::send::SendWrapper<std::rc::Rc<SessionState>>;

async fn prompt(
    ctx: Ctx,
    request: PromptRequest,
    headers: SessionHeaders,
) -> Result<SendStream<impl Stream<Item = AgentEvent>>, PromptError> {
    let session = ctx.0.clone();
    Ok(SendStream::new(async_stream::stream! {
        // read and write `session`, await fetches and timers, yield events
    }))
}

The adapter

Copy this module into your Worker crate.

//! Serves a reflectapi `Dispatcher` from a Cloudflare-compatible Worker or Durable Object.

use std::pin::Pin;
use std::task::{Context, Poll};

use futures_util::{Stream, StreamExt};
use reflectapi::dispatch::{sse_frames, Dispatcher, Reply};
use worker::{send::SendWrapper, Error, Headers, Request, Response, Result};

/// Dispatches one Worker request and converts the reply to a Worker response.
pub async fn serve<S>(dispatcher: &Dispatcher<S>, state: S, mut req: Request) -> Result<Response>
where
    S: Send + Clone + 'static,
{
    let method = http::Method::from_bytes(req.method().as_ref().as_bytes())
        .map_err(|err| Error::RustError(err.to_string()))?;
    let mut headers = http::HeaderMap::new();
    for (name, value) in req.headers().entries() {
        let name = http::HeaderName::from_bytes(name.as_bytes())
            .map_err(|err| Error::RustError(err.to_string()))?;
        let value =
            http::HeaderValue::from_str(&value).map_err(|err| Error::RustError(err.to_string()))?;
        headers.append(name, value);
    }
    let body = req.bytes().await?;

    match dispatcher
        .dispatch(state, &method, &req.path(), &headers, body.into())
        .await
    {
        None => Response::error("Not Found", 404),
        Some(Reply::Complete {
            status,
            headers,
            body,
        }) => Ok(Response::from_bytes(body.to_vec())?
            .with_status(status.as_u16())
            .with_headers(worker_headers(&headers)?)),
        Some(Reply::Stream(items)) => {
            let events = sse_frames(items)
                .map(|frame| frame.map(String::into_bytes).map_err(Error::RustError));
            let headers = Headers::new();
            headers.set("content-type", "text/event-stream")?;
            headers.set("cache-control", "no-cache")?;
            Ok(Response::from_stream(events)?.with_headers(headers))
        }
    }
}

fn worker_headers(headers: &http::HeaderMap) -> Result<Headers> {
    let out = Headers::new();
    for (name, value) in headers {
        let value = value
            .to_str()
            .map_err(|err| Error::RustError(err.to_string()))?;
        out.append(name.as_str(), value)?;
    }
    Ok(out)
}

/// Marks a stream `Send` for reflectapi, like `worker::send::SendWrapper` does for
/// values. Sound in a Worker, which runs on one thread.
pub struct SendStream<St>(SendWrapper<Pin<Box<St>>>);

impl<St> SendStream<St> {
    pub fn new(stream: St) -> Self {
        Self(SendWrapper::new(Box::pin(stream)))
    }
}

impl<St: Stream> Stream for SendStream<St> {
    type Item = St::Item;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<St::Item>> {
        self.get_mut().0.as_mut().poll_next(cx)
    }
}

Idle streams

A proxy may close a stream that sends nothing for a while. Check first whether anything needs to happen in the Worker:

  • Leave it out if the host runtime or a proxy in front of it already sends heartbeats on long-lived responses, or if nothing between the client and the Worker closes quiet connections. A timer in the Worker keeps the isolate busy, which costs CPU time and stops a Durable Object from hibernating or being evicted.
  • Opt in only when quiet streams are being closed and nothing upstream keeps them open. keep_alive writes an SSE comment whenever the stream has sent nothing for the interval, using the runtime's timer:
use std::time::Duration;
use reflectapi::dispatch::keep_alive;

let frames = keep_alive(sse_frames(items), Duration::from_secs(15), worker::Delay::from);
let events = frames.map(|frame| frame.map(String::into_bytes).map_err(Error::RustError));

To keep alive only the routes that set an interval with RouteBuilder::sse_keep_alive, use the route's own: a route that sets none gets Duration::ZERO, which writes no comments.

let interval = dispatcher.sse_keep_alive(&req.path()).unwrap_or(Duration::ZERO);
let frames = keep_alive(sse_frames(items), interval, worker::Delay::from);

Serve from a Worker or a Durable Object

A stateless API serves from the Worker's fetch handler. An API with state per entity (a session, a job) serves from a Durable Object, and the Worker forwards each request to the object it is for. Declare the routing key as a request header, so the schema and the generated clients carry it:

#[derive(serde::Deserialize, reflectapi::Input)]
pub struct SessionHeaders {
    #[serde(rename = "x-session-id")]
    pub session_id: String,
}

#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
    match req.headers().get("x-session-id")? {
        Some(id) if !id.is_empty() => {
            env.durable_object("SESSION")?.get_by_name(&id)?.fetch_with_request(req).await
        }
        _ => Response::error("missing x-session-id", 400),
    }
}

#[durable_object]
pub struct Session {
    ctx: Ctx,
    dispatcher: std::result::Result<Dispatcher<Ctx>, String>,
}

impl DurableObject for Session {
    fn new(state: State, _env: Env) -> Self {
        Self {
            ctx: SendWrapper::new(Rc::new(SessionState::new(state))),
            dispatcher: api::<reflectapi::DispatchOnly>()
                .build()
                .map(Dispatcher::new)
                .map_err(|errors| errors.to_string()),
        }
    }

    async fn fetch(&self, req: Request) -> Result<Response> {
        match &self.dispatcher {
            Ok(dispatcher) => reflectapi_worker::serve(dispatcher, self.ctx.clone(), req).await,
            Err(errors) => Response::error(format!("invalid API definition: {errors}"), 500),
        }
    }
}

The Dispatcher holds no request state: the state is passed to each dispatch call. A Durable Object builds it when it starts; to build it once for every object in an isolate instead, keep it in a thread_local!.

Generate the schema and clients at build time

The crate also builds natively, so a native test (or binary) can build the API WithSchema and write the schema and the clients:

#[cfg(all(test, not(target_arch = "wasm32")))]
#[test]
fn generate_clients() -> Result<(), Box<dyn std::error::Error>> {
    let (schema, _) = api::<reflectapi::WithSchema>().build()?;
    std::fs::write("clients/reflectapi.json", serde_json::to_string_pretty(&schema)?)?;
    let rust = reflectapi::codegen::rust::generate(schema.clone(), &Default::default())?;
    std::fs::write("clients/rust/src/generated.rs", rust)?;
    for (file, content) in reflectapi::codegen::typescript::generate(schema, &Default::default())? {
        std::fs::write(format!("clients/typescript/{file}"), content)?;
    }
    Ok(())
}

Commit the output, and have CI regenerate it and fail on a difference, so an API change cannot merge without its regenerated clients. The default codegen configurations run no formatter, so the output is the same on every machine; enabling formatting makes it depend on the formatter version installed. The reflectapi codegen CLI formats by default, with rustfmt, biome or prettier, or ruff when it finds them; pass --format=false for the same output everywhere.

Integrating Other Servers

Any HTTP server can serve a reflectapi API through reflectapi::dispatch::Dispatcher. It needs only the builder feature, and it is what the axum and Worker integrations are built on. This page is the contract an integration implements.

Build modes

A server needs the routes; the schema is for generating clients and documentation. Builder<S, M> takes a build mode:

Modebuild() returnsUse
WithSchema (default)(Schema, Vec<Router<S>>)Build step: write the schema, generate clients, check them in CI. A server that also serves its schema
DispatchOnlyVec<Router<S>>Serving. Only request-headers types are reflected, for the header names, so startup does almost no schema work and the reflection code of every other type is not linked

Write the definition once, generic over the mode, starting from Builder::default() (Builder::new() is always WithSchema):

pub fn api<M: reflectapi::BuildMode>() -> reflectapi::Builder<AppState, M> {
    reflectapi::Builder::default()
        .name("Pets")
        .route(pets_list, |b| b.name("pets.list").readonly(true))
        .stream_route(pets_events, |b| b.name("pets.events"))
}

let (schema, _) = api::<reflectapi::WithSchema>().build()?; // build step
let routers = api::<reflectapi::DispatchOnly>().build()?;   // server

Schema validation (custom validators, response headers, redundant renames) runs only in the WithSchema build, so run that build in CI. Errors that affect serving, such as an invalid request header name, fail both builds.

Dispatch a request

use reflectapi::dispatch::{sse_frames, Dispatcher, Reply};

let dispatcher = Dispatcher::new(routers);

// per request
match dispatcher.dispatch(state.clone(), &method, path, &headers, body).await {
    None => { /* no such route */ }
    Some(Reply::Complete { status, headers, body }) => { /* send as is */ }
    Some(Reply::Stream(items)) => { /* send sse_frames(items) as Server-Sent Events */ }
}

dispatch takes the request method, its path without the query string, all its headers, and the complete body.

The contract

Routing. Every route is at POST {path}/{name}; a readonly route also accepts GET. This is what the axum adapter serves, and dispatch answers the same way:

  • None when no route has the path. Respond 404, or pass the request on to the server's other routes.
  • A 405 Method Not Allowed reply when the route exists but not for this method, with an allow header: POST, or GET,POST for a readonly route. This includes HEAD: axum answers it for readonly routes by running the GET handler and dropping the body, and says GET,HEAD,POST; dispatch does not.
  • For HEAD, the GET reply's status and headers, without a body.

Requests.

  • Pass all request headers; the dispatcher forwards to each handler only the headers it declares, flattened ones included (Request Headers), plus content-type and traceparent.
  • Pass the complete body. Enforce a body size limit before dispatching.
  • The state is cloned into every call: make it cheap to clone (Arc, handles).

Complete replies. Send status, headers and body unchanged. The reply has no content-length: the length is transport metadata, which the server sets when it writes the body (axum does, and so do Worker runtimes).

Stream replies.

  • Respond 200 with content-type: text/event-stream and cache-control: no-cache.
  • Frame the items with sse_frames, and send each frame as soon as it arrives: do not buffer the response. An item is an Event<String>: the serialized value, and the event id if the route gave the item one by wrapping it in reflectapi::Event; sse_event, which sse_frames applies to each item, writes the id as the standard SSE id: field.
  • An Err item is a value that failed to serialize: log it and end the response.
  • There is no end-of-stream marker; the stream ends when the response ends.
  • If a proxy closes quiet connections and nothing upstream keeps them open, wrap the frames in keep_alive with the host runtime's timer. It writes an SSE comment whenever the stream has sent nothing for the interval, restarting the interval after every frame: keep_alive(sse_frames(items), Duration::from_secs(15), tokio::time::sleep). The result is Send when the timer is, so a single-threaded runtime's timer works too.
  • Leave keep_alive out when the host or a proxy in front of it already sends heartbeats. A timer of the app's own then only keeps the instance busy, and on serverless runtimes it stops the instance from hibernating or being evicted.
  • A route can set its own interval with RouteBuilder::sse_keep_alive. dispatcher.sse_keep_alive(path) returns it, or None when the route leaves it to the host: dispatcher.sse_keep_alive(path).unwrap_or(default). A zero interval writes no comments.
  • An error that the handler returns before the stream opens arrives as a complete reply, not as a stream.

Send. Handlers, their futures and their streams must be Send. On a single-threaded runtime, wrap values that are not, as the Worker integration does.

Test the integration

The responses must be identical to the axum adapter's. The reflectapi demo checks this by replaying recorded requests through both and comparing status, headers and body (reflectapi-demo/tests/run), and does the same for unknown paths and unaccepted methods (reflectapi-demo/tests/dispatch.rs); do the same with your adapter. The expected differences are content-length, which axum sets itself, and HEAD on readonly routes, described above.

Architecture

Overview

ReflectAPI has three layers:

  1. Rust types and handler functions define the API surface.
  2. Reflection builds a Schema, which is the interchange format between the server side and code generators.
  3. Codegen backends transform that schema into language-specific clients or an OpenAPI document.

The workspace is split accordingly:

  • reflectapi-schema: raw schema types and raw-schema transforms
  • reflectapi-derive: #[derive(Input, Output)] macros
  • reflectapi: reflection traits, builder, runtime integrations, codegen backends, and the private compiler schema module
  • reflectapi-cli: CLI wrapper around codegen
  • reflectapi-demo: snapshot and integration tests
  • reflectapi-python-runtime: runtime support for generated Python clients

Reflection Model

Reflection starts from the Input and Output traits in reflectapi/src/traits.rs. Derived implementations and hand-written impls register types into a Typespace and return TypeReferences that point at those definitions.

The top-level Schema in reflectapi-schema/src/lib.rs contains:

  • functions: endpoint definitions
  • input_types: types seen in request positions
  • output_types: types seen in response positions

Input and output types stay separate at schema-construction time so the same Rust name can have different request and response shapes. Some backends later consolidate them into a single naming domain.

Schema and IDs

SymbolId and SymbolKind live in the private reflectapi/src/codegen/schema/symbol.rs module. They are compiler identifiers, not part of the serialized JSON contract.

Key points:

  • raw Schema, Function, and type/member definitions do not store symbol IDs
  • build_schema_ids() in reflectapi/src/codegen/schema/ids.rs assigns IDs in a compiler-owned side table
  • the schema root now uses SymbolKind::Schema
  • the schema root path includes the __schema__ sentinel to avoid colliding with a user-defined type of the same name

That keeps reflectapi.json wire-focused while normalization and semantic analysis still get stable identities.

Type Metadata

Every reflected type is one of:

  • Primitive
  • Struct
  • Enum

Primitive.fallback lets a backend substitute a simpler representation when it does not natively model the original Rust type. Examples in the current codebase include pointer-like wrappers falling back to T, and ordered collections falling back to unordered equivalents or vectors.

Language-specific metadata is carried by LanguageSpecificTypeCodegenConfig in reflectapi-schema/src/codegen.rs:

  • Rust metadata is serialized when present, for example extra derives on generated Rust types.
  • Python type mappings are backend-local in reflectapi/src/codegen/python.rs, not schema annotations.

Response enum policy is shared API metadata: Enum.open retains unfamiliar tags and JSON in generated responses, while Variant.other preserves an explicit Serde unit fallback. Both are omitted from JSON when false, and both are carried into the semantic IR. Reflection records these flags only for outputs, so request types stay closed.

The derive rejects unsupported or conflicting policies. Rust, TypeScript and Python codegen also call the shared validate_response_enums() guard before rendering, including for schemas loaded from JSON. OpenAPI describes the currently declared wire variants; it does not add the generated unknown case.

Normalization

Normalization lives in reflectapi/src/codegen/schema/normalize.rs.

There are two parts:

  1. A mutable normalization pipeline over raw Schema
  2. A Normalizer that converts the resulting schema into SemanticSchema

The configurable pipeline is built with PipelineBuilder. The convenience constructors are:

  • NormalizationPipeline::standard() Runs type consolidation, naming resolution, and circular dependency resolution.
  • NormalizationPipeline::for_codegen() Skips consolidation and naming, and only runs circular dependency resolution.

After the pipeline runs, Normalizer performs:

  1. symbol discovery
  2. type resolution
  3. dependency analysis
  4. a semantic validation hook (additional checks are currently a TODO)
  5. semantic IR construction

SemanticSchema provides resolved, deterministic views of functions and types and is defined in reflectapi/src/codegen/schema/semantic.rs.

Backend Behavior

Backends do not all consume the schema in the same way.

TypeScript

The TypeScript backend in reflectapi/src/codegen/typescript.rs consolidates raw schema types and renders directly from the raw schema.

Rust

The Rust backend in reflectapi/src/codegen/rust.rs also works primarily from the raw schema after consolidation.

Python

The Python backend in reflectapi/src/codegen/python.rs uses both representations:

  1. enum-policy validation and hidden-field filtering run before preprocessing
  2. types are consolidated and flattened generic models are monomorphized
  3. validate_type_references() checks raw references
  4. Normalizer::normalize_with_pipeline(...) builds SemanticSchema using a pipeline that skips consolidation and naming
  5. rendering uses semantic ordering and symbol information, while still consulting raw schema details where the backend needs original field/type shapes

Python-specific type support is driven by backend-local mappings keyed by canonical Rust type name. Those mappings are static codegen knowledge, not part of the shared schema contract.

OpenAPI

The OpenAPI backend in reflectapi/src/codegen/openapi.rs walks the raw schema directly.

Runtime-Specific Types

ReflectAPI includes special API-facing types whose semantics matter to codegen:

The Python backend treats these as runtime-provided abstractions rather than generated models. Generated Python clients use real package modules for reflected namespaces; the flat generated.py file is only a compatibility facade over those modules.

Testing and Validation

reflectapi-demo is the main regression suite.

The combined-type and builder snapshot harnesses in reflectapi-demo/src/tests/assert.rs generate five artifacts:

  • raw schema JSON
  • TypeScript client output
  • Rust client output
  • OpenAPI output
  • Python client output

The workspace also contains compile-pass and compile-fail tests driven by trybuild.

reflectapi-demo/tests/enum_compatibility.rs exports a shared enum schema and Serde-produced fallback samples. Separate Rust, Python and TypeScript suites decode newer wire values through those generated clients. The suite also checks consumer-facing TS and Python types, closed request enums, nested and flattened models, errors, headers where supported, and streaming items.

reflectapi-demo/tests/conformance.rs is the cross-generator wire check. Each case is an echo route with serde-produced samples of its type. For every sample, the Rust, Python and TypeScript clients must send it unchanged as a request and re-encode it unchanged as a response, TypeScript's types must admit it, and it must validate against the OpenAPI request and response schemas. A disagreement with serde we accept for now is listed in DIVERGENCES, and fails its harness once it starts passing, so the list stays current. Add a case there when a generator change touches how a type is written on the wire.

reflectapi-demo/tests/wasm holds codegen to a bytes-in, bytes-out contract: a JSON request (target, schema, options) in, the files as JSON out. Built for wasm32-unknown-unknown, the module imports nothing, so codegen can't reach a filesystem, a process, the environment or a clock, and check.mjs checks that, run under Node, it gives the native build's files. Formatting and type-checking run external tools, so they belong to the host; in wasm they're an error that says so.

This architecture chapter is intended to describe the code paths that exist in the repository, not an aspirational future design.