--- title: "Download Uploads" author: "SoSci Survey" date: "`r Sys.Date()`" output: html_document --- ## Preparation * Go to the user account, select **API Access** and create a new token that is allowed to read `/projects` and `/projects/uploads` (you can skip `/projects` if you already know the project's ID) * Copy the "API URL" and paste here the setup script below * Copy the "API key" and paste into the script ```{r setup, include=FALSE} # R setup block knitr::opts_chunk$set(echo = TRUE) # Insert the API URL below api_url <- "INSERT HERE" # Insert the API key below api_key <- "INSERT HERE" # Insert the project's ID below, # eventually to be added after running the "projects" block project_id <- 0 if (!require("pacman")) { install.packages("pacman") library("pacman") } p_load("httr2") ``` ## Projects Now, find the project's ID in this list (skip this code block if you already know the project's ID). ```{r projects, results='asis'} if (project_id < 1) { req <- request(paste(api_url, "/projects", sep="")) |> req_auth_bearer_token(api_key) resp <- req |> req_perform() api_projects <- resp |> resp_body_json() for (api_project in api_projects) { cat(paste(" * ID ", api_project$id, ": ", api_project$title, "\r\n", sep="")) } rm(api_projects, api_project, resp, req) } else { cat("Already set a project ID, skipping project listing retrieval.\r\n") } ``` **Note:** Write the project's ID to `project_id` in the setup block (if not already done). **Note:** Should you see an 401 error, make sure to grant the API key reading access to `/projects`. ## Download Uploads Download the uploads to ''/uploads''. ```{r download, results='asis'} if (project_id < 1) { cat("No project ID set, yet. Stopping processing.\r\n") } else { req <- request(paste(api_url, "/projects/", project_id, "/uploads", sep="")) |> req_auth_bearer_token(api_key) resp <- req |> req_perform() api_uploads <- resp |> resp_body_json() dir.create("uploads", showWarnings = FALSE) for (upload_filename in api_uploads$files) { # Skip download if the file already exists if (file.exists(paste("uploads", upload_filename, sep="/"))) { cat(paste(" * ", upload_filename, " (skipped, already present)\r\n", sep="")) } else { cat(paste(" * ", upload_filename, "\r\n", sep="")) # Download the file and store to /uploads req_file <- request( paste(api_url, "/projects/", project_id, "/uploads/", upload_filename, sep="") ) |> req_auth_bearer_token(api_key) req_file |> req_perform(path = paste("uploads", upload_filename, sep="/")) } } rm(upload_filename, api_uploads, resp, req, req_file) } rm(api_key, api_url, project_id) ``` **Note:** Should you see an 401 error, make sure to grant the API key reading access to `/projects/uploads`.