Skip to content
FRAGMENT
C Call the API#

FRAGMENT has a GraphQL API. Call it with an SDK, or with any GraphQL client and an access token from an API client.

a. Set up the SDK

#

FRAGMENT publishes open-source SDKs for TypeScript, Python, Go and Ruby. Each SDK implements authentication and comes with predefined GraphQL queries. Install the SDK for your language:

npm install --save @fragment-dev/node-client

Create an API client in the FRAGMENT Dashboard. Each API client has a role that scopes its permissions:

  • Admin: full read and write access to the Workspace.
  • Reader: read-only access.

Note the API client's auth endpoint URL and OAuth scope. They are specific to the AWS region of the Workspace. Each SDK's README covers passing them in, along with initialization, query generation and usage:

b. Use the CLI

#

The FRAGMENT CLI calls the API from your terminal or a CI pipeline. Use it to store and verify Schemas, create Ledgers, post Ledger Entries, generate GraphQL queries and create API clients. Install it with one of:

curl
curl -fsSL https://fragment.dev/install.sh | sh
npm
npm install -g @fragment-dev/cli
Homebrew
brew tap fragment-dev/tap
brew install fragment-dev/tap/fragment-cli

Run fragment version to print the installed version, and fragment update to update it. The CLI checks for a newer release on each command. Set FRAGMENT_SKIP_AUTO_UPDATE=true to skip the check. Sign in through your browser, on the same machine as the CLI. Add --workspace <workspace-id> to select a Workspace directly:

fragment login --browser

In CI and other non-interactive environments, log in with an API client's credentials instead. fragment api-client create creates one from your terminal:

fragment login \
  --api-url="<api-url>" \
  --client-id="<client-id>" \
  --client-secret="<client-secret>" \
  --oauth-scope="<oauth-scope>" \
  --oauth-url="<oauth-url>"

The CLI saves credentials to ~/.fragment/auth.json. Run fragment login --test to check them. CLI Commands lists every command and its flags. In your terminal, run fragment help, or --help on a command:

fragment help
fragment verify-schema --help

c. Retry writes safely

#

All write mutations in FRAGMENT are idempotent, so each write runs exactly once. Your application can retry a write without duplicate effects. It only needs to call the API at least once:

  • Mutations require a unique idempotency key (ik).
  • For calls to reconcileTx, syncCustomAccounts and syncCustomTxs, FRAGMENT uses the transaction or account ID from the request as the idempotency key.
  • A repeated request with the same ik is ignored. The API returns the original response with isIkReplay: true.
  • Idempotency keys are scoped per Ledger. Requests with the same ik to different Ledgers each run the mutation and return isIkReplay: false.

d. Handle errors

#

Every response is an object containing data and errors:

  • data: the result of a query or mutation. In the FRAGMENT API, every mutation returns a union type that represents an application error or a successful result.
  • errors: a list of errors raised during the request. It is typically populated when a query omits a required argument or passes an invalid ID. A query can return null for its data when an error is raised, with a non-empty errors list.

For example, the response type of the addLedgerEntry mutation is:

API Response Union Types
union AddLedgerEntryResponse =
    AddLedgerEntryResult | BadRequestError | InternalError

When you call the API, handle errors in this order:

  1. Handle retryable HTTP errors. These are 429 or 5XX.
  2. Handle non-retryable HTTP errors, such as other 4XX status codes. These typically happen when the query does not conform to the GraphQL spec, like omitting a required variable or selecting a nonexistent field. A generated, typed SDK avoids this class of error.
  3. Handle null responses from queries by checking the errors key. This typically happens when querying an item with an invalid ID.
  4. Query the __typename field. It contains BadRequestError, InternalError or the matching <Mutation>Result type.
  5. Handle InternalError with retries and exponential backoff.
  6. Handle BadRequestError by failing the operation.
  7. Handle <Mutation>Result types such as AddLedgerEntryResult.

This TypeScript example follows that order:

Handling API Responses
↓
import assert from 'assert';

type RequestParams = {
query: string;
variables: Record<string, unknown>;
};

const makeRequest = async ({ query, variables }: RequestParams): Promise<Response> => {
const token = await getToken();
return fetch('Fragment GraphQL URL', {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query, variables }),
});
};

const query = '''
mutation addLedgerEntry($ik: SafeString, $entry: LedgerEntryInput!) {
addLedgerEntry(ik: $ik, entry: $entry) {
__typename
...
}
}
''';
const variables = { ik: 'sample-ik', entry: {...} };

const handleRequest = (req: Response) => {
if (req.status === 429 || req.status >= 500) {
// Rate-limited or intermittent http failures. Retry the request.
return handleRequest(await makeRequest({ query, variables }));
}
if (req.status >= 400 && req.status < 500) {
// Invalid GraphQL request provided to Fragment. Handle the error.
throw new Error('Invalid GraphQL request');
}

// .json() checks that it was a 200
const response = await req.json();
if (response.data.addLedgerEntry.__typename === 'InternalError') {
// Retry the request in case of internal errors, with backoff.
return handleRequest(await makeRequest({ query, variables }));
}
if (response.data.addLedgerEntry.__typename === 'BadRequestError') {
// Invalid request provided to Fragment. Handle the error.
throw new Error('Invalid API request to Fragment');
}
return response;
};

const response = handleRequest(await makeRequest({ query, variables }));
// Entry successfully posted to Fragment. Handle the response.
assert(response.data.addLedgerEntry.__typename === 'AddLedgerEntryResult');
handlePostedEntry(response.data.addLedgerEntry);
 

To test how your application handles errors, set the X-Fragment-Return-Error request header. FRAGMENT skips processing your request and returns the error immediately:

  • internalError returns an InternalError.
  • badRequestError returns a BadRequestError.

e. Embed UI

#

FRAGMENT publishes Payment Elements, a React SDK that collects card details in your frontend. It needs React 17, 18 or 19. Install the SDK:

npm install --save @fragment-dev/payment-elements

Use Payment Elements to:

Pass a theme to PaymentElements to change how the card form looks. Every field is optional, and a field you leave out keeps FRAGMENT's default:

Checkout.tsx
<PaymentElements
  theme={{
    appearance: 'light',
    colors: { text: 'rgb(20 20 20)', error: 'rgb(200 30 30)' },
    fontFamily: 'Inter, sans-serif',
    fontSize: '16px',
    borderRadius: '8px',
  }}
>
  {/* PaymentSession or PaymentMethodSetupSession */}
</PaymentElements>

The fields render in a frame that cannot read your page's CSS custom properties, so pass literal colors. Each field sets:

  • appearance: light or dark. Defaults to dark when <html> has the dark class.
  • colors: text, mutedText, inputBackground, inputFocusBackground, surface, border and error.
  • fontFamily: a font family the payment frame already has. The frame loads no web font from your page.
  • fontSize: a size in px, such as 16px. The line height follows it.
  • borderRadius: the corner radius of the fields, the rows and the address suggestions.

f. Skip the SDK

#

For a language without an SDK, generate a client and authenticate its requests yourself. Start with an API client, then:

  1. Use the CLI to generate GraphQL queries from your Schema. Run fragment gen-graphql --help for its options:

    fragment get-schema \
      --output=schema.jsonc &&\
    fragment gen-graphql \
      --path=schema.jsonc \
      --output=queries.graphql
  2. Generate a type-safe client with a GraphQL codegen tool for your language. The GraphQL website lists codegen tools. Provide the GraphQL schema as input. Reference lists every query, mutation and type in it:

    GraphQL schema URL
    https://api.fragment.dev/schema.graphql
  3. Get a fresh access token from the token endpoint. The access token expires in 1 hour. Retrieve a new token for each set of calls. You can generate several tokens and use them at the same time.

  4. Add the Authorization request header with the value Bearer {{access_token}} when you call the GraphQL API.

  5. Implement error handling.

FRAGMENT uses OAuth2's client credentials flow to authenticate API clients. The call requesting an access token follows the OAuth2 spec. Use an OAuth2 library that supports the client credentials grant to retrieve the token, or make an HTTP request. The token request payload is in x-www-form-urlencoded format, with the keys grant_type, scope and client_id:

Token request body
grant_type=client_credentials&scope={{scope}}&client_id={{client_id}}

The token request headers contain these items, where client_credentials is the Base64-encoded version of {{client_id}}:{{client_secret}}:

Token request headers
{
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": "Basic {{client_credentials}}",
    "Accept": "*/*"
}

The response is a JSON object containing the access token:

Token response body
{
    "access_token": "<access token>",
    "expires_in": 3600,
    "token_type": "Bearer"
}

Putting it all together:

Javascript
↓
import axios from "axios";

const btoa = (str) => Buffer.from(str).toString("base64");

// credentials from the dashboard
const clientId = "2h4t0cv7qv5c9r0qgs1o3erkuk";
const secret = "superSecretClientSecret";
const scope = "https://api.us-west-2.fragment.dev/*";
const authUrl = "https://auth.us-west-2.fragment.dev/oauth2/token";

const getToken = async () => {

// encode the client id and secret
const auth = btoa(`${clientId}:${secret}`);

// create the request body
const data = new URLSearchParams();
data.append("grant_type", "client_credentials");
data.append("scope", scope);
data.append("client_id", clientId);

// retrieve the token
const response = await axios.request({
method: "POST",
url: authUrl,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Basic ${auth}`,
Accept: "*/*",
},
data,
});

if (!response.data.access_token) {
throw new Error(
"didn't get an access token from auth endpoint"
);
}
return response.data.access_token;
};