Docs

Example: R


title: "R Example"

R Example

This example scores a CSV file using the Profile Scoring API with R and the httr2 package.

Prerequisites

install.packages(c("httr2", "jsonlite", "readr"))

Full example

library(httr2)
library(jsonlite)
library(readr)

api_key <- Sys.getenv("AUSYNTH_API_KEY")

# Upload and score
resp <- request("https://api.ausynth.com/api/score") |>
  req_headers(Authorization = paste("Bearer", api_key)) |>
  req_body_multipart(file = curl::form_file("my_customers.csv", type = "text/csv")) |>
  req_perform()

result <- resp |> resp_body_json()

if (result$status == "complete") {
  cat(sprintf("Scored %d rows, charged %d credits\n",
              result$rows_scored, result$credits_charged))

  # Download the scored CSV
  download.file(result$download_url, "scored_output.csv", mode = "wb")
  scored <- read_csv("scored_output.csv", show_col_types = FALSE)

  # Inspect the results
  print(head(scored[c("id", "profile_name", "profile_confidence")]))
  print(table(scored$profile_name))

} else if (result$status == "processing") {
  # Large file - poll for completion
  poll_url <- paste0("https://api.ausynth.com", result$poll_url)
  repeat {
    Sys.sleep(5)
    poll_resp <- request(poll_url) |>
      req_headers(Authorization = paste("Bearer", api_key)) |>
      req_perform()
    poll_result <- poll_resp |> resp_body_json()

    if (poll_result$status == "complete") {
      download.file(poll_result$download_url, "scored_output.csv", mode = "wb")
      cat(sprintf("Scored %d rows\n", poll_result$rows_scored))
      break
    }
    cat("Still processing...\n")
  }
}

Checking data quality flags

dq <- result$data_quality
if (!is.null(dq) && dq$rows_with_invalid_values > 0) {
  cat(sprintf("Warning: %d rows had unrecognised values\n", dq$rows_with_invalid_values))
  for (detail in dq$invalid_value_details[1:min(5, length(dq$invalid_value_details))]) {
    cat(sprintf("  Row %d: %s='%s' -> mapped to Not stated\n",
                detail$row, detail$field, detail$value))
  }
}

Handling errors

resp <- tryCatch(
  request("https://api.ausynth.com/api/score") |>
    req_headers(Authorization = paste("Bearer", api_key)) |>
    req_body_multipart(file = curl::form_file("my_customers.csv", type = "text/csv")) |>
    req_error(is_error = function(resp) FALSE) |>
    req_perform(),
  error = function(e) {
    cat("Request failed:", conditionMessage(e), "\n")
    NULL
  }
)

if (!is.null(resp)) {
  status <- resp_status(resp)
  if (status == 401) {
    cat("Invalid API key. Check AUSYNTH_API_KEY.\n")
  } else if (status == 402) {
    err <- resp |> resp_body_json()
    cat(sprintf("Need %d credits, have %d\n", err$credits_required, err$credits_available))
  } else if (status == 429) {
    err <- resp |> resp_body_json()
    cat(sprintf("Rate limited. Retry in %d seconds.\n", err$retry_after_seconds))
  }
}

Setting the API key

Set the environment variable before starting R:

export AUSYNTH_API_KEY="ask_live_abc123def456"
Rscript score_my_data.R

Or in your .Renviron file (not tracked by git):

AUSYNTH_API_KEY=ask_live_abc123def456