utoipa-ts
Why?
When making fullstack applications with Rust and TypeScript (e.g. with SvelteKit), you usually have to write type definitions on both ends. This can lead to types going out of sync and is also just really annoying to deal with.
This crate aims to solve that by automatically generating TypeScript types from your Rust API endpoint definitions.
What?
Rust crate that generates TypeScript types from utoipa API endpoint definitions. It extracts endpoint information for all defined endpoints and generates TypeScript bindings for them with the help of ts-rs.
Get started
Either add it as a dependency in your Cargo.toml:
[]
= "0.1"
Or do it automatically with cargo add:
Already using utoipa?
To add utoipa-ts to an existing project that already uses utoipa, simply add the dependency, change all utoipa::path attributes to utoipa_ts::path, and add utoipa_ts::export!() to your codebase.
The types file can then be generated by running cargo test export_api.
Configuration
The export path for utoipa_ts::export!() can be chosen with utoipa_ts::export!("you/path/here.ts"). If a path is not present, it will use the default value of types.ts. The UTOIPA_TS_PATH environment variable can also be used to set the export path. If both are present, the environment variable will have priority.
| Variable | Description | Default |
|---|---|---|
UTOIPA_TS_PATH |
The path where the generated TypeScript file will be saved. | types.ts |
Cargo Features
| Feature | Description |
|---|---|
| ts-format | Enables formatting of the generated TypeScript bindings. |
| ts-serde-json | Add TypeScript support for serde_json |
| ts-chrono | Add TypeScript support for chrono |
| ts-bigdecimal | Add TypeScript support for bigdecimal |
| ts-url | Add TypeScript support for url |
| ts-uuid | Add TypeScript support for uuid |
| ts-bson-uuid | Add TypeScript support for bson::oid::ObjectId and bson::uuid |
| ts-bytes | Add TypeScript support for bytes |
| ts-indexmap | Add TypeScript support for indexmap |
| ts-ordered-float | Add TypeScript support for ordered_float |
| ts-heapless | Add TypeScript support for heapless |
| ts-semver | Add TypeScript support for semver |
| ts-smol_str | Add TypeScript support for smol_str |
| ts-tokio | Add TypeScript support for tokio |
| ts-jiff | Add TypeScript support for jiff |
| ts-arrayvec | Add TypeScript support for arrayvec |
| ts-astrolabe | Add TypeScript support for astrolabe |
Examples
use ToSchema;
async
async
export!;
To generate the types.ts file, run the following command:
// This file was generated by utoipa-ts. Do not edit it manually.
export type CreateTodo = { title: string, };
export type Todo = { id: string, title: string, done: boolean, };
export type Api = {
"GET /todos": {
responses: {
200: Array<Todo>;
};
};
"POST /todos": {
body: CreateTodo;
responses: {
201: Todo;
400: never;
};
};
};
More examples
All examples can be found in the examples directory.
Disclaimer
This project is not affiliated with utoipa.