Create custom API functions Last updated: 14. May 2025

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

let 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!

let folders = docly.getFolders(query.folder);
return folders;

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);
let folders = docly.getFolders(form.folder);
return folders;

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 modify Docly-data with the following API only functions:

Function Description
docly.saveFile(filepath, json, [schemaPath]) Create or update a Docly document.
docly.patchFile(filepath, jsonPatch) Updates a Docly document by overwriting only specified keys in JSON.
docly.deleteFile(filepath) Delete a Docly document.
docly.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

let today = format(new Date(), "yyyy-MM-dd");
let liste = docly.getFiles("Tenancies", "*", 1);
let result = [];
for(let item of liste) {
    if (item.To > today) {
        let 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
docly.isStr(value, [length]) If parameter is a string and not empty, otherwise error with message is returned.
Optional a required minimum length.
docly.isNum(value, [min], [max]) If parameter is a number and not empty, otherwise error with message is returned.
Optional minimum and maximum values.
docly.isEmail(value) If parameter is a string and not empty, otherwise error with message is returned.
docly.isName(value) If parameters is a string and contains atleast two words seperated with space.

GET method example:

// Validate params with if statements and throw new Error
if (!docly.isString(query.name, 5)) throw new Error("Name is required!");
if (!docly.isEmail(query.email)) throw new Error("Email is required!");
if (!docly.isNum(query.age)) throw new Error("Age is required!");
if (!docly.isNum(query.age, 18, 100)) throw new Error("Age must be between 18 and 100!");
if (!query.address) throw new Error("Address is not specified!");
// ....