TypeScript client
With the ts feature (on by default), axum-autodoc renders a TypeScript client from the same document, in the style of Elysia's Eden Treaty: paths are properties, path parameters are calls and every response is typed. No code generator to install, no build step: it is served by your API.
Get the client
The client is always served at /client.ts. Move it with .client_path(Some("/sdk.ts")) or turn it off with .client_path(None).
To keep a copy in your frontend, export it:
fn openapi() -> OpenApi {
OpenApi::new()
.export_ts("web/api.ts")
}export_ts writes the file in debug builds only, every time the router is finished. finish prints an export error and keeps serving; try_finish returns it.
Use it
import { createClient } from "./api";
const api = createClient("http://localhost:3000", {
headers: () => ({ authorization: `Bearer ${token}` }),
});
const users = await api.users.get();
const created = await api.users.post({ name: "Ann", email: "ann@example.com" });
const user = await api.users({ id: 1 }).get();
if (user.status === 200) user.data.name;
else if (user.status === 404) user.error.value.message;Paths become properties and path parameters become calls: /users/{id} is api.users({ id: 1 }). Query parameters and typed headers go in the last argument.
Every status, typed
Each call returns a discriminated union of { data, error, status } built from the statuses that route can really return. Narrow on status:
type Ok<S extends number, T> = { data: T; error: null; status: S; response: Response };
type Err<S extends number, E> = {
data: null;
error: { status: S; value: E };
status: S;
response: Response;
};A 404 that the handler cannot return is not in the union, so TypeScript will tell you when a check can never match.
Bodies
Bodies are sent in the route's media type:
| Rust | Sent as |
|---|---|
Json<T>, Body<T> | JSON |
Form<T> | application/x-www-form-urlencoded |
String | plain text |
Bytes | a Blob, ArrayBuffer or string |
Upload<T> | FormData, see Uploads |
Uploads
An Upload<T> route takes the struct as its body, with each File as a Blob. The client builds the FormData and leaves the content-type header to fetch, which adds the boundary:
const avatar = await api.users({ id }).avatar.post({
image: new Blob(["png bytes"], { type: "image/png" }),
caption: "me",
});
if (avatar.status === 201) avatar.data.bytes;A Vec<File> is an array of Blob, and each item is appended under the same name.
Event streams
A route that returns EventStream<T> has an AsyncIterable<T> as its data. Read it with for await; every event is parsed from its JSON:
const feed = await api.users.events.get();
if (feed.status === 200) {
for await (const event of feed.data) {
if (event.type === "created") console.log(event.user.name);
}
}Leave the loop with break to close the connection. A plain axum Sse route yields the data: text of each event as a string.
WebSockets
A route with a Socket<In, Out> gets a subscribe() call instead of a method. It opens a WebSocket on the same host, with ws: or wss: in place of the scheme, and returns a typed handle:
const chat = api.chat.subscribe();
chat
.on("open", () => chat.send({ text: "hello" }))
.on("message", (reply) => console.log(reply.number, reply.text))
.on("close", () => console.log("closed"));
chat.close();send takes In and the message listener gets Out, both parsed and serialized as JSON. A message sent before the socket is open waits and goes out on open. Query parameters go in subscribe({ query: { room: "a" } }). The open, close and error listeners get the browser's own Event and CloseEvent.
The details
- Summaries, descriptions and
deprecatedbecome JSDoc. - Documented header parameters are typed in
options.headers. - A path segment that is also an HTTP method name, or is named
subscribe, gets a$prefix:/items/getbecomesapi.items.$get.get(). - Cookie parameters are listed in the JSDoc only, since the browser manages cookies and the client cannot send them.
- A route whose status is only known at run time has a
defaultresponse, which the client types asOk<number, T> | Err<number, T>, sostatusis any number and you narrow on the statuses listed beside it. - Arrays in the query string are sent as repeated keys, which the validated
Query<T>reads. - The output passes
tsc --strictwithexactOptionalPropertyTypesandnoUncheckedIndexedAccess. It only needs the standardfetch,HeadersandURLSearchParams, and CI runs it under Bun.