Developers
Client Libraries for C# and Java
The official .NET and Java libraries for the Trackberry API, with retries, idempotency keys, paging, typed errors and webhook checks built in.
6 min readPublished
Goal
Call the Trackberry API from C# or Java without writing the HTTP plumbing yourself. Trackberry publishes two official client libraries:
| C# / .NET | Java | |
|---|---|---|
| Package | Trackberry on NuGet |
com.trackberry:trackberry-java on Maven Central |
| Version | 0.1.0 | 0.1.0 |
| Runs on | .NET 10 or later | Java 17 or later |
| Source | Trackberry/trackberry-dotnet | Trackberry/trackberry-java |
Both are open source under the MIT license. Both are generated from the API’s OpenAPI file, https://trackberry.com/api/v1/openapi.json, so every endpoint, parameter and field of the API is there, with the names of the API reference. A small hand-written layer on top does what a generator can’t: it sends your token and the API version, retries what is safe to retry, gives every write an idempotency key, walks paged lists, turns errors into exceptions and checks webhook signatures.
The libraries are optional. Plain HTTP stays fully supported, and everything on this page is also described in The Trackberry API for any language: curl, Python, PHP or the HTTP client your ERP already has.
Install
For .NET:
dotnet add package Trackberry
For Java with Maven:
<dependency>
<groupId>com.trackberry</groupId>
<artifactId>trackberry-java</artifactId>
<version>0.1.0</version>
</dependency>
For Java with Gradle:
implementation("com.trackberry:trackberry-java:0.1.0")
Authenticate
Create a token under Organization settings → API & webhooks (see Create a token). A “Read only” token can call every read; anything that changes data needs “Read and write”.
Pass the token to the client, or leave it out and set the
TRACKBERRY_API_TOKEN environment variable, which keeps it out of your code.
The client sends it as Authorization: Bearer tb_... on every request.
using Trackberry;
using var trackberry = new TrackberryClient("tb_...");
// or: new TrackberryClient() reads TRACKBERRY_API_TOKEN
import com.trackberry.Trackberry;
Trackberry trackberry = Trackberry.builder()
.token("tb_...")
.build();
// or: Trackberry.fromEnvironment() reads TRACKBERRY_API_TOKEN
Create one client and reuse it everywhere: both are thread-safe.
Your first call
The client has one property (.NET) or accessor (Java) per section of the API
reference: Shipments, ShipmentActions, Documents, Companies,
AlertsAndChecks, FreeTime, Webhooks and so on, or shipments(),
shipmentActions() and so on in Java. Method names are the API’s
operation names, so get_shipment is GetShipmentAsync in C# and
getShipment in Java.
In C#, each method returns the response; .Ok() reads the object out of it
(.Created() for an answer that is a 201):
var shipment = (await trackberry.Shipments.GetShipmentAsync("shp_812")).Ok()!;
Console.WriteLine($"{shipment.Reference}: {shipment.Status}, ETA {shipment.EffectiveEta}");
In Java, each method has a request-object form, a form with positional
arguments, and a ...WithHttpInfo variant that also returns the status and the
headers. The generated methods also declare the checked ApiException, thrown
only when an answer can’t be read, so declare or catch it:
import com.trackberry.client.api.ShipmentsApi;
import com.trackberry.client.model.Shipment;
Shipment shipment = trackberry.shipments().getShipment(
ShipmentsApi.APIGetShipmentRequest.newBuilder().id("shp_812").build());
System.out.println(shipment.getReference() + ": " + shipment.getStatus());
For a whole ERP import, from listing the ready shipments to recording the export, follow Quick Start: Your First ERP Import and Building an ERP Integration. Each library’s README shows the same loop in its own language.
The API version is pinned
Every request carries Trackberry-Version: 2026-10-01, the API version the
release was generated from. Answers keep the shape the library’s classes
expect, even after an admin moves your organization’s pin forward in settings.
See Versions for how the API is versioned.
The constant is TrackberryClient.ApiVersion in .NET and
Trackberry.API_VERSION in Java. To send another version, set ApiVersion in
TrackberryOptions or call .apiVersion(...) on the Java builder. Set it to
null to get your organization’s pinned version instead. A method’s
trackberryVersion argument overrides it for one call.
What the library handles for you
Retries
The client retries a request that failed for a reason that may pass: a 429,
502, 503 or 504, a connection failure or a try that timed out, and a
409 idempotency_key_in_progress, which means the first request with the
same key is still running. It waits as long as the Retry-After header says,
and otherwise backs off with a random wait of up to 0.5 seconds, then 1, then
2. That is three retries by default. MaxRetries (.NET) and .maxRetries(...)
(Java) change the number, and 0 turns retries off.
A Retry-After longer than MaxRetryDelay (.NET, 30 seconds by default) or
.maxRetryAfter(...) (Java, 60 seconds by default) is not waited for: the
client throws the exception at once, with the wait in RetryAfter
(getRetryAfter() in Java).
A read is always retried. A write is retried only when it carries an idempotency key, so a retry can never make the change twice.
Idempotency keys
The client gives every write a random Idempotency-Key and keeps the same key
for all of that write’s retries. Within 24 hours, the API answers a repeated
key with the first answer instead of doing the work again (see
Retrying writes).
To make a write safe to repeat across restarts of your program, pass your own key, built from what the write is about:
await trackberry.ShipmentActions.RecordErpExportAsync(id, new RecordErpExportRequest(figuresVersion),
idempotencyKey: $"export-{id}-{figuresVersion}");
trackberry.shipmentActions().recordErpExport(ShipmentActionsApi.APIRecordErpExportRequest.newBuilder()
.shipmentId(id)
.recordErpExportRequest(new RecordErpExportRequest().figuresVersion(figuresVersion))
.idempotencyKey("export-" + id + "-" + figuresVersion)
.build());
Three operations handle their key their own way and get no automatic key:
starting tracking (track_shipment), uploading a document
(upload_document) and simulating a sandbox event
(simulate_shipment_event). Pass a key to these when you want them retried.
Paging
Lists of shipments, companies, alerts, products and the other paged lists
return one page at a time. ListAllAsync (.NET) and listAll (Java) walk all
of them: they pass the last item’s id as starting_after while has_more is
true, and fetch a page only when you reach it.
await foreach (var shipment in trackberry.ListAllAsync((after, ct) => trackberry.Shipments.ListShipmentsAsync(
erpStatus: new List<string> { "ready", "changed_since_export" },
startingAfter: after, cancellationToken: ct)))
{
Console.WriteLine($"{shipment.Id} {shipment.ErpStatus}");
}
ShipmentsApi.APIListShipmentsRequest.Builder request = ShipmentsApi.APIListShipmentsRequest.newBuilder()
.erpStatus(List.of("ready", "changed_since_export"));
for (Shipment shipment : trackberry.listAll(
cursor -> trackberry.shipments().listShipments(request.startingAfter(cursor).build()),
ShipmentList::getData,
ShipmentList::getHasMore)) {
System.out.println(shipment.getId() + " " + shipment.getErpStatus());
}
In Java, Pages.streamAll gives a Stream instead.
Errors
An answer outside 2xx throws a TrackberryException, after any retries. Its
subclass says what kind of error it was:
| Exception | When |
|---|---|
AuthenticationException |
401: the token is missing, malformed, revoked or expired |
PermissionException |
403: for example, a read-only token trying to write |
NotFoundException |
404: no such object in the token’s organization |
InvalidRequestException |
400, 409, 422: the request can’t be done as sent |
RateLimitException |
429, still after the retries, or with a Retry-After too long to wait for |
The exception carries the error’s Code, Message, Param and RequestId
(getCode() and so on in Java). Branch on the code, show the message to
people, and quote the request ID to support. A code added to the API after your
release still arrives as a string. Every code is explained in
Troubleshooting by Error Code.
The .NET client also has an IdempotencyException for errors about the
Idempotency-Key. In Java, a request that got no answer at all after the
retries throws an ApiConnectionException; in .NET it is an
HttpRequestException, or a TimeoutException for a try that took too long.
try
{
await trackberry.ShipmentActions.RecordErpExportAsync(id, new RecordErpExportRequest(figuresVersion));
}
catch (InvalidRequestException e) when (e.Code == "unknown_figures_version")
{
// The figures changed while you were importing: import again on the next poll.
}
try {
trackberry.shipments().getShipment(ShipmentsApi.APIGetShipmentRequest.newBuilder().id("shp_999").build());
} catch (NotFoundException e) {
System.out.println(e.getCode() + " " + e.getRequestId());
}
Verify a webhook
When Trackberry calls your server (see Webhooks),
check the request before you act on it. Webhook.Verify (.NET) and
Webhook.verify (Java) check its
Standard Webhooks signature with your
endpoint’s signing secret, refuse a timestamp more than 5 minutes away, and
return the event. Pass the body exactly as you received it, before any JSON
parsing.
using Trackberry.Webhooks;
// In an ASP.NET Core endpoint: body is the raw request body as a string.
try
{
var evt = Webhook.Verify(body, request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString()), secret: "whsec_...");
if (evt.Test == true) return Results.Ok(); // a test event from settings: acknowledge it, don't act on it
Console.WriteLine($"{evt.Id} {evt.Type}");
}
catch (WebhookVerificationException)
{
return Results.BadRequest();
}
import com.trackberry.webhooks.Webhook;
import com.trackberry.webhooks.WebhookEvent;
import com.trackberry.webhooks.WebhookVerificationException;
// rawBody: the body as received (String or byte[]); headers: a Map<String, String>
try {
WebhookEvent event = Webhook.verify(rawBody, headers, System.getenv("TRACKBERRY_WEBHOOK_SECRET"));
System.out.println(event.getId() + " " + event.getType());
} catch (WebhookVerificationException e) {
// answer 400 and ignore the request
}
Use the event’s id to drop duplicate deliveries: a retried delivery keeps the same id. A webhook speaks the API version your organization is pinned to, not the library’s, so read the event’s JSON when its shape is newer than your release.
Test against a sandbox
Build and test with a token from your ERP sandbox, a separate organization of sample data, before you point the client at real shipments. Nothing in the client changes: only the token does.
IsSandboxAsync() (.NET) and isSandbox() (Java) say whether the token belongs
to a sandbox. They ask the API once and remember the answer, so an integration
can check where it is before it writes. In a sandbox,
ErpSandbox.SimulateShipmentEventAsync (.NET) and
erpSandbox().simulateShipmentEvent (Java) make something happen to a
shipment, such as a new ETA or a corrected packing list (see
Simulate an event). Webhook events
from a sandbox have livemode set to false.
Versions of the libraries
The libraries follow semantic versioning, separately from the API’s own date versions:
- Below 1.0, a minor version (0.2.0) adds or changes generated code and may need changes on your side. A patch version (0.1.1) only fixes.
- From 1.0, a major version means a breaking change or a new pinned
Trackberry-Version. A minor version adds operations or fields, and a patch version fixes.
Each release’s changelog entry says which API version it pins. Watch the repositories on GitHub to hear about new releases.
Source, issues and other languages
The code, the changelogs and the full READMEs are on GitHub: trackberry-dotnet and trackberry-java. Report a bug or ask for a feature there.
For another language, generate a client from the OpenAPI file or call the API over plain HTTP, as The Trackberry API describes.
Was this page helpful?
Please leave out names, emails and anything private.