Backend SDKs
Call the Astrada API from your server with the backend SDKs for TypeScript, Python and Java: install, log in, make calls, handle errors, check webhooks.
For: developers
The backend SDKs are Astrada's libraries for calling the API from your server, in TypeScript, Python and Java. They are generated from the same API definitions as the API reference. They are separate from the enrollment SDKs that run in the browser: the Unified Enrollment SDK v2 and the legacy Card Enrollment SDK.
Each backend SDK:
- logs in with your API credentials and gets a new token before the old one expires;
- has methods for the API reference calls (all but the direct card-enrollment calls), the Banking API and the sandbox simulations;
- walks list pages for you, retries calls that are safe to repeat, and raises errors that carry the status and the error body;
- checks the signature on a webhook delivery;
- comes with a mock of the API for your own tests.
The packages, each linked to its source and README on GitHub:
- TypeScript:
@astrada.co/ts-astrada-sdkon npm, for Node.js 20 or later. It also works from JavaScript. Reference: TypeDoc. - Python:
astradaon PyPI, for Python 3.10 or later. Reference: pdoc. - Java:
co.astrada:astrada-javaon Maven Central, for Java 11 or later.
The SDKs use your client secret, so run them only on your server, never in a browser or a mobile app.
Install
npm install @astrada.co/ts-astrada-sdk@^2.0.0pip install "astrada>=2.0.0,<3"<dependency>
<groupId>co.astrada</groupId>
<artifactId>astrada-java</artifactId>
<version>2.0.0</version>
</dependency>implementation "co.astrada:astrada-java:2.0.0"Log in
Give the SDK your account ID, client ID and client secret, and the environment: sandbox or production. Sandbox and production have separate credentials, and credentials from one are refused by the other. Authentication explains the credentials; for sandbox ones, see Get a token.
import { Configuration } from '@astrada.co/ts-astrada-sdk';
export const config = new Configuration({
environment: 'sandbox', // or 'production'
accountId: process.env.ASTRADA_ACCOUNT_ID!,
clientId: process.env.ASTRADA_CLIENT_ID!,
clientSecret: process.env.ASTRADA_CLIENT_SECRET!,
});import os
import astrada
client = astrada.Astrada(
account_id=os.environ["ASTRADA_ACCOUNT_ID"],
client_id=os.environ["ASTRADA_CLIENT_ID"],
client_secret=os.environ["ASTRADA_CLIENT_SECRET"],
environment="sandbox", # or "production"
)import co.astrada.client.ApiClient;
import co.astrada.client.Astrada;
import co.astrada.client.Environment;
ApiClient client = Astrada.builder()
.environment(Environment.SANDBOX) // Environment.PRODUCTION for live cards
.credentials(System.getenv("ASTRADA_ACCOUNT_ID"), System.getenv("ASTRADA_CLIENT_ID"),
System.getenv("ASTRADA_CLIENT_SECRET"))
.build();In TypeScript and Python the environment is required (in TypeScript, unless you give a basePath). The Java builder uses production unless you set Environment.SANDBOX.
The SDK requests a token from /auth/realms/{accountId}/protocol/openid-connect/token on the same host on the first call, keeps it until shortly before it expires, then requests a new one. Make one client (one Configuration in TypeScript) and share it: the card API, the Banking API and the sandbox calls all use its one login. If the client ID or secret is wrong, the first call fails with AuthenticationError in TypeScript, astrada.AuthenticationError in Python, and an ApiException in Java, and nothing is sent to the API.
A token for the browser enrollment SDK
The Unified Enrollment SDK v2 asks your backend for a token through its getAccessToken option. Each backend SDK can mint that token with your SDK client, the separate client ID and secret for the browser: config.mintSdkAccessToken(...) in TypeScript, client.mint_sdk_access_token(...) in Python and client.mintSdkAccessToken(...) in Java. Never hand the browser a token of your API client.
The token carries every scope the SDK client holds. Pass the scopes the browser calls need (allowedScopes in TypeScript and Java, allowed_scopes in Python), taken from the SDK credentials table in Authentication; never list banking:admin or webhooks:write. The call then fails with UnexpectedScopesError (UnexpectedScopesException in Java) instead of returning a token that carries any scope outside the list; a token missing a listed scope is still returned. If your SDK client holds a scope the browser does not need, ask Astrada to remove it; without bank sign-in, that includes banking:read and banking:write. Leave the list out only for a sandbox self sign-up client, which is one client for both uses; never in production.
The token is not tied to one subaccount: for its five minutes it works on every subaccount of your account, and with the banking scopes on bank data too. Your server decides who gets a token, so check that the signed-in user may use the subaccount the page opens. Each README shows a token route; Authentication covers the SDK credentials.
Make a call
This lists the first ten subaccounts:
import { SubaccountsApi } from '@astrada.co/ts-astrada-sdk';
const page = await new SubaccountsApi(config).listSubaccounts({ limit: 10 });
for (const subaccount of page._embedded.subaccounts) {
console.log(subaccount.id, subaccount.name);
}page = client.subaccounts.list_subaccounts(limit=10)
for subaccount in page.embedded.subaccounts:
print(subaccount.id, subaccount.name)import co.astrada.client.api.SubaccountsApi;
import co.astrada.client.model.Subaccount;
import co.astrada.client.model.SubaccountList;
SubaccountList page = new SubaccountsApi(client).listSubaccounts(null, 10); // cursor, limit
for (Subaccount subaccount : page.getEmbedded().getSubaccounts()) {
System.out.println(subaccount.getId() + " " + subaccount.getName());
}Each group of calls in the API reference is a class in TypeScript and Java (SubaccountsApi, WebhooksApi, TransactionsApi and so on) and an attribute of the client in Python (client.subaccounts, client.webhooks, client.transactions). Getting Started and the two quick starts, Quick Start: Bank Linking and SDK v2: Quick Start, show the SDK call in the three languages beside the HTTP request for each step that calls the API.
A list call returns one page. To read every page, use paginate in TypeScript, astrada.paginate in Python, and Pages.iterate (or Pages.iterateByOffset for lists paged by offset) in Java.
Banking API
The Banking API's calls (bank links, bank accounts, bank subscriptions, bank transactions and transaction matches) use the same login:
- TypeScript: the
bankingnamespace, such asnew banking.BankLinksApi(config). - Python:
client.banking, such asclient.banking.bank_links. - Java: classes beside the others, such as
new BankLinksApi(client).
Some Banking API calls need the banking:admin scope, and their reference pages say so. Without it the API answers 403, and the SDK raises ScopeRequiredError (TypeScript and Python) or ScopeRequiredException (Java), which names the scope.
Sandbox calls
The sandbox-only calls, the simulations and the deletes that clear test data, are under sandbox in TypeScript (new sandbox.SandboxSimulationApi(config)), client.sandbox in Python and client.sandbox() in Java. On a client set up for production, each one fails with SandboxOnlyError (TypeScript and Python) or SandboxOnlyException (Java) before anything is sent, the login included. The request method for calls an SDK does not wrap (RequestApi.send in TypeScript, client.request in Python and Java) applies the same check to every sandbox-only call and any /simulate path.
Errors, retries and timeouts
An answer outside 2xx raises an error that carries the HTTP status and the error body's title, detail and code:
- TypeScript:
ResponseError, with one subclass per common status:ValidationError(400, 422),AuthenticationError(401),PermissionDeniedError(403),NotFoundError(404),ConflictError(409),RateLimitError(429) andInternalServerError(500 and above). - Python:
astrada.ApiException, with one subclass per common status:BadRequestException(400),UnauthorizedException(401),ForbiddenException(403),NotFoundException(404),ConflictException(409),UnprocessableEntityException(422),RateLimitError(429) andServiceException(500 and above). - Java:
ApiException, unchecked, for every failure. Read the status withgetCode()and the body withgetTitle(),getDetail()andgetErrorCode().
Each SDK retries a call that is safe to repeat (GET, HEAD, PUT, DELETE and OPTIONS) up to twice by default, waiting as long as the API's Retry-After header asks, up to a limit each README gives. A POST or PATCH is never retried after the answers listed below, so a create is not made twice, and the sandbox deletes are never retried after a server error. What each SDK retries:
- TypeScript retries after a
408,429,500,502,503or504, a network error or a timeout. After a401it sends the call once more with a new token. - Python retries after a
429,500,502,503or504, or a read timeout, and after a failed connection for every method except the sandbox deletes,POSTincluded (nothing reached the API). A401raisesUnauthorizedException. - Java retries after a
429or any5xx, or a failed connection, and OkHttp may also resend after a408. After a401it sends the call once more with a new token.
A call waits up to 30 seconds per attempt for an answer in TypeScript and 60 seconds in Python; in Java, up to 10 seconds to connect and 30 seconds to read. Each README shows how to change the timeout and the number of retries.
Verify a webhook
Every webhook delivery is signed with the secret returned once when you create the webhook. Each SDK's handler follows the same three steps; each README shows a full one.
- Check. Pass the raw request body exactly as received, the request headers and the secret. The SDK refuses a delivery whose signature does not match or whose
webhook-timestampis more than five minutes from now: answer it400. - Store what the SDK cannot read. A delivery can be correctly signed and still not readable by this SDK version:
WebhookPayloadErrorin TypeScript,event.unreadablein Python,WebhookEvent.WebhookPayloadExceptionin Java when you read the payload. Store it (body, type, id, timestamp and the time your check passed), count its failures in your store, and answer500so Astrada sends it again. Once the same delivery has failed a few times (the READMEs use 3), answer2xx, but only after it is stored: a2xxwithout the stored copy drops the event. Python also reports a partial delivery: a transaction it could read with one or more of its messages it could not (event.unreadable_messages). Store it, then handle the transaction and answer204. - Replay after updating the SDK. Read each stored delivery with
parseStoredWebhookEvent({ body, type, id, timestamp })in TypeScript,astrada.parse_stored_webhook(body, event_type, id, timestamp)in Python orWebhookEvent.parseStored(id, type, body)in Java, and handle it like a new one. These functions check no signature (the five-minute limit would refuse a stored delivery), so give them only deliveries you stored after the check passed. For a delivery stored without a type (nowebhook-event-typeheader), passNonein Python ornullin Java and read the JSON (data, orgetData()in Java); in TypeScript it cannot be replayed this way, so read its body yourself. Skip a stored delivery whose id you already handled, except a partial delivery whose missing messages you have not. For a transaction, apply the stored body only if itsupdatedAt(updated_atin Python) is newer than your copy's; for other resources, fetch the current state first. Do not compare the event's timestamp, which is when the delivery was sent.
import { createServer } from 'node:http';
import { constructWebhookEvent, WebhookPayloadError, WebhookVerificationError } from '@astrada.co/ts-astrada-sdk';
createServer(async (req, res) => {
const chunks: Buffer[] = [];
try {
// Read inside the try: a client that drops mid-body must not crash the server.
for await (const chunk of req) chunks.push(chunk as Buffer);
const event = constructWebhookEvent(Buffer.concat(chunks), req.headers, process.env.ASTRADA_WEBHOOK_SECRET!);
console.log(event.id, event.type); // handle the event
res.writeHead(204).end();
} catch (error) {
if (error instanceof WebhookPayloadError) {
// Signed, but this SDK version cannot read it: store
// Buffer.concat(chunks), alert, and answer 500 so it is sent again.
console.error('unreadable webhook', req.headers['webhook-id'], error.message);
res.writeHead(500).end();
} else if (error instanceof WebhookVerificationError) {
res.writeHead(400).end(); // not from Astrada, or too old
} else {
console.error(error);
res.writeHead(500).end();
}
}
}).listen(3000);import os
from flask import Flask, request
import astrada
app = Flask(__name__)
@app.post("/astrada/webhooks")
def astrada_webhook():
try:
event = astrada.verify_webhook(
request.get_data(), request.headers, os.environ.get("ASTRADA_WEBHOOK_SECRET", "")
)
except astrada.WebhookVerificationError as error:
app.logger.warning("webhook refused: %s", error) # also shows an empty or bad secret
return "", 400 # not from Astrada, or too old
if event.unreadable or event.unreadable_messages:
# Signed, but this SDK version cannot read the body, or some of a transaction's
# messages: store request.get_data() first, and alert.
if event.unreadable:
return "", 500 # sent again later
# A partial delivery: the transaction was read; replay only its missing messages later.
print(event.id, event.type) # handle the event
return "", 204import co.astrada.client.model.Transaction;
import co.astrada.client.webhooks.WebhookEvent;
import co.astrada.client.webhooks.WebhookVerifier;
import java.util.Map;
public class AstradaWebhooks {
private final WebhookVerifier verifier = new WebhookVerifier(System.getenv("ASTRADA_WEBHOOK_SECRET"));
/** Returns the HTTP status to answer with. */
public int handle(String rawBody, Map<String, String> headers) {
WebhookEvent event;
try {
event = verifier.verifyAndParse(rawBody, headers);
} catch (WebhookVerifier.WebhookVerificationException e) {
return 400; // not from Astrada, or too old
}
try {
switch (String.valueOf(event.getType())) {
case WebhookEvent.TRANSACTION_CREATED:
case WebhookEvent.TRANSACTION_UPDATED:
Transaction transaction = event.getTransaction();
System.out.println(transaction.getId() + " " + transaction.getStatus());
break;
default:
System.out.println(event.getId() + " " + event.getType()); // handle other events
}
} catch (WebhookEvent.WebhookPayloadException e) {
// Signed, but this SDK version cannot read it: store rawBody, alert, and answer 500.
return 500;
}
return 204;
}
}In Python, an empty, missing or non-base64 secret also raises WebhookVerificationError, so log its message: a bad secret then shows on every delivery instead of looking like refused traffic. The signature covers the delivery's id, timestamp and body, not the webhook-event-type header the event's type comes from, so use the type to route and rely on the payload. The event's id is the delivery's webhook-id header, which stays the same when a delivery is sent again: use it to skip one you have already handled. For transaction events the SDKs also give the payload as a typed model; each README lists which events have one. Webhooks covers retries and how fast to answer.
Test without the API
Each SDK comes with a mock that answers every call with the example from the API definition, and lets you set your own answer for a call:
- TypeScript:
createMockFetch()from@astrada.co/ts-astrada-sdk/testing, passed to theConfigurationasfetchApi. - Python:
astrada.testing.MockAstrada. - Java: the separate
co.astrada:astrada-java-testingartifact, with a WireMock stub for each call.
Each README shows the mock in use, and how to run Prism on the API definition instead when you want an HTTP server.
Build with an AI assistant
Connect your assistant to these docs and it can look up any call and model while you write code with the backend SDKs. See Use the Docs with AI Assistants.
Updated 28 minutes ago
