Skip to content

Rust SDK

Set up your agent

Give your coding agent a Steel browser and the Steel skills, so that it browses and writes Steel code the right way. Learn more

Install the Steel CLI. It signs you in and installs the skills for your coding agents.

curl -fsS https://setup.steel.dev | sh

Or send this prompt to your coding agent, and it does the same:

Read https://setup.steel.dev/install.md and follow it to set up Steel for this coding client.
Then continue my requested task using the installed Steel skill.

Set up your agent →

The Steel SDK for Rust is the crate steel-rs on crates.io, used in code as steel_rs. It gives your code async methods for the endpoints of the Steel API, and it retries failed requests and pages through lists for you. The API reference shows the call for each endpoint.

Install

Each Rust program in these docs is the src/main.rs of a Cargo project. The methods are async, so the SDK needs an async runtime. These commands create the project and add the SDK and Tokio:

cargo new example
cd example
cargo add steel-rs
cargo add tokio --features macros,rt-multi-thread

The SDK needs Rust 1.80 or later. It sends requests with reqwest over rustls.

Create a client

steel_rs::Client::new() reads your API key from the STEEL_API_KEY environment variable and the base URL from STEEL_BASE_URL. To set the options in code, use the builder:

use std::time::Duration;

let client = steel_rs::Client::builder()
    .api_key(std::env::var("STEEL_API_KEY")?)
    .max_retries(5)
    .timeout(Duration::from_secs(20))
    .build();
Builder methodDefaultMeaning
api_keySTEEL_API_KEYThe API key.
base_urlSTEEL_BASE_URL, then https://api.steel.devThe URL of the API. Change it to use a self-hosted Steel Browser.
max_retries2How many times the SDK retries a request that failed.
timeout60 secondsHow long each attempt of a request can take.
headernoneA header to send with every request. Call it once for each header.
http_clienta new reqwest::ClientThe reqwest client that sends the requests.

The STEEL_CUSTOM_HEADERS environment variable adds headers to every request. Write one Name: value pair on each line.

Client keeps its state behind an Arc, so a clone shares the same settings and HTTP client. Accessors such as client.sessions() borrow the client.

Create a session

This program creates a session, prints its ID, and releases it. A session runs until you release it or until it times out, so release it when the work is done.

src/main.rs
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = steel_rs::Client::new();
    let session = client
        .sessions()
        .create(steel_rs::SessionCreateParams::default())
        .await?;

    let result: Result<(), Box<dyn std::error::Error>> = async {
        println!("{}", session.id);
        Ok(())
    }
    .await;

    client.sessions().release(&session.id).await?;
    result
}

Run the program from the root of a Cargo project, with the file at src/main.rs:

cargo run

The program prints the session's ID.

313385e8-469d-40c8-9509-7607521186b2

The program does its work in an async block and releases the session after the block. If a step in the block returns an error, the ? ends the block, not the program, so the release still runs.

To drive the session's browser, connect a CDP (Chrome DevTools Protocol) client to session.websocket_url. The URL holds a token for the session, so the client needs no API key.

Params structs list every input of a method. A struct without required fields implements Default. A struct with required fields has a new constructor that takes only those fields. Set the other fields with struct update syntax:

let page = client
    .scrape(steel_rs::ScrapeParams {
        format: Some(vec![steel_rs::ScrapeParamsFormat::Markdown]),
        ..steel_rs::ScrapeParams::new("https://example.com".to_owned())
    })
    .await?;

Session configuration lists every option of a new session.

Retries and timeouts

The SDK retries a request twice, with exponential backoff, after one of these failures:

  • a connection error or a timeout
  • 408 Request Timeout
  • 409 Conflict
  • 429 Too Many Requests
  • a status of 500 or higher

A response with the x-should-retry header overrides this rule. This needs steel-rs 0.23.0 or later, because older versions do not read the header. When the response has a retry-after or retry-after-ms header of 60 seconds or less, the SDK waits that long before it retries.

Each attempt times out after 60 seconds. Change the number of retries and the timeout with max_retries and timeout on the builder, as in Create a client.

Handle errors

Every method returns Result<T, steel_rs::Error>. The error is one of these variants:

VariantWhen
Error::ApiThe API returned a status outside 2xx. It holds status, body and headers.
Error::HttpThe request failed in reqwest, for example on a network error or a timeout.
Error::DecodeThe SDK could not decode the response.
Error::InvalidThe current SDK does not return it. It holds a message as a String.

error.status() returns the status of any error that has one, and error.body() returns the body of an Error::Api.

match client.sessions().retrieve(&session_id).await {
    Ok(session) => println!("{}", session.id),
    Err(error) => {
        println!("{:?}", error.status());
        println!("{:?}", error.body());
    }
}

Errors lists the error codes and messages of the API.

Pagination

A list method returns a Page. next_page() fetches the next one. Each list method also has an _auto_paging version that returns a Stream over every item.

src/main.rs
use futures_util::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = steel_rs::Client::new();

    let sessions = client
        .sessions()
        .list_auto_paging(steel_rs::SessionListParams {
            status: Some(steel_rs::SessionListParamsStatus::Live),
            ..Default::default()
        });
    let mut sessions = std::pin::pin!(sessions);
    while let Some(session) = sessions.next().await {
        let session = session?;
        println!("{} started at {}", session.id, session.created_at);
    }
    Ok(())
}

This program also needs futures-util:

cargo add futures-util

Methods

The Rust SDK has the methods of the other SDKs, with snake_case names. You reach each group of methods through an accessor on the client, such as client.sessions() or client.sessions().files(). sessions.create is client.sessions().create. Types are PascalCase and named by their path, such as SessionCreateParams.

The API reference documents each endpoint and its parameters. The types and methods of the crate are on docs.rs.