---
title: "Call the API"
description: "Set up the SDK, embed UI, retry writes safely, and handle errors."
canonical: "https://fragment.dev/docs/call-the-api"
---

# Call the API

Source: https://fragment.dev/docs/call-the-api

[Documentation index](https://fragment.dev/llms.txt)

<a id="call-the-api"></a>

Fragment has a GraphQL API. Call it with an [SDK](https://fragment.dev/docs/call-the-api.md#set-up-the-sdk), or with any GraphQL client and an access token from an API client.

<a id="set-up-the-sdk"></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:

```bash group="typescript"
npm install --save @fragment-dev/node-client
```
```bash group="python"
pip install fragment-python
```
```bash group="go"
go get 'github.com/fragment-dev/fragment-go/v3'
```
```bash group="ruby"
gem install fragment-dev
```

Create an API client in the Fragment [Dashboard](https://dashboard.fragment.dev/go/s/api-clients). 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](https://fragment.dev/docs/deploy-to-production.md#create-workspaces) of the Workspace. Each SDK's README covers passing them in, along with initialization, query generation and usage:

- [TypeScript](https://github.com/fragment-dev/node-client/blob/dev/README.md)
- [Python](https://github.com/fragment-dev/fragment-python/blob/dev/README.md)
- [Go](https://github.com/fragment-dev/fragment-go/blob/dev/README.md)
- [Ruby](https://github.com/fragment-dev/fragment-ruby/blob/dev/README.md)

<a id="use-the-cli"></a>

## 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:

```bash title="curl"
curl -fsSL https://fragment.dev/install.sh | sh
```

```bash title="npm"
npm install -g @fragment-dev/cli
```

```bash title="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:

```bash
fragment login --browser
```

In CI and other non-interactive environments, log in with an [API client's](https://fragment.dev/docs/call-the-api.md#set-up-the-sdk) credentials instead. `fragment api-client create` creates one from your terminal:

```bash
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](https://fragment.dev/api-reference/cli.md) lists every command and its flags. In your terminal, run `fragment help`, or `--help` on a command:

```bash
fragment help
fragment verify-schema --help
```

<a id="retry-writes-safely"></a>

## Retry writes safely

[Visual: idempotency. View on the HTML page.](https://fragment.dev/docs/call-the-api?mode=human)

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`.

<a id="handle-errors"></a>

## 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:

```graphql
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.
1. 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.
1. Handle `null` responses from queries by checking the `errors` key. This typically happens when querying an item with an invalid ID.
1. Query the `__typename` field. It contains `BadRequestError`, `InternalError` or the matching `<Mutation>Result` type.
1. Handle `InternalError` with retries and exponential backoff.
1. Handle `BadRequestError` by failing the operation.
1. Handle `<Mutation>Result` types such as `AddLedgerEntryResult`.

This TypeScript example follows that order:

```typescript
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`.

<a id="embed-ui"></a>

## 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:

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

Use Payment Elements to:

- [Render a checkout form](https://fragment.dev/docs/make-payments.md#embed-checkout-render-the-checkout-form) that collects a card for a Payment.
- [Save a customer's card](https://fragment.dev/docs/make-payments.md#manage-saved-cards-save-a-card) to charge later.

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:

```typescript title="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.

<a id="skip-the-sdk"></a>

## Skip the SDK

For a language without an SDK, generate a client and authenticate its requests yourself. Start with an [API client](https://fragment.dev/docs/call-the-api.md#set-up-the-sdk), then:

1. Use the [CLI](https://fragment.dev/docs/call-the-api.md#use-the-cli) to generate GraphQL queries from your Schema. Run `fragment gen-graphql --help` for its options:

   ```bash
   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](https://graphql.org/community/tools-and-libraries/?tags=client) lists codegen tools. Provide the GraphQL schema as input. [Reference](https://fragment.dev/api-reference.md) lists every query, mutation and type in it:

   ```plaintext title="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](https://fragment.dev/docs/call-the-api.md#handle-errors).

[Visual: authentication. View on the HTML page.](https://fragment.dev/docs/call-the-api?mode=human)

Fragment uses OAuth2's [client credentials flow](https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/) 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`:

```plaintext
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}}`:

```json
{
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": "Basic {{client_credentials}}",
    "Accept": "*/*"
}
```

The response is a JSON object containing the access token:

```json
{
    "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;
};
```
