API Getting Started
Learn how to use the global
kobject in Kooboo server-side scripts (Api,CodeBlock, and<script env="server">).
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
Api, CodeBlock, <script env="server">, Module | Supports 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
// 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:
| Module | Description |
|---|---|
k.request | HTTP request data |
k.response | HTTP response handling |
k.session | Session state |
k.DB | Database access |
k.content | Content management |
k.file | File operations |
k.site | Site resources such as pages, layouts, and menus |
k.net | Network access |
k.commerce | Commerce features |
k.payment | Payment integrations |
k.mail | Email sending |
Type Hints
In a local project or any TypeScript-aware IDE, reference kooboo.d.ts to get full IntelliSense and type hints:
/// <reference path="kooboo.d.ts" />
// Full code completion and type checking for k.* APIs
k.DB.Next Steps
- k.api — Create GET/POST/PUT/DELETE routes
- k.request — Read HTTP request data
- k.DB Databases — Database CRUD operations
- Authentication and Authorization — Login and session APIs