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-clientCreate 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 -fsSL https://fragment.dev/install.sh | shnpm install -g @fragment-dev/clibrew tap fragment-dev/tap
brew install fragment-dev/tap/fragment-cliRun 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 --browserIn 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 --helpc. 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,syncCustomAccountsandsyncCustomTxs, FRAGMENT uses the transaction or account ID from the request as the idempotency key. - A repeated request with the same
ikis ignored. The API returns the original response withisIkReplay: true. - Idempotency keys are scoped per Ledger. Requests with the same
ikto different Ledgers each run the mutation and returnisIkReplay: 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 returnnullfor itsdatawhen an error is raised, with a non-emptyerrorslist.
For example, the response type of the addLedgerEntry mutation is:
union AddLedgerEntryResponse =
AddLedgerEntryResult | BadRequestError | InternalErrorWhen you call the API, handle errors in this order:
- Handle retryable HTTP errors. These are 429 or 5XX.
- 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.
- Handle
nullresponses from queries by checking theerrorskey. This typically happens when querying an item with an invalid ID. - Query the
__typenamefield. It containsBadRequestError,InternalErroror the matching<Mutation>Resulttype. - Handle
InternalErrorwith retries and exponential backoff. - Handle
BadRequestErrorby failing the operation. - Handle
<Mutation>Resulttypes such asAddLedgerEntryResult.
This TypeScript example follows that order:
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:
internalErrorreturns anInternalError.badRequestErrorreturns aBadRequestError.
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-elementsUse Payment Elements to:
- Render a checkout form that collects a card for a Payment.
- Save a customer's 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:
<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:lightordark. Defaults todarkwhen<html>has thedarkclass.colors:text,mutedText,inputBackground,inputFocusBackground,surface,borderanderror.fontFamily: a font family the payment frame already has. The frame loads no web font from your page.fontSize: a size inpx, such as16px. 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:
-
Use the CLI to generate GraphQL queries from your Schema. Run
fragment gen-graphql --helpfor its options:fragment get-schema \ --output=schema.jsonc &&\ fragment gen-graphql \ --path=schema.jsonc \ --output=queries.graphql -
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 URLhttps://api.fragment.dev/schema.graphql -
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.
-
Add the
Authorizationrequest header with the valueBearer {{access_token}}when you call the GraphQL API. -
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:
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}}:
{
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic {{client_credentials}}",
"Accept": "*/*"
}The response is a JSON object containing the access token:
{
"access_token": "<access token>",
"expires_in": 3600,
"token_type": "Bearer"
}
Putting it all together:
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;
};