The Spin Rust SDK
The Spin Rust SDK makes it easy to build Spin components in Rust.
Fermyon Developer Home
This README
file provides a few examples, such as writing Spin HTTP components in Rust and making outbound HTTP requests. For comprehensive information, visit the official Fermyon Developer Home. This resource includes a page on installing Spin, a quickstart guide, and a language support overview page. The latter lists all of Spin's features—including key-value storage, SQLite, MySQL, Redis, Serverless AI, etc.—and their implementation in specific languages such as Rust, TS/JS, Python, and TinyGo.
Writing Spin HTTP Components in Rust
This library simplifies writing Spin HTTP components. Below is an example of such a component:
// lib.rs
use ;
use http_component;
/// A simple Spin HTTP component.
The important things to note about the function above are:
- the
spin_sdk::http_component
macro marks the function as the entry point for the Spin component, - in the function signature (
fn handle_hello_world(req: Request) -> anyhow::Result<impl IntoResponse>
),req
can be any number of types, including the built-inRequest
type or thehttp::Request
type from the popularhttp
crate - in the function signature, the response type can be anything that implements
IntoResponse
meaning the return type can any number of things includinganyhow::Result<impl IntoResponse>
(as shown above),impl IntoResponse
,Response
,anyhow::Result<Response>
, or even thehttp::Response
type from thehttp
crate.- Note: Using the
http
crate will require you to add it to your Cargo.toml manifest (i.e.,cargo add http
).
- Note: Using the
Making Outbound HTTP Requests
Let's see an example where the component makes an outbound HTTP request to a server, modifies the result, and then returns it:
use ;
async
For the component above to be allowed to make the outbound HTTP request, the destination host must be declared, using the allowed_outbound_hosts
configuration, in the Spin application's manifest (the spin.toml
file):
= 2
[]
= "hello_world"
= "0.1.0"
= ["Your Name <your-name@example.com>"]
= "An example application"
[[]]
= "/..."
= "hello-world"
[]
= "target/wasm32-wasi/release/hello_world.wasm"
= ["https://random-data-api.fermyon.app"]
[]
= "cargo build --target wasm32-wasi --release"
= ["src/**/*.rs", "Cargo.toml"]
Building and Running the Spin Application
Spin build can be used to build all components defined in the Spin manifest file at the same time, and also has a flag that starts the application after finishing the compilation, spin build --up
:
)
)
Once our application is running, we can make a request (by visiting http://localhost:3000/
in a web browser) or using curl
as shown below:
}