Skip to content

API Getting Started ​

Learn how to use the global k object in Kooboo server-side scripts (Api, CodeBlock, and <script env="server">).

Execution ContextPrerequisitesTypical Use
Api, CodeBlock, <script env="server">, ModuleSupports JavaScript & TypeScript syntax (transpiled and run synchronously on Jint; no DOM / Node APIs)Handle API routes, inspect requests, and access DB or site data

KScript is Kooboo's server-side scripting runtime. It supports both JavaScript and TypeScript syntax, automatically transpiling scripts before executing them synchronously in the Jint engine inside Api, CodeBlock, PageScript, and Module resources (see KScript Language and Runtime).

Quick Start ​

js
// GET API (return an object directly to serialize as JSON)
k.api.get(() => {
    return { message: "Hello Kooboo" }
})

// POST API (read k.request.form for form submissions, or parse k.request.body safely for JSON)
k.api.post(() => {
    if (k.request.form.length > 0) {
        return { type: "form", received: k.request.form }
    }

    let body = {}
    if (k.request.body) {
        try {
            body = JSON.parse(k.request.body)
        } catch (e) {
            k.response.statusCode(400)
            return { error: "Invalid JSON body" }
        }
    }

    return { type: "json", body }
})

Do not unconditionally JSON.parse k.request.body

For application/x-www-form-urlencoded requests, k.request.body still contains the URL-decoded form payload (such as a=1&b=2), not an empty string. Calling JSON.parse(k.request.body || "{}") unconditionally will throw a SyntaxError (HTTP 400); check k.request.form.length > 0 first or wrap JSON.parse in try / catch.

The Global k Object ​

k is the entry point to all built-in Kooboo capabilities:

ModuleDescription
k.requestHTTP request data
k.responseHTTP response handling
k.sessionSession state
k.DBDatabase access
k.contentContent management
k.fileFile operations
k.siteSite resources such as pages, layouts, and menus
k.netNetwork access
k.commerceCommerce features
k.paymentPayment integrations
k.mailEmail sending

Type Hints ​

In a local project or any TypeScript-aware IDE, reference kooboo.d.ts to get full IntelliSense and type hints:

ts
/// <reference path="kooboo.d.ts" />

// Full code completion and type checking for k.* APIs
k.DB.

Next Steps ​