Meet Toki Operator

Docs/Developers

Manage API.

The GraphQL API behind the Toki app. Read and change everything you manage in Toki — members and their balances, rewards, memberships, gift cards, campaigns and workflows — from your own code.

POSThttps://api.buildwithtoki.com/external/graphql
Operations
292
Sections
24

Your first request

  1. 01

    Get your API key

    In the Toki app, open Integrations and generate your Toki API Key (how). Keep it secret: it acts on your whole program.

  2. 02

    Send a query

    POST a GraphQL query to the endpoint, with the key in the Authorization header.

  3. 03

    Read the response

    You get back exactly the fields you asked for, as JSON.

Request
curl https://api.buildwithtoki.com/external/graphql \
  -H "Authorization: Bearer $TOKI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "query": "{ users(first: 3) { nodes { id email name } } }" }'
Response
{
  "data": {
    "users": {
      "nodes": [
        {
          "id": "6f3c2e97-6e3c-4d04-a13c-31bd703c302a",
          "email": "anna@example.com",
          "name": "Anna Petrova"
        },
        {
          "id": "0b4d1f4e-58c1-4b45-a2f7-0f1b8e65c9d2",
          "email": "li.wei@example.com",
          "name": "Li Wei"
        },
        {
          "id": "c1aa9f6b-03a8-4f1e-bf0d-77d5e4a1f2b3",
          "email": "sam@example.com",
          "name": null
        }
      ]
    }
  }
}

users in the reference lists every field and argument it takes.

Authentication#

Send your API key as a bearer token in the Authorization header of every request. Your account has one key at a time: regenerating it in the app revokes the old key immediately.

Many operations act on one store, which this reference calls the current store: your main store, or the one you pick with the X-Shop-Domain header if your account runs several. Operations that cover all your stores say so. A missing or invalid key is rejected with HTTP 401 or 403.

The key also signs the webhooks Toki sends you, so keep it on your servers — never in a browser or an app.

Headers
Authorization: Bearer <your API key>
Content-Type: application/json
X-Shop-Domain: your-store.myshopify.com   # optional

Requests and responses#

Every request is a POST with a JSON body: query holds the GraphQL document, variables its inputs, and operationName picks one operation when the document holds several.

Ask for exactly the fields you need. Related records are fields too, so a single request can follow them — a member's balances and latest orders, or an activity's completions. Related data is only loaded when you select it.

A response always has data. If anything went wrong it also has errors; see Errors.

One request, three kinds of data
query Member($email: String) {
  user(email: $email) {
    id
    name
    balances(first: 5) {
      nodes {
        name
        balance
        expirationDate
      }
    }
    orders(first: 3) {
      nodes {
        id
        totalPrice
        createdAt
      }
    }
  }
}

Pagination#

Lists are connections: each page has its items in nodes and a pageInfo describing where it sits. Ask for the first page with first — 20 items unless you say otherwise, at most 250.

While pageInfo.hasNextPage is true, ask for the next page with after set to pageInfo.endCursor. To page backwards, use last with before set to pageInfo.startCursor.

Cursors are opaque: they belong to one list with the same arguments. Don't build or store them; take them from the page you just read.

MEMBERS
query Members($after: String) {
  users(first: 100, after: $after) {
    nodes {
      id
      email
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
Fetch every page
const toki = async (query, variables) => {
  const response = await fetch("https://api.buildwithtoki.com/external/graphql", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.TOKI_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ query, variables }),
  });
  return response.json();
};

let after = null;
do {
  const { data } = await toki(MEMBERS, { after });
  for (const member of data.users.nodes) {
    // …
  }
  const { hasNextPage, endCursor } = data.users.pageInfo;
  after = hasNextPage ? endCursor : null;
} while (after);

Errors#

Problems come back in errors, each with a machine-readable extensions.code. When input is invalid, extensions.fieldErrors lists every problem with the path of the field it concerns, ready to show next to a form field.

BAD_USER_INPUT

An argument or input field is invalid. fieldErrors says which one and why.

FORBIDDEN

The key may not do this, or the record belongs to another account.

NOT_FOUND

The record doesn't exist, or isn't yours.

CONFLICT

The change clashes with the record's current state. Read it again and retry.

INTERNAL_SERVER_ERROR

Something failed on our side. The details are logged for us; the response never includes them.

Partial success. Operations that take a list of IDs, such as approving activity completions, handle each ID on its own. They return the IDs that went through in succeededIds and one entry in errors for each ID that didn't, so a single bad ID never undoes the rest.

Invalid input
{
  "errors": [
    {
      "message": "Invalid input",
      "path": [
        "webhookSubscriptionCreate"
      ],
      "extensions": {
        "code": "BAD_USER_INPUT",
        "fieldErrors": [
          {
            "path": [
              "endpoint"
            ],
            "message": "Invalid url"
          }
        ]
      }
    }
  ],
  "data": null
}

Schema and changes#

This reference is generated from the API itself and refreshed every day: every operation, field and description you read here comes from the schema the API runs.

Download the schema to generate typed clients, or browse every type. This page shows schema version 83927b1d368a.

Typed clients
# codegen.yml — GraphQL Code Generator
schema: https://www.buildwithtoki.com/docs/manage-api/schema.graphql
documents: src/**/*.graphql
generates:
  src/toki.generated.ts:
    plugins: [typescript, typescript-operations]

Reference

Operations grouped the way the Toki app is organized.

Shop catalogues

Merchant shops, products, variants and community channels with cursor pagination.

5 queries

Member imports

Import progress, failures and transfer rollbacks.

3 queries2 mutations

Program management

Store credits, exchange rules, membership rewards and activity administration.

10 queries9 mutations

Portal tools

Design embeds and integration lookups.

9 queries

Members

Look up, create and update members, their notes, suspensions, referrals and total codes.

10 queries18 mutations

Balances & redemptions

Points transactions, issued discounts and perks, and redeeming on a member's behalf.

4 queries3 mutations

Orders

Orders Toki has received from your stores.

2 queries

Activities & rewards

Ways to earn, the rewards they issue, and what members can spend points on.

11 queries13 mutations

Completions & approvals

Completed activities: list them, approve or deny submissions, credit a member by hand, or remove one.

2 queries4 mutations

Memberships & tiers

Membership tiers and paid memberships, and when members entered or left them.

7 queries5 mutations

Paid memberships

Members' subscriptions: plans, prices, pauses, cancellations, trials and billing history.

11 queries12 mutations

Segments

Groups of members who meet conditions you set, and each member's progress towards them.

6 queries5 mutations

Loyalty groups

Shared wallets for clubs and teams: groups, members, invitations and Shopify B2B companies.

6 queries11 mutations

Gift cards

Issued gift cards and the gift card products you sell.

4 queries7 mutations

Wallet passes

Apple Wallet and Google Wallet pass designs, and the passes members have installed.

3 queries3 mutations

Reviews

Product reviews, replies, review groups, product groups and the Google Shopping feed.

12 queries17 mutations

Campaigns

Push, email and wallet notifications, sent on a schedule or when something happens.

5 queries8 mutations

Workflows

Automations built from a trigger, conditions and actions, and their executions.

4 queries5 mutations

Webhooks

Subscribe your own endpoints to events, and inspect every delivery.

1 query2 mutations

Program settings

Program-wide settings, languages, translations, purchase rules and product recommendations.

9 queries8 mutations

Design modules

Saved designs of Toki's storefront modules: create, edit and publish them, and open the theme editor to install them.

8 queries3 mutations

Integrations

Connected apps, Tremendous payouts, past order imports and customer sign-in with Toki.

4 queries7 mutations

Analytics

The stats, charts and tables from the Analytics page.

12 queries

SQL reporting

Analytical reports, top customer rankings, sales summaries and reporting dataset descriptions.

1 query1 mutation