# SDK de Datlase para R (paquetes httr2 y jsonlite). # # source("datlase.R") # dl <- datlase("dlk_...", "https://tu-servidor/api/v1") # reg <- dl_records(dl, "D087", place = "XA-NO", max = 5000) # data.frame # tab <- dl_analytics(dl, "XA", c("D087:count", "pop"), level = "state", per_capita = TRUE) library(httr2); library(jsonlite) datlase <- function(token, base_url = "https://datlase.com/api/v1") list(token = token, base = sub("/$", "", base_url)) dl_request <- function(dl, path, query = list(), method = "GET", body = NULL) { query <- Filter(Negate(is.null), lapply(query, function(v) if (length(v) > 1) paste(v, collapse = ",") else v)) req <- request(paste0(dl$base, path)) |> req_auth_bearer_token(dl$token) |> req_url_query(!!!query) |> req_method(method) |> req_retry(max_tries = 4, is_transient = function(r) resp_status(r) %in% c(429, 500, 502, 503)) |> req_error(body = function(r) tryCatch(resp_body_json(r)$error, error = function(e) "error")) if (!is.null(body)) req <- req_body_json(req, body) fromJSON(resp_body_string(req_perform(req)), simplifyVector = FALSE) } dl_datasets <- function(dl, ...) { d <- fromJSON(toJSON(dl_request(dl, "/datasets", list(...))$data, auto_unbox = TRUE)); d } dl_records <- function(dl, dataset, ..., max = Inf) { q <- list(..., limit = 500); out <- list(); n <- 0 repeat { p <- dl_request(dl, paste0("/datasets/", dataset, "/records"), q) out <- c(out, p$data); n <- n + length(p$data) if (is.null(p$next_cursor) || n >= max) break q$cursor <- p$next_cursor } fromJSON(toJSON(head(out, max), auto_unbox = TRUE), flatten = TRUE) } dl_analytics <- function(dl, scope, metrics, level = "children", from = NULL, to = NULL, per_capita = FALSE) { r <- dl_request(dl, "/analytics", list(scope = scope, metrics = metrics, level = level, from = from, to = to, pc = if (per_capita) 1 else NULL)) rows <- lapply(r$data, function(x) c(list(code = x$code, name = x$name, population = if (is.null(x$population)) NA else x$population), lapply(x$values, function(v) if (is.null(v)) NA else v))) df <- do.call(rbind, lapply(rows, as.data.frame, check.names = FALSE)); attr(df, "correlation") <- r$correlation; df } dl_series <- function(dl, scope, metric, places = NULL, yearly = FALSE) dl_request(dl, "/analytics/series", list(scope = scope, metrics = metric, places = places, grain = if (yearly) "year" else "month")) dl_submit <- function(dl, dataset, records, mode = "append") dl_request(dl, paste0("/datasets/", dataset, "/records"), method = "POST", body = list(records = records, mode = mode))