Axum
rspc has a built-in integration with Axum (opens in a new tab) so that you can expose your API over HTTP.
Enable feature
You must install the rspc_axum
(opens in a new tab) crate to use Axum with rspc.
Cargo.toml
[dependencies]
rspc = "0.0.0"
rspc_axum = { version = "0.0.0", features = ["ws"] }
axum = "0.7.0"
Usage
src/main.rs
let router = rspc::Router::<()>::new()
.query("version", |_, _: ()| "1.0.0")
.build()
.arced();
let app = axum::Router::new()
.route("/", get(|| async { "Hello 'rspc'!" }))
.nest("/rspc", rspc_axum::endpoint(router, || ()))
.layer(cors);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
Usage on frontend
index.ts
import { FetchTransport, WebsocketTransport, createClient } from "@rspc/client";
import type { Procedures } from "./ts/bindings"; // These were the bindings exported from your Rust code!
// For fetch transport
const client = createClient<Procedures>({
transport: new FetchTransport("http://localhost:4000/rspc"),
});
// For websocket transport - Required for subscriptions
const client = createClient<Procedures>({
transport: new WebsocketTransport("ws://localhost:8080/rspc/ws"),
});
client.query(["version"]).then((data) => console.log(data));