Rust SDK
Install from crates.io and use typed services in your Rust backend with Tokio.
The official Rust SDK provides typed services, pagination, and webhook verification for server integrations with the public API. Keep the API key in your backend instead of distributing it in customer applications.
The SDK reference lists each resource's methods and parameters.
Install the SDK
Use Rust 1.90 or later and a Tokio runtime. The official
raims crate is available on crates.io.
From your application directory:
For a new project, first run cargo new consulta-raims and enter consulta-raims.
cargo add raims
cargo add tokio --features macros,rt-multi-threadCargo fetches from crates.io, selects the compatible stable version, and
records resolved versions in Cargo.lock. Keep the lockfile for repeatable
installation.
For a manual installation, download the raims.crate archive and SHA256SUMS. Verify the hash before using the package. The repository instructions explain installation through Git or a local directory.
Configure the client
Prepare the credential
Obtain a key through API keys and keep it in
RAIMS_API_KEYor your secret store. It determines company, environment, and permissions. Sandbox and Production usehttps://api.raims.com.For this first read, use a Sandbox key with View customers permission. The request only reads one page; it does not create customers or request emails.
Save the read example
Use a Cargo binary project.
src/main.rs Rustuse raims::{params::ListCustomersParams, Optional, RaimsClient}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let client = RaimsClient::new(std::env::var("RAIMS_API_KEY")?)?; let customers = client.customers().list(&ListCustomersParams { page_size: Optional::Value(10), ..Default::default() }).await?; println!("HTTP status: {}; items: {}", customers.last_response.status_code, customers.data.list.len()); Ok(()) }Run and check the result
From the project directory, with
RAIMS_API_KEYavailable to the process, run:Shellcargo runA successful read prints
HTTP status: 200and the number of items in this page.items: 0is a valid empty result for the key’s company and environment. It is not an authentication failure.
What to check
The SDK reads the list and page envelope below. In an empty page, has_next: false means there is no next page. A nonempty page also returns customer records; the program prints only their count.
No customers found
{
"list": [],
"page": {
"page_size": 10,
"has_next": false,
"has_previous": false,
"next_after": null,
"previous_before": null
}
}Reuse the client; clones share its HTTP pool. Other snippets using await
belong inside asynchronous functions returning Result.
Use RaimsClient::builder with timeout, accepting std::time::Duration, and
max_read_retries to configure timeout and read retries. The timeout covers attempts and waits;
retries default to zero.
Create a customer and a charge
This is a backend snippet, after loading the order from your application’s storage. Keep the customer key separate from the charge key. Save the entire request payload, including the amount and title, before sending; read it again on retries instead of generating new values. The text inputs below are String; the due date is i64.
| Input from the saved order | Source and purpose |
|---|---|
customer_tax_id | Customer tax ID already authorized and saved by your application. |
customer_key | Idempotency key for creating this customer; saved before the first request. |
charge_key | A different idempotency key for this charge; saved with the order. |
due_date_unix | Chosen due date, saved in UTC Unix seconds. |
use raims::{params::{CreateCustomerParams, CreateChargeParams}, Optional, RequestOptions};
let customer_params = CreateCustomerParams {
tax_id: Optional::Value(customer_tax_id),
..Default::default()
};
let customer_options = RequestOptions {
idempotency_key: Some(customer_key),
..Default::default()
};
let customer = client.customers()
.create_with_options(&customer_params, &customer_options).await?;
let charge_params = CreateChargeParams {
customer_id: Optional::Value(customer.data.id),
amount_cents: Optional::Value(15000),
due_date: Optional::Value(due_date_unix),
title: Optional::Value("Pedido 1234".to_owned()),
..Default::default()
};
let charge_options = RequestOptions {
idempotency_key: Some(charge_key),
..Default::default()
};
let charge = client.charges()
.create_with_options(&charge_params, &charge_options).await?;
let charge_id = charge.data.id.clone();
let pending = charge.last_response.status_code == 202;If the CPF or CNPJ already exists in the same company and environment, the customer record is updated and keeps its ID.
Persist the returned customer ID and charge ID on the order before returning success to your caller. The charge ID is the value used to resume the read below; the SDK variables are not durable storage.
| Result | What to do next |
|---|---|
HTTP 201 | The charge was created. Save its ID; creation does not confirm payment. This snippet does not request email or payment issuance. |
HTTP 202 in a creation that requests payment issuance | Save the same returned ID and keep the order pending. Retrieve that charge; do not create another one to resolve the pending result. |
| Error or missing response | Handle the structured error. If execution is uncertain, keep the intent and reconcile before retrying with the original key and payload. |
The canonical creation example below shows only the ID and status fields:
Charge without a link or email request
{
"id": "ch_1Q2W3E4R5T6Y7U8I9O0P",
"status": 0
}15000 represents BRL 150.00. Optional::Unset leaves a field absent,
Optional::Null sends null where permitted, and Optional::Value(...) sets
a value. For updates, omission preserves a field and null may clear it under
the contract. ApiResponse<T> contains data, last_response, and raw;
use raw when response absence and null must be distinguished.
Pagination and pending results
The following backend snippet counts at most 100 customers across pages, without logging their records. Keep the configured client open during iteration.
use raims::{params::ListCustomersParams, Optional};
let filters = ListCustomersParams {
page_size: Optional::Value(50),
..Default::default()
};
let mut pages = client.customers().list_pages(&filters)?;
let mut visited = 0;
while visited < 100 {
let Some(response) = pages.next_page().await? else { break };
for _customer in response.data.list {
visited += 1;
if visited == 100 { break; }
}
}
println!("Items visited: {visited}");Items visited: 0 means the query found no customers. 100 means the chosen limit was reached; it does not prove there are no more records. A page error interrupts the count. Save progress only after processing a complete page if your job must resume later.
Creating a pager sends no
HTTP; next_page().await fetches the first page and follows its cursors.
Reading a response list does not fetch pages itself. The pager preserves
filters and options; a failed fetch does not advance its cursor. Use
previous_page().await to move backward. Cursors are opaque; do not combine
after and before.
HTTP 202 keeps the result pending. It does not confirm payment and the SDK does not start polling. When resuming the saved order, load charge_id from storage and retrieve that same charge once:
let current = client.charges().retrieve(&charge_id).await?;
println!("HTTP status: {}; charge status: {}",
current.last_response.status_code, current.data.status);HTTP 200 here confirms that the read succeeded. Interpret the returned status and payment_information using the charge reference; a successful GET does not mean the charge was paid or that issuance completed. If issuance is still pending, keep the same ID. Repeated reads do not speed up processing or issue another payment; contact support if the condition persists.
Idempotency and errors
use raims::params::ListCustomersParams;
match client.customers().list(&ListCustomersParams::default()).await {
Ok(response) => println!("Items: {}", response.data.list.len()),
Err(error) => eprintln!(
"kind: {:?}; HTTP status: {:?}; code: {:?}; Request-Id: {:?}",
error.kind(), error.status_code(), error.code(), error.request_id()
),
}Requests return
Result<ApiResponse<T>, Error>; kind(), status_code(), code(), and
request_id() help decide the next action. Do not treat human messages as
codes or log complete bodies or secrets.
The SDK does not generate keys or retry writes automatically. After a lost
response, reconcile the operation and preserve the original key and
parameters if the endpoint permits another attempt. max_read_retries
enables eligible read retries only. Retry-After and attempts share the
timeout budget; local cancellation does not reverse work accepted by the API.
See Idempotency.
For example, if the read above returns HTTP 403 with API_KEY_PERMISSION_DENIED, the key lacks access to list customers. Enable View customers on the appropriate key and retry the read. Repeating it with the same permissions will not resolve that error.
For field validation failures, use error.details[].field and error.details[].code to locate the input to correct. Check HTTP response codes for other failures.
For an uncertain write, recover the saved key and the entire original payload. If the charge ID was received, retrieve that ID first. Within the idempotency retention period, a compatible retry can return the preserved result, including a pending 202. A key with different parameters can be rejected; do not change the due date or create a new key to bypass the uncertainty. After retention expires, reconcile before another write.
Use Sandbox
Use a Sandbox credential and a charge from that environment:
let sandbox = RaimsClient::new(std::env::var("RAIMS_SANDBOX_API_KEY")?)?;
let result = sandbox.simulations().charges()
.confirm_payment(&sandbox_charge_id).await?;sandbox_charge_id is a String obtained in your Sandbox integration. The
SDK does not select an environment by header or convert a Production
credential. See Simulations. Email requests
and webhooks may still reach external destinations; use authorized ones only.
Receive webhooks
Preserve raw_body as &[u8], signing_headers as a list of (&str, &str)
pairs, and webhook_secret as the webhook's secret_key string. Include all
occurrences of webhook-id, webhook-timestamp, and webhook-signature;
do not collapse them before verification.
use std::time::SystemTime;
use raims::{construct_webhook_event, DEFAULT_WEBHOOK_TOLERANCE};
let event = construct_webhook_event(
raw_body,
&signing_headers,
&webhook_secret,
DEFAULT_WEBHOOK_TOLERANCE,
SystemTime::now(),
)?;
persist_event(event);persist_event belongs to your application. The signature is checked before
JSON decoding; do not reserialize the body. The default tolerance is five
minutes in either direction; keep the server clock synchronized.
verify_webhook_signature authenticates without decoding the event.
Check type and environment, deduplicate the event id, and persist the work
before returning success. webhook-id identifies the delivery and does not
replace the event ID. See Receive events.
Update the SDK
Read the release notes
and update the SDK within the requirement declared in Cargo.toml:
cargo update -p raimscargo update -p raims keeps the version requirement declared in the manifest.
This command preserves the existing requirement. To select the current
stable version outside that requirement or migrate from Git or a local
directory, record the dependency options your application uses. Remove only
the raims entry from the manifest that declares it and keep Cargo.lock.
For an inherited workspace dependency, change its [workspace.dependencies]
entry.
If it is optional, preserve and temporarily remove dependency references in
[features], such as dep:raims, to keep the manifest valid. After adding
the dependency, restore those declarations together with its optional and
feature options. From your application directory:
cargo add raimsReapply the dependency options, such as features, and review the entry in
Cargo.toml: it must use the registry version requirement selected by Cargo,
without git, path, branch, tag, or rev.
Review and keep the updated Cargo.lock, and test the flows used by your
integration before updating the application. Installation does not apply
future updates automatically.