Developer guide

OFAC API in Swift: screening and error handling

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

On this page

What this Swift 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 Swift 6 with Foundation. This is a trusted CLI or server-side Swift example. Never embed a SanctionsKit API key in an iPhone, iPad, Apple TV, or macOS client distributed to end users; those apps should call your authenticated backend.

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

// Swift 6. Server or trusted CLI only. Do not ship an API key in an iOS app.
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

struct ScreeningFailure: Error { let message: String }
final class NoRedirect: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
    func urlSession(_ session: URLSession, task: URLSessionTask,
                    willPerformHTTPRedirection response: HTTPURLResponse,
                    newRequest request: URLRequest,
                    completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) }
}
@main struct Screen {
    static func main() async {
        do { try await run() }
        catch {
            // Do not print the request, credential, or raw response.
            FileHandle.standardError.write(Data("Screening incomplete. Check the operation before retrying.\n".utf8))
            exit(1)
        }
    }
    static func run() async throws {
        let env = ProcessInfo.processInfo.environment
        guard let key = env["SANCTIONSKIT_API_KEY"], let operation = env["SCREENING_OPERATION_ID"], !operation.isEmpty else {
            throw ScreeningFailure(message: "Missing credential or operation ID")
        }
        guard key.hasPrefix("sk_test_") || (key.hasPrefix("sk_live_") && env["ALLOW_LIVE_SCREENING"] == "yes") else {
            throw ScreeningFailure(message: "Live operation not explicitly authorized")
        }
        let path = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "../request.sandbox.json"
        let raw = try Data(contentsOf: URL(fileURLWithPath: path))
        guard raw.count <= 65_536,
              let body = try JSONSerialization.jsonObject(with: raw) as? [String: Any],
              body["subject"] != nil, (body["sources"] != nil) != (body["package"] != nil) else {
            throw ScreeningFailure(message: "Invalid request object")
        }
        var request = URLRequest(url: URL(string: "https://www.sanctionskit.com/api/v1/screenings")!)
        request.httpMethod = "POST"; request.httpBody = raw
        request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(operation, forHTTPHeaderField: "Idempotency-Key")
        let configuration = URLSessionConfiguration.ephemeral
        configuration.timeoutIntervalForRequest = 25; configuration.timeoutIntervalForResource = 30
        let session = URLSession(configuration: configuration, delegate: NoRedirect(), delegateQueue: nil)
        defer { session.invalidateAndCancel() }
        // URLSession download avoids retaining an unbounded response in memory.
        let (file, response) = try await session.download(for: request)
        defer { try? FileManager.default.removeItem(at: file) }
        let size = try file.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
        guard size <= 8 * 1024 * 1024, let http = response as? HTTPURLResponse,
              (200..<300).contains(http.statusCode) else { throw ScreeningFailure(message: "Incomplete HTTP response") }
        let payload = try Data(contentsOf: file)
        guard let envelope = try JSONSerialization.jsonObject(with: payload) as? [String: Any],
              let data = envelope["data"] as? [String: Any], let id = data["id"] as? String, !id.isEmpty,
              let status = data["status"] as? String, ["potential_match", "no_match"].contains(status),
              let matches = data["matches"] as? [Any],
              (status == "no_match" ? matches.isEmpty : !matches.isEmpty) else {
            throw ScreeningFailure(message: "Unexpected screening response")
        }
        let summary: [String: Any] = ["id":id, "status":status, "candidateCount":matches.count]
        FileHandle.standardOutput.write(try JSONSerialization.data(withJSONObject: summary))
        FileHandle.standardOutput.write(Data("\n".utf8))
    }
}

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 an ephemeral URLSession, explicit timeouts, and a delegate that declines redirects. The example downloads the response to a temporary file, checks its size, validates the JSON shape, and removes the file. The post-download limit protects parsing memory, not a complete production disk quota.

swiftc -parse-as-library Screen.swift -o screen
./screen 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 with URLProtocol where supported or a test-only local transport. Verify missing id, a number in status, matches encoded as an object, and cancellation. Keep async network work outside the user-interface approval decision.

  • 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