GraphQL
Overview and use cases
Graphql The service allows developers to use standard GraphQL query (read-only queries) and mutation (data mutations) statements to access platform data-plane resources (such as Account, Users, Teams, TablesDB/Databases, Storage, Functions, etc.); its underlying permission checks, row-level security (RLS), and quota/rate-limiting systems are fully consistent with the REST API.
In frontend aggregation pages or complex BFF (Backend For Frontend) scenarios (such as the demo project enterprise-ai-hub-210, which needs to read the current logged-in account info, the list of teams it belongs to, and summary data from the support ticket table customer_tickets simultaneously), using GraphQL allows trimming returned fields on demand and combining multiple queries in a single HTTP request, reducing multi-round-trip overhead and redundant field transmission.
Prerequisites
Client initialization and authentication:
Server SDK (Node.js / Java / Python / Go): initialize via
setEndpoint('https://appbuild-sit.oceanbase.com/v1'),setProject('enterprise-ai-hub-210'),setKey('<APPBASE_API_KEY>'); the API Key must have the scopes corresponding to the underlying resources queried/mutated (such asusers.read,tables.read,rows.write, etc.).Client / Web SDK: initialize via
setEndpoint,setProjectand complete user login (Session or JWT); the query scope is strictly constrained by the current user's Session and table/row-level Permissions.Console SDK: supports management-plane Session or short-lived JWT.
Usage workflow
Initialize the client and the
Graphqlservice: constructClientand instantiatenew Graphql(client).Execute a read-only query (
graphql.query): pass in a JSON payload containingquery(the GraphQL query string) plus optionalvariables(a parameterized variables object) andoperationName, then read the on-demand projected results from thedatafield of the returned object.Execute a mutation (
graphql.mutation): pass in amutationmutation statement andvariables(e.g. creating a row, updating preferences, creating a team, etc.); ensure all dynamic user input is passed via$variablevariable binding — never concatenate GraphQL strings directly.Validate the business-level
errorsarray: under the GraphQL specification, even if some or all fields fail to resolve, the HTTP status code is usually still200; callers must check whetherresponse.errorsis non-empty first after receiving the response.
Key parameters and returns
Methods and Request Payloads
| SDK Method (Node / Web / Java / Python) | Go Method | REST Endpoint | Request Parameters (query Payload Object) | Description |
|---|---|---|---|---|
query({ query }) | Query(query) | POST /v1/graphql | { query: string, variables?: object, operationName?: string } | Executes a GraphQL read-only query or mutation request. |
mutation({ query }) | Mutation(query) | POST /v1/graphql/mutation | { query: string, variables?: object, operationName?: string } | A semantic entry point dedicated to executing GraphQL mutation mutation operations. |
Request Body Field Details
| Field | Type | Required | Constraints / Default | Description |
|---|---|---|---|---|
query | string | Yes | Non-empty GraphQL document string | A standard GraphQL query or mutation statement, supporting fragments (Fragment) and variable declarations. |
variables | object | No | Default {} | A variable key-value mapping corresponding to the $varName parameters declared in the GraphQL statement. |
operationName | string | No | String | When the query document contains multiple named operations, specifies the operation name to execute. |
Response Structure (GraphQL Standard Response Envelope)
| Field | Type | Description |
|---|---|---|
data | object | null | The business data object returned by projecting the query Selection Set; if top-level execution fails, it is null. |
errors | object[] (optional) | List of execution or syntax validation errors. Each item contains message (error description), locations ([{ line, column }]), path (path of the failing field), and optional extensions. |
Errors and boundaries
Two-layer error handling of HTTP 200 and GraphQL
errors[]:Network interruption, gateway unreachable, project not found (
404), or rate limit exceeded (429) will throwAgentbaseException(or return a non-2xx HTTP status code).For GraphQL syntax errors, nonexistent field names, unauthorized target resources, or single-field resolver errors, the HTTP status code remains
200 OK, and error messages are written into theerrorsarray of the response JSON. Business code must both catchAgentbaseExceptionand checkresult.errors.
Unified rate limit quota: The GraphQL API shares the project rate limit system with the REST API (default per-endpoint rate limit 60 requests/minute); when rate limited,
429 rate_limit_exceededand theRetry-Afterresponse header are returned.Query depth and complexity limits: To prevent nested loop queries from exhausting memory, the server limits the maximum nesting depth and node complexity of a single GraphQL query; when bulk-fetching large table rows, it is still recommended to use
queriescursor pagination (limit+cursorAfter).Never inject via string concatenation: Dynamic query conditions must be written into the
variablesdictionary and referenced through GraphQL variables (e.g.mutation($name: String!)) to prevent GraphQL structure injection.
SDK Category Differences
| SDK category | Coverage | Authentication method | Typical scenarios |
|---|---|---|---|
| Server SDK (Node.js / Java / Python / Go) | query, mutation Full | Project API Key (scope verified against the actual resources accessed) | Backend BFF aggregate queries, cross-module batch data assembly |
| Client / Web SDK (Web) | query, mutation Full | User Session / JWT (subject to RLS row-level permissions) | Frontend single-page application fetching user info and business lists in one request |
| Console SDK (Node.js / Java / Python / Go) | query, mutation Full | Management plane Session / short-lived JWT | Custom aggregate queries in the admin console |
Examples by language
Available on both client and server sides; the Web tab uses the user Session and is subject to data plane permissions.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
import { Client, Graphql, AgentbaseException } from 'agentbase-node-sdk';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT ?? 'https://appbuild-sit.oceanbase.com/v1')
.setProject(process.env.APPBASE_PROJECT_ID ?? 'enterprise-ai-hub-210')
.setKey(process.env.APPBASE_API_KEY!);
const graphql = new Graphql(client);
try {
// 1. Execute a read-only query (with parameterized variables)
const queryRes: any = await graphql.query({
query: {
query: `query GetLocaleAndDatabases {
localeGet { countryCode country currency }
tablesDBList { total databases { _id name } }
}`,
variables: {},
},
});
if (queryRes.errors?.length) {
console.error('GraphQL 业务错误:', queryRes.errors);
} else {
console.log('查询结果:', queryRes.data);
}
// 2. Execute a mutation
const mutationRes: any = await graphql.mutation({
query: {
query: `mutation CreateSupportTeam($teamId: String!, $name: String!) {
teamsCreate(teamId: $teamId, name: $name) { _id name total }
}`,
variables: {
teamId: 'team_tier2_support',
name: '二线技术支持专家组',
},
},
});
if (mutationRes.errors?.length) {
console.error('GraphQL 变更错误:', mutationRes.errors);
}
} catch (err) {
if (err instanceof AgentbaseException) {
console.error(`HTTP 异常 [${err.code} ${err.type}]: ${err.message}`);
}
throw err;
}import { Client, Graphql } from 'agentbase-web-sdk'; // Prerequisite: the user has already completed login in the browser
const client = new Client()
.setEndpoint('https://appbuild-sit.oceanbase.com/v1')
.setProject('enterprise-ai-hub-210');
const graphql = new Graphql(client);
const result = await graphql.query({
query: {
query: 'query { accountGet { _id name email status } localeGet { country currency } }',
},
});
if (result.errors) {
console.error('GraphQL errors:', result.errors);
} else {
console.log('Account & Locale:', result.data);
}import io.agentbase.Client;
import io.agentbase.services.Graphql;
import io.agentbase.exceptions.AppBaseException;
import java.util.Map;
Client client = new Client()
.setEndpoint("https://appbuild-sit.oceanbase.com/v1")
.setProject("enterprise-ai-hub-210")
.setKey(System.getenv("APPBASE_API_KEY"));
Graphql graphql = new Graphql(client);
try {
Object result = graphql.query(Map.of(
"query", "query { localeGet { countryCode country currency } }"
));
Object mutationResult = graphql.mutation(Map.of(
"query", "mutation CreateTeam($teamId: String!, $name: String!) { teamsCreate(teamId: $teamId, name: $name) { _id name } }",
"variables", Map.of("teamId", "team_tier2_support", "name", "二线技术支持专家组")
));
System.out.println(result);
System.out.println(mutationResult);
} catch (AppBaseException e) {
System.err.println("HTTP " + e.getCode() + " type=" + e.getType() + ": " + e.getMessage());
}import os
from agentbase.client import Client
from agentbase.services.graphql import Graphql
from agentbase.exception import AgentbaseException
client = (
Client()
.set_endpoint(os.environ.get('APPBASE_ENDPOINT', 'https://appbuild-sit.oceanbase.com/v1'))
.set_project(os.environ.get('APPBASE_PROJECT_ID', 'enterprise-ai-hub-210'))
.set_key(os.environ['APPBASE_API_KEY'])
)
graphql = Graphql(client)
try:
result = graphql.query(query={
'query': 'query { localeGet { countryCode country currency } }'
})
if isinstance(result, dict) and result.get('errors'):
print('GraphQL errors:', result['errors'])
graphql.mutation(query={
'query': 'mutation CreateTeam($teamId: String!, $name: String!) { teamsCreate(teamId: $teamId, name: $name) { _id name } }',
'variables': {'teamId': 'team_tier2_support', 'name': '二线技术支持专家组'},
})
except AgentbaseException as exc:
print(f"GraphQL HTTP error {exc.code} ({exc.type}): {exc.message}")package main
import (
"fmt"
"os"
"agentbase-go-sdk/agentbase"
)
func main() {
cl := agentbase.NewClient(
agentbase.WithEndpoint("https://appbuild-sit.oceanbase.com/v1"),
agentbase.WithProject("enterprise-ai-hub-210"),
agentbase.WithKey(os.Getenv("APPBASE_API_KEY")),
)
graphql := agentbase.NewGraphql(cl)
result, err := graphql.Query(map[string]interface{}{
"query": "query { localeGet { countryCode country currency } }",
})
fmt.Println(result, err)
_, _ = graphql.Mutation(map[string]interface{}{
"query": "mutation CreateTeam($teamId: String!, $name: String!) { teamsCreate(teamId: $teamId, name: $name) { _id name } }",
"variables": map[string]interface{}{"teamId": "team_tier2_support", "name": "二线技术支持专家组"},
})
}# 1. Execute a read-only query (POST /v1/graphql)
curl -sS -X POST "$APPBASE_ENDPOINT/graphql" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{
"query": "query { localeGet { countryCode country currency } }",
"variables": {}
}'
# 2. Execute a data change (POST /v1/graphql/mutation)
curl -sS -X POST "$APPBASE_ENDPOINT/graphql/mutation" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{
"query": "mutation CreateTeam($teamId: String!, $name: String!) { teamsCreate(teamId: $teamId, name: $name) { _id name } }",
"variables": {
"teamId": "team_tier2_support",
"name": "二线技术支持专家组"
}
}'Example Guide
JavaScript / TypeScript full example: ../examples/javascript.md
Python full example: ../examples/python.md
Java full example: ../examples/java.md
Go full example: ../examples/go.md