Skip to content

Instantly share code, notes, and snippets.

@nutterb
Forked from couthcommander/filerepo_example.R
Last active March 21, 2023 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nutterb/bc6ecbe51a1c54cb94ed1731112c1929 to your computer and use it in GitHub Desktop.
Save nutterb/bc6ecbe51a1c54cb94ed1731112c1929 to your computer and use it in GitHub Desktop.
fileRepository API functionality
library(redcapAPI)
key <- ''
rcon <- redcapConnection("https://redcap.vanderbilt.edu/api/", key, conn, 'MatchedRandomization1')
fr_ls <- function(rcon, folder_id = NA, recursive = FALSE) {
args <- list(content = 'fileRepository', action = 'list', format = 'csv')
if(!is.na(folder_id)) {
args$folder_id <- folder_id
parent <- folder_id
} else {
parent <- 'top-level'
}
# need to call once, and convert to DF if any data
has_res <- nchar(makeApiCall(rcon, body = args)) > 0
if(!has_res) return(NULL)
root <- makeApiCall(rcon, args)
root <- cbind(parent_folder = parent, root)
if(recursive) {
fids <- root[!is.na(root[,'folder_id']), 'folder_id']
if(length(fids)) {
addl <- do.call(rbind, lapply(fids, fr_ls, rcon = rcon, recursive = TRUE))
root <- rbind(root, addl)
}
}
root
}
myfile <- '~/Downloads/tennessee-history.csv'
fr_ls(rcon, recursive = TRUE)
makeApiCall(rcon, body = list(content='fileRepository', action='createFolder', name = 'rcode'))
tmp <- fr_ls(rcon)
rcode_id <- tmp[tmp[,'name'] == 'rcode','folder_id']
makeApiCall(rcon, body = list(content='fileRepository', action='createFolder', folder_id=rcode_id, name = 'check'))
tmp <- fr_ls(rcon, folder_id=rcode_id)
check_id <- tmp[tmp[,'name'] == 'check','folder_id']
fh <- httr::upload_file(myfile)
makeApiCall(rcon, body = list(content='fileRepository', action='import', folder_id=check_id, file=fh))
tmp <- fr_ls(rcon, recursive = TRUE)
file_id <- tmp[tmp[,'name'] == basename(myfile),'doc_id']
data <- makeApiCall(rcon, body = list(content='fileRepository', action='export', doc_id=file_id))
data <- read.csv(text = as.character(data),
stringsAsFactors = FALSE,
na.strings = "")
makeApiCall(rcon, body = list(content='fileRepository', action='delete', doc_id=file_id))
## you can't delete a directory with the API!
# makeApiCall(rcon, body = list(content='fileRepository', action='delete', folder_id=check_id))
fr_ls(rcon, recursive = TRUE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment