Skip to content

Conversation events in Rust

Send a live transcript from your Rust app. Sparkle sends a signed webhook the moment someone makes a decision, asks a question or commits to something.

Plain HTTP, no SDK to install. Test keys are never billed.

Integrate with any Rust application

Sparkle is an HTTP API, so it works from axum, Actix Web, Rocket, a Tokio task or a CLI: anything that can make an HTTPS request.

  1. Create a conversation with your webhook URL. Keep the webhook.secret it returns: it is shown once.
  2. Post each turn once it is final. Every POST carries your X-API-Key and a fresh Idempotency-Key.
Five-minute quickstart
src/main.rs reqwest (blocking, json), serde_json, uuid
use reqwest::blocking::Client;
use serde_json::{json, Value};
use uuid::Uuid;

const API: &str = "https://api.sparkle.ai/public/v1";

fn main() -> Result<(), reqwest::Error> {
    let key = std::env::var("SPARKLE_API_KEY").expect("SPARKLE_API_KEY is set");
    let client = Client::new();
    let post = |path: String, body: Value| {
        client
            .post(format!("{API}{path}"))
            .header("X-API-Key", &key)
            .header("Idempotency-Key", Uuid::new_v4().to_string())
            .json(&body)
            .send()
    };

    let created: Value = post(
        "/conversations".into(),
        json!({
            "title": "Acme renewal call",
            "webhook_url": "https://yourapp.com/hooks/sparkle",
        }),
    )?
    .json()?;

    let id = created["conversation"]["id"].as_str().unwrap_or_default();
    post(
        format!("/conversations/{id}/turns"),
        json!({ "turns": [{
            "id": "t2", "final": true, "speaker": "dana", "name": "Dana",
            "channel": "remote", "start": 21.0, "end": 23.4,
            "text": "I'll get the SSO fix out by Friday.",
        }] }),
    )?;
    Ok(())
}

Receive moments with axum

Each moment arrives as a moment.detected POST. Its Sparkle-Signature header is an HMAC of a timestamp and the body, keyed with the webhook's whsec_ secret.

  • Check the signature on the raw body, before parsing it.
  • Reject a timestamp more than 5 minutes from your clock.
  • Accept any matching v1: while a rotated secret overlaps, each delivery carries two.
  • Answer 2xx within 30 seconds. A retry repeats the event id, so skip one you have handled.

The Bytes extractor hands over the body as Sparkle sent it; don't take Json on this route. In Actix Web, take web::Bytes.

For a live UI, the conversation's event stream sends the same events as server-sent events.

webhook/src/main.rs axum 0.8, tokio, hmac, sha2, hex, serde_json
use axum::{
    Router,
    body::Bytes,
    http::{HeaderMap, StatusCode},
    routing::post,
};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::time::{SystemTime, UNIX_EPOCH};

fn verify(secret: &str, header: &str, body: &[u8]) -> bool {
    let mut t = "";
    let mut signatures = Vec::new();
    for part in header.split(',') {
        match part.trim().split_once('=') {
            Some(("t", value)) => t = value,
            Some(("v1", value)) => {
                if let Ok(signature) = hex::decode(value) {
                    signatures.push(signature);
                }
            }
            _ => {}
        }
    }
    let Ok(signed_at) = t.parse::<u64>() else {
        return false;
    };
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    if now.abs_diff(signed_at) > 300 {
        return false;
    }
    let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(secret.as_bytes()) else {
        return false;
    };
    mac.update(t.as_bytes());
    mac.update(b".");
    mac.update(body);
    // verify_slice compares in constant time.
    signatures
        .iter()
        .any(|signature| mac.clone().verify_slice(signature).is_ok())
}

async fn sparkle_webhook(headers: HeaderMap, body: Bytes) -> StatusCode {
    let secret = std::env::var("SPARKLE_WEBHOOK_SECRET").unwrap_or_default();
    let header = headers
        .get("sparkle-signature")
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default();
    if !verify(&secret, header, &body) {
        return StatusCode::BAD_REQUEST;
    }
    let Ok(event) = serde_json::from_slice::<serde_json::Value>(&body) else {
        return StatusCode::BAD_REQUEST;
    };
    // A retry repeats event["id"]: skip one you have already handled.
    if event["type"] == "moment.detected" {
        let moment = &event["data"];
        let (kind, text) = (moment["kind"].as_str(), moment["text"].as_str());
        println!("{} {}", kind.unwrap_or(""), text.unwrap_or(""));
    }
    StatusCode::NO_CONTENT
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/hooks/sparkle", post(sparkle_webhook));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Send your first transcript

Create a test key, then run the samples above against it. Test conversations are never billed.