SOLUTION:
function REDCapImportRecord() {
const url = 'https://redcap.INSTITUTION.edu/api/'
const testdata = [{
record_id: 'TEST123456',
testfield: 'test'
}]
const body = new FormData();
body.append('token', 'MYTOKEN');
body.append('content', 'record');
body.append('format', 'json');
body.append('data', JSON.stringify(testdata));
const params = {
method: 'POST',
body,
}
return fetch(url, params)
.then(data => {
console.log('fetch data: ', data)
})
.catch(error => console.log('Error: ', error))
}
Original question:
I'm creating a React Native app to interface with REDCap and am having difficulty utilizing the API in Javascript.
I've enabled all privileges on REDCap, and I'm able to make calls successfully using PHP and in the REDCap API Playground.
For the app, I'm using fetch:
async function REDCapImport() {
const url = 'https://redcap.med.INSTITUTION.edu/api/'
const testdata = {
record_id: 'TEST1234',
test_field: 'TEST'
}
const params = {
method: 'POST',
token: 'MYTOKEN',
content: 'record',
format: 'json',
type: 'flat',
overwriteBehavior: 'normal',
forceAutoNumber: false,
data: JSON.stringify(testdata),
returnContent: 'count',
returnFormat: 'json',
}
return await fetch(url, params)
.then(data => {
console.log('fetch data: ', data)
})
.then(response => console.log('Response: ', response))
.catch(error => console.log('Error: ', error))
}
}
Here is the PHP that works:
<?php
$data = array(
'token' => 'MYTOKEN',
'content' => 'record',
'format' => 'json',
'type' => 'flat',
'overwriteBehavior' => 'normal',
'forceAutoNumber' => 'false',
'data' => $testdata,
'returnContent' => 'count',
'returnFormat' => 'json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://redcap.med.upenn.edu/api/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));
$output = curl_exec($ch);
print $output;
curl_close($ch);
I get a 403 error:
It seems even that in the params object, if I remove the API token it doesn't change the error -- it still returns 403.
It works just fine in PHP, so I feel like I'm doing something wrong as my token and privileges indeed work.
Any help about how to get this request to work in Javascript would be greatly appreciated. Thanks!