In this tutorial, you will learn how to use the RedCap API to download and upload files from and to your RedCap project. The RedCap API allows you to interact with your project programmatically, enabling the automation of data transfers such as downloading and uploading files.
To interact with the RedCap API, you need an API token. This token is used to authenticate your requests. Follow the steps below to get your token:
Save this token securely as it will be needed to authenticate your requests.
Before you can interact with the RedCap API, you need to create a config.r file. This file will store your API token and the RedCap URL. Use the example config_example.r provided in the repository.
Here is an example of how your config.r file should look:
api_token <- 'YOUR_API_TOKEN' # Replace with your personal API token
api_url <- 'https://redcap.au.dk/api/' #change this url to your RedCAP url (e.g. 'https://redcap.wustl.edu/')Important: Keep this file secure. If you are working with sensitive
data, make sure not to share this file or commit it to a public
repository. If you use Git, make sure you add a
.gitignore file and add config.R to it (or
consider storing it outside of the project directory). You can take a
look at the gitignore file in this repository for inspiration.
You can use the export_file_from_redcap function to
download files from RedCap. The function requires three arguments:
Example: Once your configuration file is set up, you can use the following code to download a file. Replace record_id and fieldname with your actual record ID and field name:
Let’s assume you have multiple records and files that need to be
processed. You can use the preprocess_WRIC_files function to download
and process files for multiple records. You need to specify the record
IDs in your project, and the easiest is if you save them in a .csv file.
The function has arguments very similar to function
preprocess_WRIC_file (and the function name is only
different in the additional s in the end):
The function returns a list where each key is a record ID, and the corresponding value is another list containing R1_metadata, R2_metadata, df_room1, df_room2.
Example: Assuming you have a CSV file (record_ids.csv) with record IDs and a fieldname of “WRIC_raw”, you can call the function like this:
You can upload files to RedCap using the
upload_file_to_redcap function. This function requires:
Example: To upload a file, use the following code, replacing filepath, record_id, and fieldname with your actual file path, record ID, and field name:
upload_file_to_redcap(filepath = "./example_data/XXXX_WRIC_data.csv",
record_id = "12345", fieldname = "WRIC_processed")Remember to delete the tmp folder after uploading the files again.