Developer guide
OFAC API in Rust: screening and error handling
Build OFAC screening in Rust with a complete HTTP example, explicit source selection, idempotency, safe failures, and review handoffs.
On this page
What this Rust integration does
OFAC is the U.S. Treasury authority that publishes the SDN and non-SDN sanctions data. This tutorial calls SanctionsKit, not an OFAC-operated screening endpoint. Keep the original authority and list identity visible in each result.
The client submits a subject, validates the response, and prints only the screening ID, status, and candidate count. It does not approve a customer, resolve an identity, or make a legal decision. A nonzero exit leaves the local operation incomplete.
Prepare the runtime and a synthetic request
Use a maintained Rust toolchain with Cargo. Save the client as src/main.rs and use the Cargo.toml shown below. This is a blocking CLI or worker example, not a function to run directly inside an async executor task.
Save the following as request.json. Mira Calder is an invented subject and sandbox@1 uses synthetic fixtures, not a current production sanctions search. Set SANCTIONSKIT_API_KEY to your test key in the process environment. Set SCREENING_OPERATION_ID to a new persistent identifier for this operation, and reuse it only for an unchanged retry.
{
"subject": {
"name": "Mira Calder",
"entityType": "person",
"birthDate": "1984"
},
"package": "sandbox@1",
"retention": "standard"
}Add the project configuration
Save this as Cargo.toml. These dependencies are for the standalone tutorial, not dependencies to add to SanctionsKit’s website build. Review and lock them under your own maintenance process.
[package]
name = "sanctions-screen"
version = "0.1.0"
edition = "2021"
[dependencies]
reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] }
serde_json = "1"Send the request and validate the result
Save the client as src/main.rs. The endpoint is fixed to SanctionsKit’s HTTPS API. The example rejects redirects, requires explicit authorization before using a live key, and does not retry automatically. Production integrations should preserve the operation state before the first network call.
// Trusted CLI/backend worker. Do not run blocking I/O inside an async executor task.
use reqwest::{blocking::Client, redirect::Policy};
use serde_json::{json, Value};
use std::{env, error::Error, fs, io::Read, time::Duration};
fn run() -> Result<(), Box<dyn Error>> {
let key = env::var("SANCTIONSKIT_API_KEY")?;
let operation = env::var("SCREENING_OPERATION_ID")?;
if operation.is_empty() { return Err("missing operation ID".into()); }
if !key.starts_with("sk_test_") && !(key.starts_with("sk_live_") && env::var("ALLOW_LIVE_SCREENING").ok().as_deref() == Some("yes")) {
return Err("live operation not explicitly authorized".into());
}
let path = env::args().nth(1).unwrap_or_else(|| "../request.sandbox.json".to_owned());
let raw = fs::read(path)?;
if raw.len() > 65_536 { return Err("request file exceeds 64 KiB".into()); }
let body: Value = serde_json::from_slice(&raw)?;
if !body.is_object() || body.get("subject").is_none() || body.get("sources").is_some() == body.get("package").is_some() {
return Err("invalid request object".into());
}
let client = Client::builder().connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(25)).redirect(Policy::none()).build()?;
let response = client.post("https://www.sanctionskit.com/api/v1/screenings")
.bearer_auth(&key).header("Idempotency-Key", operation).json(&body).send()?;
let status_code = response.status();
let limit = 8 * 1024 * 1024;
let mut payload = Vec::new();
response.take((limit + 1) as u64).read_to_end(&mut payload)?;
if payload.len() > limit { return Err("oversized response".into()); }
if !status_code.is_success() { return Err("screening HTTP request incomplete".into()); }
let envelope: Value = serde_json::from_slice(&payload)?;
let data = envelope.get("data").ok_or("missing response data")?;
let id = data.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or("missing screening ID")?;
let status = data.get("status").and_then(Value::as_str).ok_or("missing screening status")?;
let matches = data.get("matches").and_then(Value::as_array).ok_or("missing matches array")?;
if !["potential_match", "no_match"].contains(&status) ||
(status == "no_match" && !matches.is_empty()) || (status == "potential_match" && matches.is_empty()) {
return Err("inconsistent screening response".into());
}
println!("{}", json!({"id":id,"status":status,"candidateCount":matches.len()}));
Ok(())
}
fn main() {
if run().is_err() {
// Do not print parser errors, submitted identity, or the raw response.
eprintln!("Screening incomplete. Check the operation before retrying.");
std::process::exit(1);
}
}Run the client
Run this from the directory containing request.json and the project files. Keep the API key out of committed files and shell tracing. The tutorial’s request-file limit is 64 KiB and its response parsing limit is 8 MiB; these are client safeguards, not claims about API service limits.
Use Result to carry failures rather than returning a synthetic no-match value. Configure reqwest with TLS, deadlines, and redirect rejection. Validate serde_json Value types before accessing fields. In an async application, use the async client or isolate this blocking work appropriately.
cargo run -- request.jsonChange to the required production coverage
The production example selects ofac-sdn only. Add ofac-non-sdn only when your required scope includes it, after checking current availability and compatibility. An SDN-only check is not a complete non-SDN check, and non-SDN records do not all have the same restrictions.
For an authorized production operation, replace the package field with the sources array shown below, supply the actual lawfully held subject details, use a live key, and set ALLOW_LIVE_SCREENING=yes. Keep the complete request in request.json and create a new operation ID. Do not send both sources and package. The fragment below is a coverage change, not a complete request.
{
"sources": [
"ofac-sdn"
]
}Preserve the source details a reviewer needs
Preserve source record IDs, list names, program context, aliases, date precision, and the actual fields that support or conflict with a candidate. A no-match result does not resolve OFAC’s 50 Percent Rule, geography-based restrictions, or the legality of a proposed activity.
Retain the screening ID with your internal subject reference. Retrieve the complete evidence through the documented retained-result workflow when authorized; the console summary deliberately does not print raw identity details. A later analyst decision must not overwrite the original screening outcome.
Handle failures and test the source-specific edge cases
Treat HTTP errors, timeouts, malformed JSON, missing fields, unknown statuses, and unavailable required coverage as incomplete checks. A 401 or 403 needs credential or scope correction. A 409 needs idempotency-conflict handling. A 429 needs its specific rate-limit or usage-cap treatment; it is not a no-match result.
Test similar names with different reliable birth years, overlapping year-only dates, and a source record with no comparable identifier. The absence of an identifier is unknown, not a conflict.
Exercise missing fields and type mismatches without unwrap-based fallback values. Test that a transport error returns Err and that the caller cannot interpret Err as a cleared customer.
- Verify both valid result states and inconsistent status/matches combinations.
- Retry an accepted operation only with its original key and unchanged payload.
- Keep missing identity facts unknown instead of inventing contradictory values.
- Route potential matches into review before the separate business decision.
- Keep secrets, submitted names, and raw error bodies out of routine logs.