elow you will find links to libraries and also examples of code in various programming languages for connecting to the REDCap API. Each section below represents a different programming language.

Please also take a look at the list of know REDCap API packages in various languages.

Python

A simple Python library called PyCap (Python and REDCap) has been created for communicating with REDCap projects from Python applications. It mimics the REDCap API as much as possible and is designed to be very easy to use.http://sburns.github.com/PyCap/

VBA (Microsoft Access)

The following code requires a reference to the Microsoft XML object library - v3.0 (msxml3.dll).  

The function is tolerant of form changes in that it is designed to import only those columns whose names match between the REDCap form and the MSAccess table. It accomplishes this by checking the column name of each datum against a string of valid names, so it is not particularly efficient. If you know that every column name in the REDCap form also exists in the MSAccess table, and if the import is hideously time-consuming, you should remove that bit of code.

Developer: (Pete Charpentier peter.charpentier@yale.edu)

  1. ' --- getREDCapFormData() ---
  2. ' Function to import REDCap data into MSAccess
  3. ' February 2013. Peter Charpentier / Yale Program on Aging
  4. '
  5. ' calls REDCap API to retrieve form data, then repopulates local table
  6. '
  7. ' requires a reference to Microsoft XML, v3.0 (msxml3.dll)
  8. '
  9. ' ref: http://support.microsoft.com/kb/290591
  10. ' http://support.microsoft.com/kb/290591
  11. ' --- parameters ---
  12. ' strFormname - REDCap form name, or a list of forms per API rules
  13. ' strTablename - local MSAccess table name
  14. ' strToken - a REDCap API token
  15. ' strURL - redcap API location, eg "https://redcap.someplace.edu/api/"
  16. '
  17.  
  18. Public Function getREDCapFormData( _
  19. strFormname As String, strTablename As String, _
  20. strToken As String, strURL As String) As Long
  21. Dim objHTTP As New MSXML2.ServerXMLHTTP
  22. Dim objXML As MSXML2.DOMDocument
  23. Dim strPost As String
  24. Dim K As Long
  25. On Error GoTo errHTTP
  26. strPost = "token=" & strToken _
  27. & "&content=record" _
  28. & "&format=xml" _
  29. & "&type=flat" _
  30. & "&forms=" & strFormname
  31. ' call the API and get an XML string that contains the table data
  32. ' ..set some robust timeouts.. the API is slow
  33. Call objHTTP.setTimeouts(15000, 15000, 15000, 15000)
  34. Call objHTTP.Open("POST", strURL, False)
  35. Call objHTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
  36. Call objHTTP.Send(strPost)
  37. ' the responseXML property is a parsed XML object
  38. Set objXML = objHTTP.responseXML
  39. ' recreate the local table
  40. K = processREDCapXML(objXML, strTablename)
  41. exitHere:
  42. getREDCapFormData = K
  43. Exit Function
  44. errHTTP:
  45. MsgBox "getREDCapFormData reports error #" & Err.Number & ": " & Err.Description
  46. K = -1
  47. Resume exitHere
  48. End Function
  49.  
  50. ' populates local table from XML string
  51. ' returns number of records created, or -1 on error
  52. ' ref: http://support.microsoft.com/kb/290591
  53.  
  54. Private Function processREDCapXML( _
  55. objXML As MSXML2.DOMDocument, strTablename As String) As Long
  56. Dim ndeRecord As MSXML2.IXMLDOMNode
  57. Dim ndeColumn As MSXML2.IXMLDOMNode
  58. Dim colName As String, colValue As String
  59. Dim K As Long
  60. Dim R As DAO.Recordset
  61. Dim strFieldList As String, objFld As DAO.Field
  62. K = 0 ' record kount, also return kode
  63. ' empty the local table and open it
  64. DoCmd.RunSQL "DELETE FROM " & strTablename
  65. Set R = CurrentDb.OpenRecordset(strTablename, dbOpenDynaset)
  66. ' build the column list from the local table.
  67. ' Only columns defined in the local table, ie found in this string,
  68. ' will be imported.
  69. strFieldList = ""
  70. For Each objFld In R.Fields
  71. strFieldList = strFieldList & "[" & objFld.Name & "]"
  72. Next
  73. On Error GoTo errXML
  74. ' walk through the DOM nodes to recreate the table
  75. ' the XML structure returned by REDCap API is a
  76. ' 3-deep sequence of nodes
  77. ' <records>
  78. ' <item>
  79. ' <colname>
  80. ' colValue
  81. ' </colName>'
  82. ' ...
  83. ' </item>
  84. ' ...
  85. ' </records>
  86. ' (documentElement is the root node (<records>))
  87. For Each ndeRecord In objXML.documentElement.childNodes
  88. K = K + 1
  89. R.AddNew
  90. For Each ndeColumn In ndeRecord.childNodes
  91. colName = ndeColumn.nodeName
  92. ' is this column in the local table?
  93. If InStr(strFieldList, "[" & colName & "]") > 0 Then
  94. ' a column node may have 0 or 1 child (the value)
  95. If ndeColumn.childNodes.length > 0 Then
  96. colValue = ndeColumn.childNodes(0).nodeValue
  97. ' if the REDCap table structure differs from the
  98. ' local table, we'll find out here
  99. R(colName) = colValue
  100. End If
  101. End If
  102. Next ndeColumn
  103. R.Update
  104. Next ndeRecord
  105. endXML:
  106. On Error Resume Next
  107. R.Close
  108. Set R = Nothing
  109. processREDCapXML = K
  110. Exit Function
  111. errXML:
  112. MsgBox "processREDCapXML reports error #" & Err.Number _
  113. & ": " & Err.Description _
  114. & vbCrLf & vbCrLf _
  115. & "Error occured at formName = """ & strTablename _
  116. & """, colName = """ & colName & """ and colValue = """ & colValue & """"
  117. K = -1
  118. Resume endXML
  119. End Function

Stata

The strategy here is to use Stata's shell command to call out to curl to exchange data with REDCap.

Requirement: curl Software. See Section "Command Line Interface" on how to get curl

Download records: Issue the command, all on one line

  1. shell curl --output file
  2. --form token=APIToken
  3. --form content=record
  4. --form format=csv
  5. --form type=flat
  6. https://localhost/redcap/api/

whereAPITokenis your REDCap API token This will create the CSVfile filewith field names as the first row.

Then import the data into Stata using the command

  1. import delimited using file, varnames(1) clear

Upload records: Export the data into a CSV file namedcsvfile with REDCap field name as the first line

  1. export delimited using csvfile, delim(“,”) nolabel replace

Then uploadcsvfileto REDCap using

  1. shell curl --form token=APIToken
  2. --form content=record
  3. --form format=csv
  4. --form type=flat
  5. --form data=”<csvfile
  6. https://localhost/redcap/api/

whereAPITokenis your REDCap API Token andcsvfileis the CSV file.

Upload and Download file from REDCap: To upload the file myfile as displayname to the File Upload Field file_field for the record record_id and event event_name

  1. shell curl --form token=APIToken
  2. --form content=file
  3. --form action=import
  4. --form field=file_field
  5. --form record=record_id
  6. --form event=event_name
  7. --form "file=@myfile;filename=displayname"
  8. https://localhost/redcap/api/

This command (all on one line) will reverse the process and download file from REDCap to the your computer as file downloadfile.

  1. shell curl --output downloadfile
  2. --form token=APIToken --form content=file
  3. --form action=export --form record=record
  4. --form event=event_name
  5. --form field=file_field
  6. https://localhost/redcap/api/

You can replace --output downloadfile with -O (capital 'O') to download myfile as file displayname in your current directory.

For more Stata examples go to https://github.com/lsgs/REDCap-API-and-Stata

R

There are two actively-developed R packages for REDCap (as of Oct 2014), redcapAPI and REDCapR. Entire operations typically require a line of two of R code. To see additional documentation or ask the developers questions, please see their development sites (redcapAPI and REDCapR). Thepackagesincludeextraerrorchecking, and facilitate many types of REDCap operations. Here is an example of each package exporting records from the server.

  1. # Set the url to the api (ex. https://YOUR_REDCAP_INSTALLATION/api/)
  2. api_url = 'https://YOUR_REDAP_INSTALLATION/api/'
  3.  
  4. # Set secret token specific to your REDCap project
  5. secret_token = 'SECRET_TOKEN'
  6.  
  7. ## Export with redcapAPI
  8. library(redcapAPI)
  9. rcon <- redcapAPIredcapConnection(url=api_url, token=secret_token) #Create a connection.
  10. myData <- exportRecords(rcon) #Call the server.
  11.  
  12. ## Export with REDCapR
  13. library(REDCapR)
  14. response <- redcap_read(redcap_uri=api_url, token=secret_token) #Call the server.
  15. ds <- response$data #Isolate the returned data.frame.

To call the API without redcapAPI or REDCapR, it's still advisable to use the RCurl or httr packages to facilitate the communication. Here is an example using RCurl.

  1. # Load needed libraries
  2. # --> NOTE: RCurl is dependent on bitops
  3. library(bitops)
  4. library(RCurl)
  5.  
  6. # Set the url to the api (ex. https://YOUR_REDCAP_INSTALLATION/api/)
  7. api_url = 'https://YOUR_REDAP_INSTALLATION/api/'
  8.  
  9. # Set secret token specific to your REDCap project
  10. secret_token = 'SECRET_TOKEN'
  11.  
  12. curl_handle = getCurlHandle()
  13. curlSetOpt(ssl.verifypeer = FALSE, curl = curl_handle)
  14. ## Read all data from REDCap
  15. y <- postForm(api_url,
  16. token = secret_token,
  17. content = 'record',
  18. format = 'csv',
  19. type = 'flat',
  20. form = 'demographics',
  21. curl = curl_handle)
  22. # Use the output from postForm() to create a data frame of the exported data
  23. x <- read.table(file = textConnection(y), header = TRUE, sep = ",", na.strings = "",
  24. stringsAsFactors = FALSE)
  25. rm(secret_token, y)
  26.  
  27. ## Alternative code:
  28. #write(y, file = "data_file.csv");
  29. #x <- read.table("data_file.csv", sep = ",", header = TRUE, na.strings = "")
  30.  

Matlab

Examples are in the attachment api_matlab.zip

Useurlreadto read/write record and download file.

For file upload, use redcapreadpostwhichisattachedasapi_matlab.zip. redcapreadpostisamodificationofurlreadpostwhichisavailableinsidethesamezipattachmentorfromMATLAB Central athttp://www.mathworks.com/matlabcentral/fileexchange/27189-urlreadpost-url-post-method-with-binary-file-uploading

urlreadpostcanuploadfiles. Itwillhoweverinsistonusingdummyasthe file name displayed on REDCap.redcapreadpostremove that restriction by allowing you to specify the display file name.

See also urlread2 at Matlab File Exchange. (On Oct 4th2012, the link is http://www.mathworks.com/matlabcentral/fileexchange/35693-urlread2 with a blog post on http://undocumentedmatlab.com/blog/expanding-urlreads-capabilities/ describing its function). Ithasthepotentialtoreplaceredcapredpost,urlreadpostandurlrread. However, I (Cinly Ooi) had never tested its claims.

Notes from 2017-05 by @andy.martin, we had luck using webread which allows some more flexibility in the headers (although we aren't using it) - but this worked:

  1. disp('************************');
  2. disp('Download a file from a subject record');
  3. disp('************************');
  4. options = weboptions('RequestMethod','post');
  5. data = webread(...
  6. 'https://redcap.stanford.edu/api/',...
  7. 'token', 'xxx', ...
  8. 'content', 'record',...
  9. 'records', '1',...
  10. 'format', 'csv',...
  11. 'returnFormat', 'csv', options);
  12. % WRITE CSV FILE
  13. fid = fopen('test.csv','w')
  14. fprintf(fid,'%s',data)
  15. fclose(fid)

Command Line Interface

Uses curl. On Unix and Linux, it is probably already installed as REDCap list the PHPversionofitasaoptionalmodule. If not, use your package manager to download and install curl. Windows user should follow the procedure below

  1. Download the appropriate zip package from http://curl.haxx.se/download.html. Use “SSL, SSH” version if you are unsure
  2. Create the folder C:\Users\USR\local\wbin where USR is your username on the computer. Unzip and place the content of the zip file here. In other words,youshouldbeabletorefers to curlasC:\Users\USR\local\wbin\curl.exe
  3. On the Desktop, right click My Computer, select properties -> Advanced settings -> Environment Variables, then edit the path variable adding the text ";C:\Users\USR\local\wbin\" without quotation marks. Be careful not to add a space between the semi-colon and the directory name. (This step is optional, but will save you from having to use the full path to curl.exe every time you want to use curl.
  1. ### SET THESE VARIABLES
  2. SERVICE="http:///myserver/redcap/api/"
  3. TOKEN="replaceWithYourToken"
  4.  
  5. #DOWNLOAD all records, except file
  6. curl -F token=${TOKEN} -F content=record -F format=csv -F type=flat ${SERVICE}
  7.  
  8. #DOWNLOAD a file from REDCAP from field MYFILE and record MYRECORDNUM
  9.  
  10. curl -F token=${TOKEN} -F content=file -F action=export -F record=MYRECORDNUM -F field=MYFILE ${SERVICE}
  11. #UPLOAD a flat csv record contain in file file (/path/to/my.csv)
  12. # Note the use of '<' to get curl to read in data from external file
  13.  
  14. curl --form token=${TOKEN} \
  15. --form overwriteBehavior=normal \
  16. --form content=record
  17. --form format=csv
  18. --form type=flat \
  19. --form data="</path/to/my.csv" \
  20. ${SERVICE}
  21.  
  22. #UPLOAD a file (/path/to/myfile.txt) to field MYFILE for the record MYRECORDNUM and use 'display.txt' as the file name REDCap will display.
  23. # Note the use of '@' to get curl to read the file as a file attachment
  24.  
  25. curl --form token=${TOKEN} \
  26. --form content=file \
  27. --form action=import \
  28. --form field=MYFILE \
  29. --form record=MYRECORDNUM
  30. --form file="@/path/to/myfile.txt;filename=display.txt" \
  31. ${SERVICE}

Java

ode below uses httpcore.jar and httpclient.jar from Apache HttpComponents

  1. String token = "your_token_here";
  2. HttpClient httpclient = new DefaultHttpClient();
  3. HttpPost httppost = new HttpPost("http://redcap_url_here/redcap/api/");
  4.  
  5. try {
  6. List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
  7. nameValuePairs.add(new BasicNameValuePair("action", "export"));
  8. nameValuePairs.add(new BasicNameValuePair("token", token));
  9. nameValuePairs.add(new BasicNameValuePair("content", "record"));
  10. nameValuePairs.add(new BasicNameValuePair("format", "csv"));
  11. nameValuePairs.add(new BasicNameValuePair("type", "flat"));
  12. httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  13.  
  14. HttpResponse response = httpclient.execute(httppost);
  15. BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  16. String line = null;
  17. while((line = in.readLine()) != null) {
  18. System.out.println(line);
  19. }
  20.  
  21. } catch (ClientProtocolException e) {
  22. e.printStackTrace();
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }

PHP

  1. require_once('RestCallRequest.php');
  2.  
  3. $token = "REPLACE WITH PROJECT TOKEN";
  4. $api_url = "APP_PATH_WEBROOT_FULL.'api/' ## if being used in a REDCap plugin
  5. $api_url = "http://redcap.EXAMPLE.org/redcap/api" ## path to the REDCap API on another server
  6.  
  7. # arrays to contain elements you want to filter results by
  8. # example: array('item1', 'item2', 'item3');
  9. $records = array();
  10. $events = array();
  11. $fields = array();
  12. $forms = array();
  13.  
  14. # an array containing all the elements that must be submitted to the API
  15. $api_parameters = array('content' => 'record', 'type' => 'flat', 'format' => 'json', 'records' => $records, 'events' => $events,
  16. 'fields' => $fields, 'forms' => $forms, 'exportSurveyFields'=>'false',
  17. 'exportDataAccessGroups'=>'false',
  18. 'token' => $token, 'rawOrLabel' => 'label');
  19.  
  20. # create a new API request object
  21. $request = new RestCallRequest($api_url, 'POST', $api_parameters);
  22.  
  23. # initiate the API request
  24. $request->execute();
  25.  
  26. ## this example creates a PHP array called $data that contains the results
  27. ##
  28. $jsondata = $request->getResponseBody();
  29. $json_decoded = json_decode($jsondata, TRUE);
  30. $data = $json_decoded;
  31.  

Powershell

  1. ##
  2.  
  3. # This Windows PowerShell script requires curl.
  4. # Please make sure you have the module
  5.  
  6. # Set the destination path and filename
  7. $FOLDER = "H:\REDCap_Data\"
  8. $FILENAME = "CV_Perfusion.csv"
  9.  
  10. # Set secret token specific to your REDCap project
  11. $TOKEN = "SECRET_TOKEN"
  12.  
  13. # Set the url to the api (ex. https://YOUR_REDCAP_INSTALLATION/api/)
  14. $SERVICE = "https://YOUR_REDCAP_INSTALLATION/api/"
  15.  
  16. # Set the path to cURL module (ex. H:\Scripts\curl.exe)
  17. $CURL = "H:\Scripts\curl.exe "
  18.  
  19. # Set the cURL parameters
  20. $SWITCHES = " -F token=$TOKEN " +
  21. " -F content=record " +
  22. " -F rawOrLabel=label " +
  23. " -F format=csv " +
  24. " -F type=flat "
  25. #### No need to change anything below this line
  26. #
  27. #
  28.  
  29. # DOWNLOAD all records
  30. $command = $CURL + $SWITCHES + $SERVICE
  31.  
  32. $Res = invoke-expression $command
  33.  
  34. # Save to .csv
  35. $PATH = $FOLDER + $FILENAME
  36.  
  37. $Res |
  38. ConvertFrom-CSV |
  39. Export-CSV -Path $PATH -NoTypeInformation




  • No labels