Code samples · Swift

Swift code samples

Copy-paste Swift examples that validate one address, send the API key in the Authorization header, retry 429 and 503 answers after Retry-After when the wait is at most 10 seconds (never key_daily_cap, which lasts until the next UTC day), and report other errors with their code and request id. Each uses the free test address accepted@sandbox.email-validation.org; replace it with a real address when you are ready. The same samples in other languages: all code samples.

Set your key first: export EV_API_KEY="ev_live_…".

The samples call https://api.email-validation.org. For EU data residency, replace it with https://api-eu.email-validation.org, or pass the SDK's EU base URL constant; there /v1/validate takes POST only (EU data residency).

With the official SDK

The official Swift SDK does the retries, timeouts and error mapping for you: one call validates an address and every failure arrives as a typed error. There are official SDKs for JavaScript/TypeScript, Python, Go, PHP, Ruby, C#, Rust and Swift; those for Java, Kotlin, Dart, Elixir, C and Perl are built and tested and coming soon to their package registries. The plain HTTP samples further down call the API directly.

Swift

import EmailValidation
import Foundation

let client = try EmailValidationClient(apiKey: ProcessInfo.processInfo.environment["EV_API_KEY"] ?? "")

do {
    let result = try await client.validate("accepted@sandbox.email-validation.org")
    print(result.status, result.reason, result.action)  // valid accepted send
} catch let error as EmailValidationError where error.kind == .insufficientCredits {
    print("buy credits; nothing was charged")
} catch let error as EmailValidationError {
    print(error.code, error.requestId ?? "-")
}

Validate an address

Swift

import Foundation

struct ValidationResult: Decodable {
    let status: String
    let reason: String
    let action: String
    let creditsUsed: Int

    enum CodingKeys: String, CodingKey {
        case status, reason, action
        case creditsUsed = "credits_used"
    }
}

struct ErrorEnvelope: Decodable {
    struct APIError: Decodable {
        let code: String
        let message: String
        let requestId: String

        enum CodingKeys: String, CodingKey {
            case code, message
            case requestId = "request_id"
        }
    }

    let error: APIError
}

struct ValidationFailed: Error {
    let description: String
}

func validate(_ email: String, attempts: Int = 3) async throws -> ValidationResult {
    var request = URLRequest(url: URL(string: "https://api.email-validation.org/v1/validate")!)
    request.httpMethod = "POST"
    request.timeoutInterval = 20
    let key = ProcessInfo.processInfo.environment["EV_API_KEY"] ?? ""
    request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try JSONEncoder().encode(["email": email])

    var attempt = 0
    while true {
        attempt += 1
        let (data, response) = try await URLSession.shared.data(for: request)
        let http = response as! HTTPURLResponse
        if http.statusCode == 200 {
            return try JSONDecoder().decode(ValidationResult.self, from: data)
        }
        let error = try JSONDecoder().decode(ErrorEnvelope.self, from: data).error
        // Never wait out a long Retry-After: key_daily_cap lasts until the next UTC day.
        let wait = max(1, Int(http.value(forHTTPHeaderField: "Retry-After") ?? "") ?? 1)
        let retryable = (http.statusCode == 429 || http.statusCode == 503) && error.code != "key_daily_cap" && wait <= 10
        if retryable && attempt < attempts {
            try await Task.sleep(nanoseconds: UInt64(wait) * 1_000_000_000)
            continue
        }
        throw ValidationFailed(description: "\(error.code): \(error.message) (\(error.requestId))")
    }
}

let result = try await validate("accepted@sandbox.email-validation.org")
// the verdict only: never print or log the address itself
print(result.status, result.reason, result.action, result.creditsUsed)

Other calls

  • Read the credit balance: samples in curl, JavaScript and Python (all code samples).
  • Create a bulk job: samples in curl, JavaScript and Python (all code samples).
  • Verify a webhook: samples on Webhooks and in JavaScript, TypeScript, Python, PHP, Ruby, Go, Java and C# (all code samples).

Notes

  • Use POST with a JSON body; it keeps addresses out of URLs and logs.
  • Set the HTTP timeout to about 20 seconds: a check may take up to 15 seconds (10 by default).
  • A 200 answer with the status unknown is a normal, free result, not an error.
  • Every endpoint, field and error: the API reference.

Updated · Maintained by: Email Validation LLC

Need help? Contact support, or ask the help chat. Something wrong or missing on this page? Tell us