Calling API endpoints is usually done only from the backend to prevent the API token from being exposed publicly which poses a security risk if anyone were to access the token and abuse it to retrieve data from your application with malicious intent.
But there are some cases, where the circumstances require you to call the API from the front end directly. To ensure, this is done securely, we provide you below with a few options on how to accomplish this, depending on the type of API endpoint that you need to call.
API Wrapper Method
We provide you with a JavaScript function tp.api.callApi() that allows you to call anon endpoints (that don’t require an API token) from the front end.
The available endpoints and individual examples are listed here.
This mostly includes checking access, retrieving information about signed-in users or logging conversions.
PHP Code Method
This option will be based on calling a PHP code from your website, which will be securely hosted on your server, so the API token isn’t exposed publicly.
An example of such a code can be found below.
The use case for this is calling a GDPR deletion API endpoint /publisher/gdpr/delete on Sandbox, with the parameters aid, api_token, uid and scope.
<?php
$aid = "<aid>";
$api_token = "<api_token>";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uid = $_POST['uid'];
$url = "https://sandbox.piano.io/api/v3/publisher/gdpr/delete?aid=".$aid."&api_token=".$api_token."&scope=ALL&uid=".$uid;
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
$options = array(CURLOPT_URL => $url);
curl_setopt_array($ch, $options);
// grab URL and pass it to the browser
$output = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
// return the output
echo $output;
}
else {
echo '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>Request method must be POST!</body></html>';
}
?>
After you put your AID and API token into the $aid and $api_token variables, you would call the /file.php you saved with the POST request method and the required uid parameter to delete a user.
You can change the request method to GET or add more security measurements.
Of course, this script can be adjusted based on your needs, where you would replace either the Base URL, or API endpoint itself, as well as the required or optional parameters, and their values.
Here is an example of a JS code to execute a PHP file containing the required code for calling the API endpoint:
uid = "<UID>";
fetch('api.php', {
method: "POST",
body: new URLSearchParams({
'uid': uid
}),
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
}
})
.then(response => response.text())
.then(text => console.log(text));