Skip to main content

balikobot_dart 0.3.0 copy "balikobot_dart: ^0.3.0" to clipboard
balikobot_dart: ^0.3.0 copied to clipboard

A Dart client for the Balikobot shipping API v2: packages, labels, tracking, pickups, and carrier capabilities.

balikobot_dart #

balikobot_dart is a Dart client for the Balíkobot shipping API v2. It covers packages, labels, tracking, pickups and carrier capabilities. The client authenticates with HTTP Basic credentials, validates every response, and maps every failure to one sentinel error. It uses the http and json_rest_client libraries.

Install #

dart pub add balikobot_dart

You need Dart 3.13 or later. Only a loopback test server can use the http scheme. Every other base URL must use https.

Quick start #

Create a client with your API user and API key; the client sends them as HTTP Basic authentication. Then add a package, get a label URL and read the tracking status.

import 'package:balikobot_dart/balikobot_dart.dart';

Future<void> main() async {
  final client = BalikobotClient(
    const Config(
      user: 'api-user',
      apiKey: 'api-key',
      timeout: Duration(seconds: 15),
    ),
  );
  try {
    final result = await client.addPackage(
      Carrier.ppl,
      const AddPackageRequest(
        eid: 'order-2026-000123-S1',
        serviceType: '1',
        recName: 'Example Recipient',
        recStreet: 'Example 1',
        recCity: 'Praha',
        recZip: '11000',
        recCountry: Country.cz,
        recPhone: '+420777000000',
        weight: 1.5,
        length: 30,
        width: 20,
        height: 10,
        price: 1000,
        codCurrency: Currency.czk,
      ),
    );

    final labelUrl = await client.labels(Carrier.ppl, result.packageId);
    print(labelUrl);

    final status = await client.trackStatus(Carrier.ppl, result.carrierId);
    print(status.statusText);
  } finally {
    client.close();
  }
}

The example/main.dart file holds the same code.

Methods #

Method Endpoint Purpose
branches GET /{carrier}/branches/... Lists the branches of a service and country
addPackage POST /{carrier}/add Creates one package. ADD is idempotent on eid
overview GET /{carrier}/overview Lists the packages that ORDER has not closed
labels POST /{carrier}/labels Gets a fresh label URL for one package
orderViewLabels GET /{carrier}/orderview/{order_id} Gets the label URL of a closed order
downloadLabel GET the label URL Downloads the label body
downloadLabelPdf POST /{carrier}/labels and label download Downloads one label and requires a PDF body
downloadBatchLabels POST /{carrier}/labels and label download Downloads the labels of one to 1000 packages
parseTrackingNotifications none Parses the raw body of a tracking webhook
trackStatus POST /{carrier}/trackstatus Reads the tracking status of one package
trackStatusStream POST /{carrier}/trackstatus polls Emits changed tracking statuses until stopped
orderBatch POST /{carrier}/order Hands one package to the carrier batch
dropPackage POST /{carrier}/drop Removes one package before ORDER
orderPickup POST /{carrier}/orderpickup Books one physical collection
whoAmI GET /info/whoami Reads the account and carrier data
activatedServices GET /{carrier}/activatedservices Lists the activated services
countries GET /{carrier}/countries4service Lists the destination countries
cod GET /{carrier}/cod4services Lists the cash-on-delivery destinations
carrierCapabilities GET the discovery endpoints Discovers the contracted carriers and services
resolveBranchId none Chooses the branch id or the branch zip for an ADD request

Codes #

Carrier, currency and country values are typed, not plain strings.

Type Format Common constants
Carrier ^[a-z0-9]{2,32}$ ppl, dpd, dpdcz, dpdsk, geis, gls, intime, cp, ceskaposta, balikovna, zasilkovna, sp, ulozenka
Currency ISO 4217 ^[A-Z]{3}$ czk, eur, usd, gbp, pln, huf, ron, bgn, hrk, chf, nok, sek, dkk
Country ISO 3166-1 alpha-2 ^[A-Z]{2}$ EU member states plus gb, ch, no, isIceland, li, ua, rs, ba, me, mk, al, tr, us, ca

Every type has a fromString function and an isValid getter. fromString trims the value, normalises the case and accepts any well-formed code. A malformed value throws a FormatException. Use fromString for a value that has no constant, so custom carriers, currencies and countries work:

final custom = Carrier.fromString('MyCarrier99');
final result = await client.addPackage(custom, request);

The types keep the wire values compile-time safe: a function that expects a Carrier rejects a bare string, and a mistyped constant fails the build. The JSON form stays a plain string, so the wire contract does not change.

ADD accepts only Currency.czk and Currency.eur as codCurrency, because the carriers require one of those two values. The client rejects every other well-formed currency code before the request.

Errors #

The client reports every failure with a BalikobotException. The code field holds one of six BalikobotError values.

Error Meaning Action
BalikobotError.invalidRequest The arguments are not valid. The client sent no request. Correct the input. Do not retry.
BalikobotError.rejected The provider refused the data permanently. Correct the data. Do not retry.
BalikobotError.unavailable The provider is unavailable, or the request never left the client. Retry later.
BalikobotError.notFound The carrier has no tracking data yet. Poll again later.
BalikobotError.ambiguous A mutating call can have reached the provider. Reconcile with overview. Then retry.
BalikobotError.invalidResponse The answer violates the protocol. Inspect the provider. Do not retry blindly.

When a 429 response carries a Retry-After header, an unavailable failure carries the retryAfter field on BalikobotException. Read the field and wait before the next call:

try {
  await client.orderBatch(Carrier.ppl, packageId);
} on BalikobotException catch (error) {
  final retryAfter = error.retryAfter;
  if (retryAfter != null) {
    await Future<void>.delayed(retryAfter);
  }
}

orderPickup maps HTTP 429 to rejected. The branch, label download and capability calls return unavailable without a hint.

The client sends no automatic retry. You control the retry policy.

Labels #

downloadLabelPdf combines the label lookup and the download and requires a PDF body:

final pdf = await client.downloadLabelPdf(Carrier.ppl, packageId);
File('label.pdf').writeAsBytesSync(pdf);

Other media types, such as ZPL, throw a BalikobotException with BalikobotError.invalidResponse. Use labels and downloadLabel when you need the media type.

Tracking webhooks #

parseTrackingNotifications parses the raw JSON body of a Balíkobot tracking webhook. The body can be one notification object or an array of up to 1000 objects; an empty array returns an empty list. Each entry must identify the package through package_id, eid or carrier_id. Each entry must also carry a decimal status_id or status_id_v2 and a description in name or status_text. A malformed body throws a BalikobotException with BalikobotError.invalidResponse.

final notifications = parseTrackingNotifications(request.body);
for (final notification in notifications) {
  print('${notification.statusId}: ${notification.statusText}');
}

Polling tracking status #

trackStatusStream polls trackStatus and emits the first result and every change of the status id. The stream stops when stopWhen returns true:

await for (final status in client.trackStatusStream(
  Carrier.ppl,
  carrierId,
  interval: const Duration(minutes: 15),
  stopWhen: (status) => status.statusId == '1.2',
)) {
  print('${status.statusId}: ${status.statusText}');
}

The stream ends with the error when a poll fails. A cancelled subscription lets a pending interval finish before the stream closes.

Response limits #

The client reads every JSON body with a hard limit of 8 MiB. Set Config.maxResponseBytes to change the limit. Single and batch label downloads use a fixed limit of 4 MiB. The client refuses redirects and compares the response Content-Type with the expected media type before it decodes the body.

Account mode #

Set Config.liveAccount to true or false to verify the account before each non-GET call. The client calls WHOAMI and compares the live_account flag. A mismatch blocks the write before the client sends it. A successful result stays valid for five minutes. If Config.liveAccount is null, the client skips the check.

Carrier capability cache #

carrierCapabilities caches its result for Config.capabilityCacheTtl, ten minutes by default. A repeated call for the same scope returns the cached list without a request. Pass refresh: true to discover again, and call clearCapabilityCache() to drop every cached scope:

final carriers = await client.carrierCapabilities();
final fresh = await client.carrierCapabilities(refresh: true);
client.clearCapabilityCache();

Set capabilityCacheTtl: Duration.zero to disable the cache. Concurrent calls for the same scope share one discovery run. A failed run is not cached, and clearing the cache does not cancel a run that is already in flight.

Label hosts #

The client accepts label URLs only from pdf.balikobot.cz and the *.balikobot.cz subdomains. It also accepts the base URL origin of a loopback test server. Set Config.labelHosts to replace the default allowlist with other hosts. A leading dot selects a subdomain suffix match; it does not match the bare domain.

Development #

Run the checks from the package root:

dart analyze --fatal-infos
dart test

The tests use mocked HTTP clients, with no real credentials and no external network.

Support #

If this project helps you, you can support its development.

Support me on Ko-fi Buy me a coffee

Licence #

MIT. See LICENSE.

0
likes
150
points
142
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A Dart client for the Balikobot shipping API v2: packages, labels, tracking, pickups, and carrier capabilities.

Repository (GitHub)
View/report issues

Topics

#http #rest #balikobot #shipping #api

License

MIT (license)

Dependencies

http, json_rest_client, meta

More

Packages that depend on balikobot_dart