Project API General Conventions (Authentication and Access)
This document defines the common communication protocol and governance conventions for all project-level feature REST APIs in Agentbase: covering service and resource boundaries, the complete request header matrix, the API Key Scopes permission matrix, server/client authentication flows (API Key / Session / JWT / Gateway Key), request and response formats, pagination query grammar, rate limiting and idempotency mechanisms, the unified error envelope, and ready-to-run cURL call examples.
Service and resource boundaries
The Agentbase REST API is divided by responsibility into the "Project feature plane (Project API)", the "Agent and gateway data plane (AI Gateway / LLM Gateway / Agent Runtime)", and the "Console management plane (Console API)". This directory (apis/) focuses on access interfaces for all business features under a project; its core boundaries are as follows:
Project-level multi-tenant isolation: all project-level resources (such as databases
enterprise_biz_db, knowledge baseskb_enterprise_support, storage bucketskb_enterprise_docs, memory spaces, and the AI gatewayprod-enterprise-ai-gateway) are strictly mounted under a single project (e.g., the showcase projectenterprise-ai-hub-210). Every HTTP request must first declare the target project context viaX-Appwrite-Project.Dual-track server and client credentials:
Server access (Server SDK / backend microservices): uses
X-Appwrite-Project+X-Appwrite-Key(project API Key). The server role is authorized according to thescopesmatrix bound to the Key, and by default bypasses row-level/document-level/file-level$permissionsuser ACLs.Client/end-user access (Web SDK / mobile / agent chat endpoints): uses
X-Appwrite-Project+ a user session (Session Cookie,X-Appwrite-Session, orX-Appwrite-JWT), strictly constrained by the$permissionson resources (see permission string grammar).Model gateway inference access: in addition to project API Keys,
/v1/ai-gateway/*and/v1/llm-gateway/*also support OpenAI-compatibleAuthorization: Bearer <GATEWAY_KEY>consumer key authentication.
Resources and Base Paths
Base URL:
https://appbuild-sit.oceanbase.com/v1(or your private deployment addresshttps://<your-endpoint>/v1). All endpoint paths in documents under this directory are relative to this Base URL (corresponding to service version2.10.0).Path parameters and resource ID conventions:
{userId},{databaseId},{knowledgeBaseId},{lexiconId}, etc. in paths are unique resource identifiers (UIDs).When creating a resource, the caller may pass a custom ID (length 1–36 characters, allowing letters, digits,
.,-, and_, and must not start with a special character), or pass the literal"unique()"to have the server auto-generate a globally unique ID.
Authentication and Permissions
Complete Request Header Matrix
| Header name | Required | Applicable scenarios | Example value | Semantic description |
|---|---|---|---|---|
X-Appwrite-Project | Required | All project-level APIs | enterprise-ai-hub-210 | Identifies the Agentbase project ID the current request belongs to |
X-Appwrite-Key | Required for server | Server APIs / background tasks | <APPBASE_API_KEY> | Project-level API Key (issued in the Console under "Project Settings -> API Keys") |
X-Appwrite-JWT | Optional for client | Accessing on behalf of a user identity | eyJhbGciOiJIUzI1NiIs... | Short-lived user JWT token, used when the server or a BFF makes requests subject to $permissions on behalf of the end user |
X-Appwrite-Session | Optional for client | Sessions in cookie-less environments | 66a9d9b804d8e... | Explicitly passes the user login session secret (equivalent to the a_session_<projectId> cookie) |
Authorization | Optional for gateway | AI Gateway / LLM Gateway | Bearer <GATEWAY_KEY> | OpenAI SDK-compatible Bearer token, used for model routing, Chat Completions, Embeddings, and Rerank |
X-Appwrite-Locale | Optional | Internationalization and error messages | zh-CN | Specifies the localization language for responses (following ISO 639-1 / BCP-47, see Locale API) |
X-Appwrite-Response-Format | Optional | Cross-version format compatibility | 1.6.0 | Specifies the backward-compatible serialization format version of the response body |
If-Match / If-None-Match | Optional | Optimistic concurrency control (CAS) | "v3" or "1" | Used for conditional concurrent update validation of knowledge bases, memory systems, or configuration |
Idempotency-Key | Optional | Async writes and task submission | req_20261022_001 | Idempotency key (up to 128 characters), preventing duplicate charges or duplicate inserts caused by network timeout retries |
API Key Scopes Permission Matrix
When creating a project API Key, follow the principle of least privilege and select the required Scopes. The mapping of core Scopes required by each feature module is as follows:
| Business module | Read-only Scope (*.read) | Write/manage Scope (*.write / specialized) | Compatible aliases and special notes |
|---|---|---|---|
| Users and teams (Users / Teams) | users.read, teams.read | users.write, teams.write, sessions.write | users.write Can issue Custom Tokens (/users/{userId}/tokens) |
| Databases (Databases) | databases.read, tables.read, columns.read, indexes.read, rows.read | databases.write, tables.write, columns.write, indexes.write, rows.write | Legacy document model aliases: collections.read/write, attributes.read/write, documents.read/write |
| Storage and file tokens (Storage / Tokens) | buckets.read, files.read, tokens.read | buckets.write, files.write, tokens.write | File download/preview supports header-free access via ?token=<secret> when fileSecurity=true |
| Knowledge base and lexicons (Knowledge Base) | knowledgebases.read, lexicons.read | knowledgebases.write, lexicons.write | Lexicons are independently governed by lexicons.read / lexicons.write |
| Memory system (Memory) | memory.read | memory.write | Covers long-term memory, user profiles, context dreaming, and experience/skill distillation |
| Models and AI gateway (LLM Gateway / AI Gateway) | llm-gateway.read, ai-gateway.read | llm-gateway.write, ai-gateway.write | Data-plane inference also supports gateway Consumer Key (Authorization: Bearer) |
| Agent runtime (Agent Runtime) | agent-runtime.read, projects.read | agent-runtime.write, agent-runtime.project, projects.write | The project-level agent workbench (/v1/agent-runtime/project/*) uses agent-runtime.project |
| Functions and sites (Functions / Sites) | functions.read, execution.read, sites.read | functions.write, execution.write, sites.write | Public function execution and published preview/production domain access require no server-side API Key |
| Messaging and moderation (Messaging / Moderation) | providers.read, topics.read, subscribers.read, messages.read, moderation.read | providers.write, topics.write, subscribers.write, messages.write, moderation.write | Covers email/SMS/push channels and text/image content safety moderation |
| Observability and auxiliary domains (Observability / Misc) | observability.read, webhooks.read, locale.read, avatars.read, health.read | observability.write, webhooks.write, graphql | OTLP trace reporting (/v1/traces) requires observability.write |
Comparison of Session / JWT / OAuth2 and API Key authentication flows
Server-side direct connection flow (API Key): The backend service attaches
X-Appwrite-ProjectandX-Appwrite-Keyto every request. If the Key is missing, forged, or does not match the project,401(general_access_forbidden) is returned; if the Key is valid but lacks the Scope declared for the current endpoint,401(general_unauthorized_scope) is returned.Server-issued Custom Token handed to client for login flow: The backend calls
POST /v1/users/{userId}/tokens(see Users API) to generate a one-time short-livedsecretand delivers it to the browser or app; the client uses the(userId, secret)to establish a user Session, then directly accesses table rows or storage files protected by$permissions.BFF proxy call flow (JWT): The frontend obtains a user JWT with a validity of 15 minutes via the Client SDK and passes it to the backend BFF with business requests; the BFF uses
X-Appwrite-Project+X-Appwrite-JWTto access Agentbase, and the platform then performs resource-level permission checks under that end user's role (user:<id>,team:<id>,label:<name>).
Endpoint overview
The 24 functional module endpoints in this directory are uniformly mounted under /v1 by path prefix:
| Functional category | Path prefix | Corresponding documentation | Core responsibilities |
|---|---|---|---|
| Project management | /v1/project/* | overview/overview.md | Project environment variable management, online OceanBase table schema conversion (e.g., switching to Shared V2) |
| Identity and teams | /v1/users/*, /v1/teams/* | auth/users.md, auth/teams.md | User lifecycle, labels, Mfa, Token issuance, team and member role management |
| Structured and document databases | /v1/tablesdb/*, /v1/documentsdb/*, /v1/databases/* | databases/overview.md, databases/permissions.md | Database/table/column/index management, row-level CRUD, cross-table distributed transactions, schema multi-versioning and rollback |
| File storage and short-link tokens | /v1/storage/*, /v1/tokens/* | storage.md, file-tokens.md | Storage bucket and file chunked upload, image scaling preview, short-lived file access Token issuance |
| Knowledge base and lexicons | /v1/knowledgebases/*, /v1/lexicons/* | knowledge-base/overview.md, knowledge-base/wiki.md, knowledge-base/versions.md | Multi-source document parsing and chunking, hybrid retrieval, lexicons (synonyms/expansion terms/stopwords), GraphRAG, RAPTOR, Wiki, and version archiving |
| Memory system | /v1/memory/* | memory/overview.md | Long-term factual memory, conversation reasoning ingestion, user profile extraction, Dreaming, and experience/skill distillation |
| Models and AI gateway | /v1/llm-gateway/*, /v1/ai-gateway/* | models-ai-gateway/llm-gateway.md, models-ai-gateway/ai-gateway.md | Managed model providers, logical model routing, semantic caching, guardrails, MCP, and A2A |
| Agent runtime | /v1/agent-runtime/* | agent-runtime.md | Project-level agent workbench configuration, lexicon binding, Preview/Published sessions (Threads) and streaming run (Runs) events |
| Observability and content safety | /v1/traces, /v1/observability/*, /v1/moderation/* | observability/overview.md, moderation.md | OpenTelemetry trace reporting, GenAI metrics aggregation, online evaluations, and image/text content moderation |
| Compute, sites, and notifications | /v1/functions/*, /v1/sites/*, /v1/messaging/* | functions.md, sites.md, messaging.md | Serverless function deployment and synchronous/asynchronous execution, web site hosting, multi-channel message delivery |
| Platform auxiliary tools | /v1/webhooks/*, /v1/graphql*, /v1/avatars/*, /v1/locale/*, /v1/health/* | misc/webhooks.md, misc/graphql.md, misc/avatars.md, misc/locale.md, misc/health.md | Event callback subscriptions, GraphQL queries, QR codes/initials avatars/webpage screenshots, internationalization dictionaries, and instance health checks |
Endpoint List
This page covers global common protocol specifications and does not declare proprietary business endpoints of its own; for the complete list of "HTTP method + path" for each business module, please consult the corresponding functional documentation in the table above.
Endpoint details
Request and response lifecycle
Protocol and encoding:
HTTPS(TLS 1.2+) is mandatory across all lines; the character set for requests and responses is uniformlyUTF-8.Timestamp convention: All date-time fields (such as
$createdAt,$updatedAt,expire,scheduledAt) use the standard ISO 8601 UTC format (for example,2026-10-22T08:30:00.000+00:00); only/v1/health/timeand OTLP nanosecond timestamps use Unix timestamps.Asynchronous task pattern (
202 Accepted): For time-consuming background computations (such as knowledge base document parsing and building, large-batch memory extraction, asynchronous function execution, Agent Run creation, and table schema conversion tasks), the creation endpoint immediately returns202 Acceptedalong with a task object (containingstatus: "pending"/"processing"and the task ID); callers can obtain the final execution result by polling the detail endpoint, subscribing to the SSE event stream, or registering a Webhook.
Request and response formats
Memory business deletion requests use a JSON body, and lists mainly use limit/cursor, which differs from the common filtering conventions below; refer to Memory API for specifics.
Filter parameters for
GET/DELETEgo in the URL query string;POST/PUT/PATCHgo in theapplication/jsonrequest body. The pagination parameterqueriesis uniformly an array (queries[]=...).File upload endpoints (such as storage file chunked upload and deployment package upload for functions and sites) use
multipart/form-data; for single files exceeding 5MB, chunked upload via theContent-Rangeheader is used (see Storage API).Responses are JSON. List responses uniformly use a structure of
total(total number of matches, integer) plus a resource name field (such asrows,users,files,lexicons); most list endpoints accepttotal=falseto skip theCOUNT(*)query, significantly reducing pagination overhead on large tables.Download endpoints (files
download/view/preview, deployment packagesdownload, knowledge base documentssource, lexiconsexport) return a binary byte stream or attachment download headers, not the common JSON wrapper.
Requests and Responses
Standard list response vs. single resource response
Single resource response structure (using a typical resource with system metadata as an example):
| Metadata field | Type | Description |
|---|---|---|
$id | string | Unique resource identifier |
$createdAt | string | Creation time (ISO 8601) |
$updatedAt | string | Last update time (ISO 8601) |
$permissions | string[] | Array of resource-level permission strings (e.g., ["read(\"any\")", "update(\"team:dev/owner\")"]) |
List resource response structure:
| Field | Type | Description |
|---|---|---|
total | integer | Total number of records matching the filter; always 0 when total=false is passed in the query parameters |
<resources>[] | array | Array of resource objects within the current pagination window (field name varies by module, e.g., users, rows, documents, buckets) |
Unified error model
All non-2xx responses uniformly use the following JSON envelope structure:
{
"message": "Not found",
"code": 404,
"type": "not_found",
"version": "2.10.0",
"requestId": "req_9f8e7d6c5b4a3210"
}typeis a lowercase underscore string; common error types includegeneral_access_forbidden(401),general_unauthorized_scope(401),general_resource_blocked(403),general_route_not_found(404),general_cursor_not_found(400),general_argument_invalid(400),general_conflict(409),general_rate_limit_exceeded(429),general_service_unavailable(503), and others.Each functional domain has its own semantic error types (such as
user_not_found,database_not_found,storage_bucket_not_found,lexicon_not_found,knowledge_base_not_found), registered in the "Errors and boundaries" section of the corresponding documentation.The
codefield matches the HTTP status code; the client's automatic retry policy should be decided by the HTTP status code together withtype.
Errors and boundaries
| HTTP status code | Typical type Error code | Trigger reason | Retriable | Handling recommendation |
|---|---|---|---|---|
400 Bad Request | general_argument_invalid / general_query_invalid | Request body field type mismatch, out-of-range enum value, or queries[] syntax error | No | Validate request parameter formats and field constraints, then fix and retry |
401 Unauthorized | general_access_forbidden | X-Appwrite-Key Missing, invalid, or mismatched with X-Appwrite-Project | No | Check the project ID and API Key in environment variables |
401 Unauthorized | general_unauthorized_scope | API Key is valid but not granted the Scope required by the current endpoint | No | Check the corresponding Scope on the API Keys page in the Console |
403 Forbidden | general_resource_blocked / project_database_read_only | Resource is banned, or the project is in a read-only freeze window during schema mode cutover (Cutover) | Depends | If it is a schema mode cutover freeze window, wait for the Cutover to complete and retry |
404 Not Found | *_not_found | Target resource ID does not exist, or the client identity lacks read permission (anti-enumeration covert return of 404) | No | Verify the resource ID in the path and resource-level $permissions |
409 Conflict | general_conflict / *_already_exists | Duplicate custom resource ID, attempt to delete a lexicon still referenced, or optimistic lock version conflict | No | Query the existing resource state or refresh to the latest version number before resubmitting |
429 Too Many Requests | general_rate_limit_exceeded | Triggered the account/project/caller token bucket rate limit | Yes | Read the response header Retry-After (seconds) or X-RateLimit-Reset and retry with backoff |
503 Service Unavailable | general_service_unavailable | Upstream dependency (such as an external model provider or queue) is temporarily busy | Yes | Retry using an exponential backoff strategy with random jitter (Jitter) |
Pagination and Queries
List endpoints accept a queries array, where each element is a structured query string (constructed by the Query builder in Server SDKs; when making direct HTTP calls, you can pass a JSON-serialized query description or functional syntax):
Pagination operators: offset-based pagination
limit(n),offset(n), as well as high-performance cursor paginationcursorAfter("<lastId>"),cursorBefore("<firstId>").cursoris taken from the$idof the last resource on the previous page; when the cursor record has been deleted,400(general_cursor_not_found) is returned. When traversing more than 5,000 records in production environments, usingcursorAfter+total=falseis strongly recommended.Filter and sort operators:
Exact match and negation:
equal("attr", ["val"]),notEqual("attr", ["val"])Range comparison:
lessThan("attr", val),lessThanEqual("attr", val),greaterThan("attr", val),greaterThanEqual("attr", val),between("attr", min, max)Null values and prefix/substring:
isNull("attr"),isNotNull("attr"),startsWith("attr", "prefix"),endsWith("attr", "suffix"),contains("attr", ["sub"]),search("attr", "keywords")Logical combination and projection/sorting:
or([...]),and([...]),orderAsc("attr"),orderDesc("attr"),select(["$id", "status"])
Query quota limits: a single request accepts at most 100 queries, each at most 4096 characters; the
limitper-page limit is subject to the annotation on each endpoint (the standard list limit is 100).Default order: when
orderAsc/orderDescis not explicitly specified, results are returned by resource creation order ($idascending) by default.
Rate Limiting and Idempotency
Three-tier token bucket rate limiting: the platform enforces rate limiting via three-tier token buckets of "account → project → caller (IP / user / API Key)"; response headers carry:
X-RateLimit-Limit: the maximum request quota for the current time windowX-RateLimit-Remaining: the remaining available count for the current windowX-RateLimit-Reset: the Unix timestamp (in seconds) when the current rate limit window resets
Over-limit behavior: when rate limited,
429 Too Many Requestsis returned with error typegeneral_rate_limit_exceeded, carrying theRetry-Afterheader.Idempotency semantics:
GET,HEAD,DELETEare naturally idempotent by HTTP semantics;PUTmeans create-or-replace (such as lexicon bindingPUT /v1/knowledgebases/{id}/lexicons);PATCHperforms partial field updates; atomic writes across multiple rows/tables use explicit transactions (see Databases API).
Complete Call Examples
The following examples demonstrate standard HTTP call patterns based on the showcase project enterprise-ai-hub-210 (enterprise intelligent customer service and knowledge platform): two-header authentication, array-style pagination queries, and total=false skip counting.
List customer service agent accounts in active status within the project (with pagination and filtering; queries[] is in array form):
curl \
'https://appbuild-sit.oceanbase.com/v1/users?queries[]=limit(25)&queries[]=offset(0)&queries[]=equal("status",true)&total=false' \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: <APPBASE_API_KEY>"Create a resource (JSON request body; using the creation of a tier-two technical support team as an example):
curl -X POST "https://appbuild-sit.oceanbase.com/v1/teams" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: <APPBASE_API_KEY>" \
-H "Content-Type: application/json" \
-d '{
"teamId": "unique()",
"name": "OceanBase 向量检索专家支持组",
"roles": ["owner", "engineer"]
}'A successful response is 201 Created + resource JSON; a list response looks like {"total": 0, "teams": [...]} (when total=false, total is always 0).
Typical error response (Key missing or invalid, 401):
{
"message": "Project is not accessible in this region or API key is invalid.",
"code": 401,
"type": "general_access_forbidden",
"version": "2.10.0"
}Key is valid but missing the required Scope (401):
{
"message": "The current API key does not have the required scope (teams.write) to perform this action.",
"code": 401,
"type": "general_unauthorized_scope",
"version": "2.10.0"
}Rate limit exceeded (429, carrying the Retry-After response header):
{
"message": "Too many requests",
"code": 429,
"type": "general_rate_limit_exceeded",
"version": "2.10.0"
}When troubleshooting, it is recommended to check four places at once: the HTTP status code, the error type, the response headers X-RateLimit-Remaining / Retry-After, and the requestId in the response (which can be used for request-level search in observability platforms).
Correspondence with the Server SDK
All Server SDKs (agentbase-node-sdk@2.10.0, agentbase-python-sdk==2.10.0, and the Java / Go Server SDKs) share the conventions on this page; HTTP-level differences only appear in specific endpoints and business parameters, while authentication headers, the error model, and pagination and rate limiting semantics are fully consistent.
| Server SDK Service | API Reference Documentation | Core Responsibility Description |
|---|---|---|
Users | auth/users.md | User lifecycle, labels, sessions, MFA, and Token issuance |
Teams | auth/teams.md | Team and member role management |
TablesDB / DocumentsDB / Databases | databases/overview.md | Structured tables, collections, row/document CRUD, transactions, and Schema versions |
Storage | storage.md | Storage buckets and file upload, preview, and download |
Tokens | file-tokens.md | Short-lived access token management for stored files |
Functions | functions.md | Serverless functions, deployment packages, environment variables, and execution records |
Project | overview/overview.md | Project global variables and OceanBase schema mode cutover |
Messaging | messaging.md | Email/SMS/push providers, topics, and message sending |
Sites | sites.md | Static and SSR site builds, deployments, and preview domains |
Memory | memory/overview.md | Long-term memory, user profiles, context dreaming, and skill distillation |
KnowledgeBases / Lexicons | knowledge-base/overview.md | Knowledge base document ingestion, hybrid retrieval, lexicons, Wiki, and version archiving |
LlmGateway | models-ai-gateway/llm-gateway.md | Model providers, quotas, and base model invocation |
AiGateway | models-ai-gateway/ai-gateway.md | Logical model routing, semantic caching, safety guardrails, MCP, and A2A |
AgentRuntime | agent-runtime.md | Project-level agent workbench, Draft preview, and Published runs |
Observability | observability/overview.md | OTLP trace reporting, metrics, and evaluation runs |
Moderation | moderation.md | Automatic content moderation for database text and storage bucket images |
Webhooks / Graphql / Avatars / Locale / Health | misc/webhooks.md etc. | Webhook subscriptions, GraphQL, graphical tools, internationalization dictionaries, and health checks |
For the permission string grammar and semantics on each resource, see permissions.