Docs
Contents

GraphQL

Before running the examples, replace <APPBASE_ENDPOINT_WITH_V1> with the intended environment API endpoint and verify that the project and credentials belong to that environment.

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

Usage workflow

  1. Initialize the client and the Graphql service: construct Client and instantiate new Graphql(client).

  2. Execute a read-only query (graphql.query): pass in a JSON payload containing query (the GraphQL query string) plus optional variables (a parameterized variables object) and operationName, then read the on-demand projected results from the data field of the returned object.

  3. Execute a mutation (graphql.mutation): pass in a mutation mutation statement and variables (e.g. creating a row, updating preferences, creating a team, etc.); ensure all dynamic user input is passed via $variable variable binding — never concatenate GraphQL strings directly.

  4. Validate the business-level errors array: under the GraphQL specification, even if some or all fields fail to resolve, the HTTP status code is usually still 200; callers must check whether response.errors is non-empty first after receiving the response.

Key parameters and returns

Methods and Request Payloads

SDK Method (Node / Web / Java / Python)Go MethodREST EndpointRequest 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

FieldTypeRequiredConstraints / DefaultDescription
querystringYesNon-empty GraphQL document stringA standard GraphQL query or mutation statement, supporting fragments (Fragment) and variable declarations.
variablesobjectNoDefault {}A variable key-value mapping corresponding to the $varName parameters declared in the GraphQL statement.
operationNamestringNoStringWhen the query document contains multiple named operations, specifies the operation name to execute.

Response Structure (GraphQL Standard Response Envelope)

FieldTypeDescription
dataobject | nullThe business data object returned by projecting the query Selection Set; if top-level execution fails, it is null.
errorsobject[] (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

SDK Category Differences

SDK categoryCoverageAuthentication methodTypical scenarios
Server SDK (Node.js / Java / Python / Go)query, mutation FullProject API Key (scope verified against the actual resources accessed)Backend BFF aggregate queries, cross-module batch data assembly
Client / Web SDK (Web)query, mutation FullUser 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 FullManagement plane Session / short-lived JWTCustom 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.

import { Client, Graphql, AgentbaseException } from 'agentbase-node-sdk';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT ?? '<APPBASE_ENDPOINT_WITH_V1>')
    .setProject(process.env.APPBASE_PROJECT_ID ?? '<APPBASE_PROJECT_ID>')
    .setKey(process.env.APPBASE_API_KEY!);
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}

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;
}

Example Guide