Create custom API functions Last updated: 19. Jan 2024
EXAMPLE - Creating your custom API is needed if you want to make interactive functions in your sites.
API functions are not cached and are also allowed to access query string and form parameters. With API functions you can also write / store data to your Docly site / database.
Normal pages can't read from the query string and can only produce a single static output as it is cached in the system.
Create your API handler
Place your API functions in the #/API folder where it is only possible to create .hash files that returns JSON or JS files that return objects (converted automatically to JSON). The following example returns the date formatted:
#/API/Test.js
var result = { "date" : format(new Date(), "yyyyMMdd") };
return result;
Endpoint for this function is: https://yoursitepath/%23/API/Test
⚠️ Your API is addressed under the "/API/" prefix.
Use your API handler
Use jQuery or other JS to call your API functions and handle the results:
<html>
<head>
<title>Test page</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
The date is: <span id="Date">Loading ...</span>
<script>
fetch("~/API/GetDate")
.then(response => response.json())
.then(data => {
document.getElementById("Date").textContent = data.date;
})
.catch(err => {
alert("Error " + JSON.stringify(err));
});
</script>
</body>
</html>
Get parameters from query string (GET and POST methods)
For API functions you can use dynamic values such as query string params. The result of the API call will also never be cached.
Get the parameters like this: let value = query.paramname;
Note that the param names are case sensitive!
return GetFolders(query.folder);
Calling the API with jQuery GET:
fetch("~/API/myfunction").then(function(response) {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(function(data) {
// TODO: handle the data
})
.catch(function(error) {
alert("Error: " + error.message);
});
Get parameters from form (POST method)
For API functions where you use post method you can read from the form values.
Get the parameters like this: let value = form.paramname;
Note that the param names are case sensitive!
// Decode JSON structures from string
let data = JSON.parse(form.data);
return GetFolders(form.folder);
Example url: https://yoursite/%23/API/MyFunction
Calling the API with jQuery POST:
fetch('API/MyFunction', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(function(response) {
if (!response.ok) {
return response.json().then(function(err) {
throw new Error(err.Message || 'Unknown error occurred');
});
}
return response.json();
})
.then(function(data) {
console.log("Submit response", data);
// TODO ...
})
.catch(function(ex) {
// TODO ...
// Error occurred in code
});
Data functions
API code can access the following data functions:
Function | Description |
---|---|
SaveFile(filepath,json,[schemaId]) | Create or update a Docly document. |
DeleteFile(filepath) | Delete a Docly document. |
MoveFile(filepath,filepath) | Move a Docly document. |
Note that these functions are not available outside your API code folder (#/API). Extra charges will apply when using the API features.
Function that returns and array
Filename: #/API/GetRoomAvail.js
var today = format(new Date(), "yyyy-MM-dd");
var liste = docly.getFiles("Tenancies", "*", 1);
var result = [];
for(let item of liste) {
if (item.To > today) {
var obj = {
"Roomno" : item.Roomno,
"From" : item.From,
"To" : item.To
};
result.push(obj);
}
}
return result;
Validate incoming parameters
To validate parameters in a function handler you can use some of these utility functions:
Function | Description |
---|---|
Assert(bool,message) | If first parameter is false, then the second parameter is the error message returned. If first parameter is true, code continues to next line. |
Assert(message) | Returns specified error message. |
IsStr(value,[length]) | If parameter is a string and not empty, otherwise error with message is returned. Optional a required minimum length. |
IsNum(value,[min],[max]) | If parameter is a number and not empty, otherwise error with message is returned. Optional minimum and maximum values. |
IsEmail(value) | If parameter is a string and not empty, otherwise error with message is returned. |
IsName(value) | If parameters is a string and contains atleast two words seperated with space. |
IsNotNull(value) | If a parameter not null. |
AreEqual(value1,value2) | Returns true if the two values are equal. |
AreNotEqual(value1,value2) | Returns true if the two values are not equal. |
GET method example:
// Validate params with assert and bool param
Assert(IsString(query.name, 5), "Name is required!");
Assert(IsEmail(query.email), "Email is required!");
Assert(IsNum(query.age), "Age is required!");
Assert(IsNum(query.age, 18, 100), "Age must be between 18 and 100!");
// Using standard if's and returning errors with assert
if (!query.address) Assert("Address is not specified!");
// ....