Developer guide

OFAC API in Ruby: screening and error handling

Build OFAC screening in Ruby with a complete HTTP example, explicit source selection, idempotency, safe failures, and review handoffs.

On this page

What this Ruby 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 Ruby 3.1 or later with its standard JSON, Net::HTTP, URI, and OpenSSL libraries. The script is intended for a backend or trusted CLI and needs no provider SDK.

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"
}

Send the request and validate the result

Save the client as screen.rb. 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.

# Ruby 3.1+. Standard library only. Backend or trusted CLI.
require 'json'
require 'net/http'
require 'uri'
require 'openssl'
begin
  key = ENV.fetch('SANCTIONSKIT_API_KEY')
  operation = ENV.fetch('SCREENING_OPERATION_ID')
  raise 'Operation ID must not be empty.' if operation.empty?
  unless key.start_with?('sk_test_') || (key.start_with?('sk_live_') && ENV['ALLOW_LIVE_SCREENING'] == 'yes')
    raise 'Use a test key, or explicitly authorize a live screening.'
  end
  raw = File.binread(ARGV[0] || '../request.sandbox.json')
  raise 'Request file exceeds 64 KiB.' if raw.bytesize > 65_536
  body = JSON.parse(raw)
  unless body.is_a?(Hash) && body['subject'] && (body.key?('sources') ^ body.key?('package'))
    raise 'Supply a subject and exactly one of sources or package.'
  end
  uri = URI('https://www.sanctionskit.com/api/v1/screenings')
  request = Net::HTTP::Post.new(uri)
  request['Authorization'] = "Bearer #{key}"
  request['Content-Type'] = 'application/json'
  request['Idempotency-Key'] = operation
  request.body = JSON.generate(body)
  payload = +''
  status = 0
  Net::HTTP.start(uri.host, uri.port, use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_PEER,
                  open_timeout: 10, read_timeout: 25, write_timeout: 25) do |http|
    http.max_retries = 0
    http.request(request) do |response|
      status = response.code.to_i
      response.read_body do |chunk|
        raise 'Response size limit exceeded.' if payload.bytesize + chunk.bytesize > 8 * 1024 * 1024
        payload << chunk
      end
    end
  end
  # Net::HTTP does not automatically follow redirects.
  envelope = JSON.parse(payload)
  raise "Screening incomplete: HTTP #{status}." unless (200...300).cover?(status)
  data = envelope.is_a?(Hash) ? envelope['data'] : nil
  unless data.is_a?(Hash) && data['id'].is_a?(String) && !data['id'].empty? &&
         %w[potential_match no_match].include?(data['status']) && data['matches'].is_a?(Array)
    raise 'Incomplete response: unexpected screening shape.'
  end
  count = data['matches'].length
  if (data['status'] == 'no_match' && count != 0) || (data['status'] == 'potential_match' && count == 0)
    raise 'Incomplete response: inconsistent screening shape.'
  end
  puts JSON.generate(id: data['id'], status: data['status'], candidateCount: count)
rescue StandardError => error
  warn "Screening did not complete: #{error.class}. Check the operation before retrying."
  exit 1
end

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.

Net::HTTP does not treat an unsuccessful response as a screening decision. Inspect the status explicitly and configure connection, read, and write timeouts. The example disables automatic retries and checks Hash and Array types before using the envelope.

ruby screen.rb request.json

Change 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.

Test the response-body reader with several chunks rather than only one small string. Verify that a size-limit failure, a nil data value, and a non-array matches field all leave the operation incomplete.

  • 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.

Official references