Full-Stack Deployment
Overview and use cases
Deploy a complete application (TablesDB data model + Storage resources + Function backend + Sites frontend) to a project from scratch: create database and tables → deploy functions → deploy the site → register platforms → output accessible URLs. Suited to agent-automated delivery, scaffolding initialization, and CI-driven full-stack releases.
Three typical architectures:
Mode A: browser → Sites → the Client SDK only calls Functions → TablesDB (the frontend never connects directly to the data plane).
Mode B: reads connect directly to TablesDB/Storage/Realtime, while sensitive writes go through
functions.createExecution(e.g., a kanban demo).Mode C: Sites SSR——the SSR side uses an API Key to read the database, and the user Session uses the Client SDK to connect directly from the browser to
/v1(note the Cookie non-passthrough limitation in sites.md).
Basis: Sites/Functions/TablesDB service-plane coverage is complete in v2.7.0 SDK source, and the security defaults (restricted identity, Function API Key not via query string) take effect from 2.6.0——this page is written for the full workflow.
Prerequisites (credential gates)
Division of the two keys: the Console Session (after email/password login,
setCookie) performs Console-only operations (creating projects, creating Teams,projects.createPlatformregistering platforms, organization queries); the project API Key performs resource operations (databases/tables/storage/functions/sites/deployments).platforms.read/writeis not among the grantable scopes of a project Key——calling createPlatform with a project Key fails directly.Console login must land in cookies: intercept the login response's
set-cookieand concatenateconsoleClient.setCookie(...)afterward, otherwise subsequentteams.create/projects.createKeywill be rejected as guests.Credentials are read only from the project's
.env(priority: project-root.env>scripts/.env> process environment); it is forbidden to log passwords/Keys/JWTs, and forbidden to commit deployment scripts into the user's repository.API Key scope recommendations (17 items): databases / tables / columns / indexes / rows / buckets / functions / execution / sites each read+write, plus
rules.read. ConsolecreateKeyscopes are lowercase dot-separated strings (e.g.,sites.write).2.6.0 security defaults: Function/Site install, build, and start commands run under a restricted identity and fail directly when conditions are unmet, with no fallback to higher privilege; Function API Keys are no longer accepted via query string——use a protected header or platform-injected runtime authentication.
Usage workflow
Data layer:
tablesDB.create({ databaseId, name })→tablesDB.createTable({ databaseId, tableId, name, rowSecurity, columns, indexes })(columns/indexes inline, except relationship columns) → create buckets (storage.createBucket).Function layer:
functions.create(...)→ configureexecute(who can invoke) andscopes(runtime dynamic Key permissions; different from execute) →functions.createVariable(variablevariableIdrequired) → package as tar.gz (excludingnode_modules, build artifacts,.env) →functions.createDeployment({ functionId, code, activate: true })→ poll deploymentready.Frontend layer:
sites.create(...)(framework/adapter/build command, see sites.md) →sites.createVariable(VITE_*non-secret variables +secret: trueserver-side Key) → package and uploadsites.createDeployment({ siteId, code, activate: true })(HTTP 202) → pollgetDeploymentuntilready.Platform registration: under the Console Session,
projects.createPlatform({ projectId, type: 'web', name, hostname })——hostname withouthttps://; register localhost,127.0.0.1, and Sites domains; unregistered domains allow pages to open but APIs report CORS/Invalid URI.Resolve URL: use the current deploymentId with the Console SDK's
proxy.listRulesmatching rules to get the site URL (rules[0]is forbidden / do not reuse old URLs); query the function execution context on the spot.Report back: Project ID, Function ID, Site URL, deploymentId, Console URL (
{consoleOrigin}/console/project-{region}-{projectId}/overview/platforms, origin = endpoint minus/v1, region usuallydefault).
Key parameters and returns
Synchronous Functions have a limit of about 30 seconds through the load balancer (timeout reports 408): for long tasks, switch to
async: true+getExecutionpolling.Function runtime-injected variables:
APPWRITE_FUNCTION_API_ENDPOINT,APPWRITE_FUNCTION_PROJECT_ID, and request headersx-appwrite-key/x-appwrite-user-id——do not create variables with the same names yourself.Idempotency conventions: Site/Function use fixed IDs (get first, then update/create); variables upsert by key; deployments use
ID.unique()each time; Platforms are deduplicated by hostname.For build timeouts, evaluate based on 900 seconds; the deployment polling example uses 5-second intervals with an upper bound of 10 minutes.
Errors and boundaries
Sites capability whitelist not allowed → pass the gate in sites.md first before continuing; stop on failure (you may keep a checkpoint: write the Team/Project/Key back to
.env, fix, and rerun).Environment consistency: the endpoint must be in the same environment as the account's Console (SIT
https://appbuild-sit.oceanbase.com/v1, productionhttps://appbuild.oceanbase.com/v1); ask when no configuration exists rather than defaulting to SIT.Changed Site variables only take effect after re-running createDeployment; frontend
VITE_*endpoints must include/v1.After modifying variables or rolling back a deployment, URLs still follow "the rules bound to the current deploymentId".
SDK Category Differences
Server SDK (server-sdk/nodejs.md): the full set of tablesDB / storage / functions / sites resource operations——the workhorse of deployment scripts.
Console SDK (console-sdk/nodejs.md): Console-only operations such as projects/teams/Keys/platform registration.
Client SDK (client-sdk/web.md): does not participate in deployment; only accesses the
/v1data plane of deployed applications.For combined usage of the two, see server-sdk/nodejs.md "Using Together with the Console SDK".
Examples by language
The following provides examples by language, item by item along the usage workflow; each card can switch languages (synced across the page).
Data layer: create database, tables, and buckets
Credentials: project API Key (databases.* / tables.* / columns.* / indexes.* / buckets.*). Lists/indexes are submitted inline within createTable (relationship columns go through a dedicated endpoint); the Web SDK is not involved in deployment, so there is no Web tab.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
import { Client, TablesDB, Storage } from 'agentbase-node-sdk';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT) // Includes /v1, same environment as the account Console
.setProject(process.env.APPWRITE_PROJECT_ID)
.setKey(process.env.APPWRITE_API_KEY); // Project API Key
const tablesDB = new TablesDB(client);
await tablesDB.create({ databaseId: 'app-db', name: 'App' });
await tablesDB.createTable({
databaseId: 'app-db',
tableId: 'tasks',
name: 'Tasks',
rowSecurity: true,
columns: [/* Column definitions inline; except relationship columns */],
indexes: [],
});
const storage = new Storage(client);
await storage.createBucket({ bucketId: 'attachments', name: '附件', fileSecurity: true });// io.agentbase positional-argument form; for the per-parameter signatures, refer to the SDK source
TablesDB tables = new TablesDB(client);
tables.create("app-db", "App", null, true, null, null, null, null, null, null, null, null);
tables.createTable(
"app-db", "tasks", "Tasks",
null, // permissions
true, // rowSecurity
true, // enabled
List.of(new DatabaseColumnDefinition()
.setKey("title").setType(DatabaseSchemaType.VARCHAR)
.setSize(256L).setRequired(true)),
List.of(new DatabaseIndexDefinition()
.setKey("title_idx").setType(DatabaseSchemaIndexType.KEY)),
null // comment
);
Storage storage = new Storage(client);
storage.createBucket("attachments", "附件", null, true, true,
26214400L, null, null, true, false, true);from agentbase.services.tables_db import TablesDB
from agentbase.services.storage import Storage
tables_db = TablesDB(client)
tables_db.create(database_id='app-db', name='App')
tables_db.create_table(
database_id='app-db', table_id='tasks', name='Tasks',
row_security=True,
columns=[{'key': 'title', 'type': 'string', 'size': 256, 'required': True}],
indexes=[{'key': 'idx_title', 'type': 'unique', 'attributes': ['title']}],
)
storage = Storage(client)
storage.create_bucket(bucket_id='attachments', name='附件', file_security=True, enabled=True)tables := agentbase.NewTablesDB(cl)
_, err := tables.Create("app-db", "App")
_, err = tables.CreateTable("app-db", "tasks", "Tasks",
tables.WithCreateTableRowSecurity(true),
tables.WithCreateTableColumns([]models.DatabaseColumnDefinition{
{Key: "title", Type: "string", Size: 256, Required: true},
}),
tables.WithCreateTableIndexes([]models.DatabaseIndexDefinition{
{Key: "idx_title", Type: "unique", Attributes: []string{"title"}},
}),
)
storage := agentbase.NewStorage(cl)
_, err = storage.CreateBucket("attachments", "附件",
storage.WithCreateBucketFileSecurity(true),
storage.WithCreateBucketEnabled(true))curl -X POST "https://<your-endpoint>/v1/tablesdb" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"databaseId": "app-db", "name": "App", "enabled": true}'
curl -X POST "https://<your-endpoint>/v1/tablesdb/app-db/tables" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"tableId": "tasks",
"name": "Tasks",
"rowSecurity": true,
"columns": [{"key": "title", "type": "string", "size": 256, "required": true}],
"indexes": [{"key": "idx_title", "type": "fulltext", "attributes": ["title"]}]
}'
curl -X POST "https://<your-endpoint>/v1/storage/buckets" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"bucketId": "attachments", "name": "附件", "fileSecurity": true, "enabled": true}'Functions layer: create, configure, and deploy functions
Credentials: project API Key. execute governs who may invoke, scopes governs permissions for dynamic keys in the function runtime — the two are different things; variables require a new createDeployment to take effect for subsequent executions.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
import { Functions, ID } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';
const functions = new Functions(client);
await functions.create({
functionId: 'send-mailer',
name: 'Send Mailer',
runtime: 'node-22',
execute: ['users'], // Who can call it
scopes: ['databases.read', 'tables.read', 'rows.read',
'databases.write', 'tables.write', 'rows.write'],
entrypoint: 'src/main.js',
commands: 'npm install',
});
await functions.createVariable({
functionId: 'send-mailer',
variableId: ID.unique(),
key: 'DATABASE_ID',
value: 'app-db',
});
// tar -czf code.tar.gz --exclude=node_modules -C functions/send-mailer .
const dep = await functions.createDeployment({
functionId: 'send-mailer',
code: InputFile.fromPath('./code.tar.gz'),
activate: true,
});
// Poll getDeployment (functionId + dep.$id) until status === 'ready'Functions functions = new Functions(client);
// Isomorphic method names (positional parameters; per-parameter signatures follow the SDK source):
// create(...): runtime, execute, scopes, entrypoint, commands, etc.
// createVariable(functionId, variableId, key, value)
// Package: tar -czf code.tar.gz --exclude=node_modules -C functions/send-mailer .
// createDeployment(functionId, code, activate, ...) returns 202;
// Then poll getDeployment(functionId, deploymentId) until readyfrom agentbase.input_file import InputFile
from agentbase.services.functions import Functions
functions = Functions(client)
# Method surface mirrors the Node SDK (snake_case): create / create_variable /
# create_deployment(code=InputFile.from_path('./code.tar.gz'), activate=True)/
# get_deployment polls until status == 'ready'; per-parameter signatures follow the agentbase.services.functions source codefunctions := agentbase.NewFunctions(cl)
// Isomorphic method names (PascalCase): Create / CreateVariable / CreateDeployment /
// GetDeployment (poll until Status=ready); optional parameters use functions.With… options,
// Refer to the module source codecurl -X POST "https://<your-endpoint>/v1/functions" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"functionId": "send-mailer",
"name": "Send Mailer",
"runtime": "node-22",
"execute": ["users"],
"scopes": ["databases.read", "tables.read", "rows.read", "databases.write", "tables.write", "rows.write"],
"entrypoint": "src/main.js",
"commands": "npm install"
}'
curl -X POST "https://<your-endpoint>/v1/functions/send-mailer/variables" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"variableId": "var_database_id", "key": "DATABASE_ID", "value": "app-db"}'
# tar -czf code.tar.gz --exclude=node_modules -C functions/send-mailer .
curl -X POST "https://<your-endpoint>/v1/functions/send-mailer/deployments" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-F "code=@./code.tar.gz" \
-F "activate=true"
# 202: poll GET /v1/functions/send-mailer/deployments/{deploymentId} until status=readyFrontend layer: create a site, inject variables, and deploy
Credentials: project API Key (sites.*). Non-secret VITE_* variables add a secret: true server-side Key; VITE_APPWRITE_ENDPOINT must include /v1; changing variables requires redeployment. For framework and adapter details, see sites.mdx.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
import { Sites, ID } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';
const sites = new Sites(client);
await sites.create({
siteId: 'portal',
name: '用户门户',
framework: 'react', // Full list at GET /sites/frameworks
buildRuntime: 'node-22',
adapter: 'static',
fallbackFile: 'index.html', // Required for SPA
outputDirectory: 'dist',
installCommand: 'npm install',
buildCommand: 'npm run build',
});
await sites.createVariable({
siteId: 'portal',
variableId: ID.unique(),
key: 'VITE_APPWRITE_ENDPOINT',
value: 'https://appbuild.oceanbase.com/v1',
});
// Package frontend source (exclude node_modules and local build artifacts; build runs remotely via npm run build)
const dep = await sites.createDeployment({
siteId: 'portal',
code: InputFile.fromPath('./site.tar.gz'),
activate: true, // HTTP 202
});
// Poll sites.getDeployment (siteId + dep.$id) until status === 'ready'Sites sites = new Sites(client);
sites.create("portal", "用户门户", Framework.REACT, BuildRuntime.NODE_22,
true, true, 30L,
"npm install", "npm run build", "", "dist",
Adapter.STATIC,
null, "index.html", // installationId, fallbackFile (required for SPA)
null, null, false, null, // VCS-related
null, null, null, null, null); // Specifications / execution plan / retention period, see listSpecifications()
// Deployment: after sites.createDeployment(siteId, code, activate, ...), poll getDeployment;
// createVariable(siteId, variableId, key, value) injects VITE_* variablesfrom agentbase.input_file import InputFile
from agentbase.services.sites import Sites
sites = Sites(client)
# Method surface mirrors the Node SDK (snake_case): create / create_variable /
# create_deployment(code=InputFile.from_path('./site.tar.gz'), activate=True)/
# get_deployment polls until status == 'ready'; per-parameter signatures follow the agentbase.services.sites source codesites := agentbase.NewSites(cl)
// Isomorphic method names (PascalCase): Create / CreateVariable / CreateDeployment /
// GetDeployment (poll until Status=ready); optional parameters use sites.With… options,
// Refer to the module source codecurl -X POST "https://<your-endpoint>/v1/sites" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"siteId": "portal",
"name": "用户门户",
"framework": "react",
"buildRuntime": "node-22",
"adapter": "static",
"fallbackFile": "index.html",
"outputDirectory": "dist",
"installCommand": "npm install",
"buildCommand": "npm run build"
}'
curl -X POST "https://<your-endpoint>/v1/sites/portal/variables" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"variableId": "var_endpoint", "key": "VITE_APPWRITE_ENDPOINT", "value": "https://appbuild.oceanbase.com/v1"}'
curl -X POST "https://<your-endpoint>/v1/sites/portal/deployments" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-F "code=@./site.tar.gz" \
-F "activate=true"
# 202: poll GET /v1/sites/portal/deployments/{deploymentId} until status=readyPlatform registration (Console only)
Credentials: Console Session (email/password login + setCookie) — the project API Key has no platforms.* scope, and calling createPlatform fails directly. The hostname carries no https://; the REST management endpoints are not exposed in the apis documentation, so there is no REST tab.
- Console (Node.js)
import { Client, Account, Projects, PlatformType } from 'agentbase-console-sdk';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT) // Includes /v1
.setProject(process.env.APPBASE_CONSOLE_PROJECT_ID || 'console'); // Console context
// createEmailPasswordSession alone is not enough: after intercepting the login response set-cookie and concatenating it
// client.setCookie(sessionCookie); otherwise subsequent calls are rejected as a guest
const account = new Account(client);
await account.createEmailPasswordSession({
email: process.env.APPBASE_EMAIL,
password: process.env.APPBASE_PASSWORD,
});
const projects = new Projects(client);
const list = await projects.listPlatforms({ projectId }); // projectId is the application project ID
const registered = new Set(
list.platforms.filter((p) => p.type === 'web').map((p) => p.hostname),
);
for (const hostname of ['localhost', '127.0.0.1', '<sites-preview-hostname>']) {
if (!registered.has(hostname)) {
await projects.createPlatform({
projectId, // App project ID
type: PlatformType.Web,
name: hostname,
hostname, // Without https://
});
}
}Verification and reporting: resolve the deployment URL
Credentials: project API Key (requires rules.read) to call proxy.listRules; the Console SDK likewise exports Proxy (loaded from the Console Session). The REST endpoints for rules are not exposed in the apis documentation, so there is no REST tab. Report the Project ID, Function ID, Site URL, deploymentId, and Console URL ({consoleOrigin}/console/project-{region}-{projectId}/overview/platforms, origin = endpoint with /v1 removed, region is usually default).
- Node.js (Server)
- Console (Node.js)
import { Proxy, Query } from 'agentbase-node-sdk';
const proxy = new Proxy(client); // Project API Key (rules.read)
const rules = await proxy.listRules({
queries: [
Query.equal('deploymentResourceId', [siteId]),
Query.equal('deploymentResourceType', ['site']),
],
});
const withDomain = rules.rules.filter((r) => r.domain);
// Only rules bound to this deploymentId are recognized; order does not guarantee the latest; do not fetch rules[0]
const bound = withDomain.find((r) => r.deploymentId === deploymentId);
const siteUrl = `https://${bound.domain}`;import { Proxy, Query } from 'agentbase-console-sdk';
const proxy = new Proxy(consoleClient); // Client loaded with Console Session
// listRules is isomorphic with the Server SDK: the same query parameters locate the site rules of this deployment
const rules = await proxy.listRules({
queries: [
Query.equal('deploymentResourceId', [siteId]),
Query.equal('deploymentResourceType', ['site']),
],
});Example Guide
JavaScript (Node deployment sequence + Console platform registration): examples/javascript.md
Java:examples/java.md