docs
SupportConsole

Rust

The official Rust library for the Superslice API.

Source, issues and releases: superslice-co/superslice-rust.

Install

The crate is not yet published to crates.io. Until it is, install it from GitHub:

toml
[dependencies]
superslice = { git = "https://github.com/superslice-co/superslice-rust" }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

The library is async and runs on tokio. It uses rustls, so it needs no system OpenSSL.

Quickstart

rust
use superslice::{Client, CreateSlice, Slicer, Upload, WaitOptions};

#[tokio::main]
async fn main() -> superslice::Result<()> {
    let client = Client::new(std::env::var("SUPERSLICE_API_KEY").unwrap())?;

    let params = CreateSlice::new(
        Slicer::BambuStudio,
        "Bambu Lab A1 0.4 nozzle",
        "0.20mm Standard @BBL A1",
        "Bambu PLA Basic @BBL A1",
    )
    .plate_type("Textured PEI Plate")
    .file(Upload::path("cube.stl"));

    let slice = client.slices().create(params).await?;
    let done = client.slices().wait(&slice.id, WaitOptions::default()).await?;

    match done.result {
        Some(result) => {
            println!("print time: {} s", result.print_time_s);
            println!("filament: {} g", result.filament_g);
            if let Some(price) = done.price {
                // Money is an integer in the currency's minor unit.
                println!("price: {} {} (minor units)", price.total_minor, price.currency);
            }
        }
        None => println!("failed: {:?}", done.error),
    }
    Ok(())
}

wait returns the slice when it is succeeded or failed. A failed slice is not an Err: read done.error. It returns Error::Timeout if the slice is still running after 10 minutes.

To slice a model you already uploaded, use .model_id("mdl_..."). To have the API download one, use .source_url("https://...", None).

Page through slices with list, or walk all of them:

rust
let mut all = client.slices().list_all(Some(100));
while let Some(slice) = all.next().await? {
    println!("{} {:?}", slice.id, slice.status);
}

Catalogue lookup

Preset names come from the catalogue. Release ids contain @ and +; the library encodes them.

rust
let engines = client.engines().list().await?;
let release = &engines[0].id;
let printers = client.engines().printers(release).await?;
let printer = &printers[0].name;
let processes = client.engines().processes(release, printer).await?;
let filaments = client.engines().filaments(release, printer).await?;
let plates = client.engines().plate_types(release, printer).await?;

Idempotency

Pass an idempotency key to make a slice safe to repeat. Repeating a key returns the same slice, and the library only retries a POST /v1/slices when a key is set.

rust
let params = params.idempotency_key("order-1042");
let slice = client.slices().create(params).await?;

Errors

Every method returns superslice::Result<T>. The Error enum has one variant per error family, each carrying an ApiError with status, code, title, errors, retry_after and the raw body:

VariantStatus
Authentication401
PlanLimit402
Permission403
NotFound404
Conflict409
RateLimit429
InvalidRequest400, 413
ServerError5xx
Apiany other status
Connection, Timeouttransport problems, and wait running out
rust
match client.slices().get("job_missing").await {
    Err(superslice::Error::NotFound(e)) => println!("no such slice: {}", e.code),
    Err(other) => return Err(other),
    Ok(slice) => println!("{}", slice.id),
}

Error::status(), Error::code() and Error::api() read the details without matching. Error is #[non_exhaustive], so keep a catch-all arm.

Retries

Each request is retried up to max_retries times (default 2). On 429 the library waits Retry-After seconds (1 second if absent). On 5xx and network errors it waits 0.5 s, then 1 s, then 2 s. GET, PUT, PATCH and DELETE retry freely. POST /v1/slices retries only with an idempotency key.

Webhooks

Verify the raw request bytes before parsing them:

rust
use superslice::webhooks;

let event = webhooks::verify(&secret, signature_header, raw_body)?;
if event.event == "slice.completed" {
    let slice = event.slice().unwrap();
    println!("{} s", slice.result.unwrap().print_time_s);
}

verify checks the HMAC-SHA256 of {t}.{body} in constant time, accepts any matching v1 value, and rejects a timestamp more than 5 minutes from now. verify_with_tolerance takes another tolerance. A bad signature returns Error::Signature. An event can arrive twice, so store event.event_id.

Configuration

rust
use std::time::Duration;

let client = superslice::Client::builder()
    .api_key("sk_...")                       // default: SUPERSLICE_API_KEY
    .base_url("https://api.superslice.co")   // default
    .timeout(Duration::from_secs(60))        // default
    .max_retries(2)                          // default
    .build()?;

Client::from_env() reads SUPERSLICE_API_KEY. A missing key fails at construction. Response types ignore unknown fields and have an Unknown variant on every enum, so new API values do not break parsing.

Other resources: models(), presets(), pricing() and slicers(). See the docs for their fields.