Skip to content

JavaScript API Wrapper

  • Automatic CSRF handling — No need to manage tokens manually
  • Built-in spinner — Shows a loading indicator during requests
  • Less coupling — If the API changes, the wrapper absorbs more of that churn
  • Cleaner code — Less boilerplate for you

Add this to your template's <head>:

<meta name="csrf-token" content="{{ CSRFToken }}">
<script src="{{ "Api/API.js?v=#{guest.system_version}" | library_url }}"></script>

What this does:

  1. Creates a meta tag with the CSRF token (the wrapper reads this automatically)
  2. Loads the API wrapper, appending the system version to prevent caching issues

The wrapper follows this pattern:

API.{role}.{method}(endpoint, params, onSuccess, onError, showSpinner)
ParameterDescription
roleadmin, client, or guest
methodget or post
endpointThe API endpoint (e.g., "system/version")
paramsRequest parameters (object)
onSuccessCallback function for successful responses
onErrorCallback function for errors
showSpinnerBoolean to show/hide the loading spinner (optional, default: true)
API.guest.get(
"system/version",
{},
function(response) {
console.log("Version:", response);
},
function(error) {
console.error("Error:", error);
}
);
API.admin.post(
"client/get_list",
{ per_page: 10, page: 1 },
function(response) {
console.log("Clients:", response.list);
},
function(error) {
console.error("Failed to load clients:", error);
}
);
API.admin.post(
"client/get_list",
{},
function(response) {
// Handle success
},
function(error) {
// Handle error
},
false // No spinner
);

The wrapper automatically shows a spinner for requests taking longer than 250ms. To use it:

  1. Include a .spinner-border class in your CSS
  2. The wrapper creates and removes the spinner element automatically
.spinner-border {
/* Your spinner styles */
animation: spin 1s linear infinite;
}

Spinner example

Either:

  • Don't define a .spinner-border class in your CSS
  • Pass false as the fifth parameter to the API call
function(response) {
// response contains the API result
// Access data like response.result or response.id
}
function(error) {
// error contains error details
// Usually: error.message and error.code
console.error(error.message);
}
// Load client profile
function loadProfile() {
API.client.get(
"client/profile",
{},
function(profile) {
document.getElementById('name').textContent = profile.first_name + ' ' + profile.last_name;
document.getElementById('email').textContent = profile.email;
},
function(error) {
alert('Failed to load profile: ' + error.message);
}
);
}
// Call it when the page loads
document.addEventListener('DOMContentLoaded', loadProfile);

For more details, see the API Reference.