Skip to main content

Tillcast Python Library

fern shield pypi

Send a receipt to a printer from your own software: create a print job, make the call safe to retry and read the job back. Pre-release (0.x): the Tillcast API is live, but method names can still change before 1.0, so pin the version.

Table of Contents

Documentation

API reference documentation is available here.

Installation

pip install tillcast

Reference

A full reference for this library is available here.

Before you start

You need an API key and the id of a printer.

  • An API key. In the dashboard, open API keys and create a key with the scopes jobs:write (create a job), jobs:read (read one) and printers:read (list printers). The key is shown once. Keep it in an environment variable, never in your code. Authentication and API keys says more, and the quickstart goes from sign-up to a first receipt.
  • The id of a printer, prn_.... It is in the answer that adds the printer, in the printers list of the dashboard, and from client.printers.list() (see "Read a job" below).

Build the client with the key as token. The samples below read the key and the printer id from TILLCAST_API_KEY and TILLCAST_PRINTER_ID, and they continue one another, so they run as one script.

import os

from tillcast import Tillcast

client = Tillcast(token=os.environ["TILLCAST_API_KEY"])

Create a print job

A job is one document for one printer. The document is a list of blocks in print order, written as plain dicts. This receipt has a centred title, a table with a rule and a total.

job = client.jobs.create(
    printer=os.environ["TILLCAST_PRINTER_ID"],
    idempotency_key="order-4711-bill",
    document=[
        {"type": "text", "text": "Harbour Cafe", "align": "center", "bold": True, "size": 2},
        {"type": "text", "text": "Table 7", "align": "center"},
        {
            "type": "table",
            "columns": ["*", {"width": 9, "align": "right"}],
            "rows": [
                ["Flat white", "3.40"],
                ["Lemon cake", "4.20"],
                {"type": "rule"},
                [{"text": "Total", "bold": True}, {"text": "7.60", "bold": True}],
            ],
        },
    ],
    client_reference_id="order-4711",
)
print(job.id, job.status, job.warnings)

The answer is the job, and its status is queued. The printer takes it at its next poll and prints it. Text of your own, such as the name of an item, goes into a block as it is: nothing in a block is markup. Receipt documents describes every block.

If you have text written for other ReceiptLine tools, send it as receiptline instead of document. Send one of the two, never both.

client.jobs.create(
    printer=os.environ["TILLCAST_PRINTER_ID"],
    idempotency_key="order-4712",
    receiptline="Harbour Cafe\nTable 7\n{width:*,9}\nFlat white | 3.40\nLemon cake | 4.20\n-\nTotal | 7.60",
    client_reference_id="order-4712",
)

Create a print job in the docs has the same call with cURL, every field and the refusals.

Retry safely

A call can fail after Tillcast has accepted it. Send an idempotency key with every job, the argument idempotency_key in Python. If you send the same request again with the same key, you get the first job back and nothing is printed twice. Use one key for each print you intend, for example the order number and the kind of paper, and a new key for a new receipt.

The client also retries a request on its own, twice, when the answer is 408, 409, 429 or a 5xx. The retry carries the same key, so with a key it is safe. Without one, a retry after a lost answer can print twice.

This sends the same request twice, as a retry would. The first answer is 201. The second is 200 with the header Idempotent-Replayed: true and the same job id.

def send():
    return client.jobs.with_raw_response.create(
        printer=os.environ["TILLCAST_PRINTER_ID"],
        idempotency_key="order-4711-kitchen",
        document=[{"type": "text", "text": "Table 7: flat white"}],
        client_reference_id="order-4711",
    )


first = send()
again = send()

print(first.status_code, first.data.id)
print(again.status_code, again.headers.get("idempotent-replayed"), again.data.id)

The same key with a different request is 422 idempotency_key_reused. A key is remembered for 24 hours. Idempotency has the rules.

Read a job

Read a job back with its id. It moves from queued to delivered to printed, or it ends failed, expired or cancelled. When it is failed, reason and result_code say why.

status = client.jobs.get(job.id)
print(status.status, status.reason, status.result_code)

A printer takes a job within about one poll interval, 5 seconds by default, so do not poll faster than you need. Webhooks, which would tell you without polling, are planned and do not exist yet.

The printer id comes from the answer that adds the printer, from the printers list of the dashboard, or from the API. If you gave each printer your own client_reference_id, look the printer up with it.

printers = client.printers.list(client_reference_id="kitchen-1")
print([printer.id for printer in printers.data])

A refused document

Tillcast checks the document when it accepts the job, so a mistake is an answer to your request and no job is made. A document that cannot be printed as it is said is 422 document_invalid, and param is the path of the first problem. This table has two columns and a row of three cells.

from tillcast import UnprocessableEntityError

try:
    client.jobs.create(
        printer=os.environ["TILLCAST_PRINTER_ID"],
        idempotency_key="order-4713-bill",
        document=[
            {"type": "text", "text": "Harbour Cafe"},
            {"type": "table", "columns": ["*", 9], "rows": [["Flat white", "3.40", "1"]]},
        ],
    )
except UnprocessableEntityError as err:
    error = err.body.error
    print(error.code, error.param, error.message, error.request_id)

Here code is document_invalid and param is document[1].rows[0]: block 1 is the table, and row 0 is its first row. A refused request leaves its key free. Any other refusal is a subclass of ApiError (tillcast.core.api_error.ApiError) with status_code and body. Branch on body.error.code, for example resource_missing when there is no such printer, customer_suspended or queue_full. Errors lists the codes and what to do.

Usage

Instantiate and use the client with the following:

from tillcast import Tillcast

client = Tillcast(
    token="<token>",
)

client.jobs.create(
    printer="prn_01M44X7TQ0A9R2H5J8K1M4N7P0",
    idempotency_key="order-1042",
    client_reference_id="order-1042",
    document=[
        {
            "type": "text",
            "align": "center",
            "bold": True,
            "size": 2,
            "text": "Harbour Cafe"
        },
        {
            "type": "text",
            "align": "center",
            "text": "Old Town 1"
        },
        {
            "type": "table",
            "columns": [
                "*",
                {
                    "align": "right",
                    "width": 9
                }
            ],
            "rows": [
                [
                    "Flat white",
                    "3.40"
                ],
                [
                    "Lemon cake",
                    "4.20"
                ],
                {
                    "type": "rule"
                },
                [
                    {
                        "bold": True,
                        "text": "Total"
                    },
                    {
                        "bold": True,
                        "text": "7.60"
                    }
                ]
            ]
        },
        {
            "type": "qr",
            "align": "center",
            "data": "https://tillcast.com/"
        }
    ],
    expires_in=3600,
    metadata={
        "table": "7"
    },
)

Environments

This SDK allows you to configure different environments for API requests.

from tillcast import Tillcast
from tillcast.environment import TillcastEnvironment

client = Tillcast(
    environment=TillcastEnvironment.PRODUCTION,
)

Async Client

The SDK also exports an async client so that you can make non-blocking calls to our API. Note that if you are constructing an Async httpx client class to pass into this client, use httpx.AsyncClient() instead of httpx.Client() (e.g. for the httpx_client parameter of this client).

import asyncio

from tillcast import AsyncTillcast

client = AsyncTillcast(
    token="<token>",
)


async def main() -> None:
    await client.jobs.create(
        printer="prn_01M44X7TQ0A9R2H5J8K1M4N7P0",
        idempotency_key="order-1042",
        client_reference_id="order-1042",
        document=[
            {
                "type": "text",
                "align": "center",
                "bold": True,
                "size": 2,
                "text": "Harbour Cafe"
            },
            {
                "type": "text",
                "align": "center",
                "text": "Old Town 1"
            },
            {
                "type": "table",
                "columns": [
                    "*",
                    {
                        "align": "right",
                        "width": 9
                    }
                ],
                "rows": [
                    [
                        "Flat white",
                        "3.40"
                    ],
                    [
                        "Lemon cake",
                        "4.20"
                    ],
                    {
                        "type": "rule"
                    },
                    [
                        {
                            "bold": True,
                            "text": "Total"
                        },
                        {
                            "bold": True,
                            "text": "7.60"
                        }
                    ]
                ]
            },
            {
                "type": "qr",
                "align": "center",
                "data": "https://tillcast.com/"
            }
        ],
        expires_in=3600,
        metadata={
            "table": "7"
        },
    )


asyncio.run(main())

Exception Handling

When the API returns a non-success status code (4xx or 5xx response), a subclass of the following error will be thrown.

from tillcast.core.api_error import ApiError

try:
    client.jobs.create(...)
except ApiError as e:
    print(e.status_code)
    print(e.body)

Advanced

Access Raw Response Data

The SDK provides access to raw response data, including headers, through the .with_raw_response property. The .with_raw_response property returns a "raw" client that can be used to access the .headers and .data attributes.

from tillcast import Tillcast

client = Tillcast(...)
response = client.jobs.with_raw_response.create(...)
print(response.headers)  # access the response headers
print(response.status_code)  # access the response status code
print(response.data)  # access the underlying object

Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retryable and the number of retry attempts has not grown larger than the configured retry limit (default: 2).

Which status codes are retried depends on the retryStatusCodes generator configuration:

legacy (current default): retries on

  • 408 (Timeout)
  • 409 (Conflict)
  • 429 (Too Many Requests)
  • 5XX (All server errors, including 500)

recommended: retries on

  • 408 (Timeout)
  • 409 (Conflict)
  • 429 (Too Many Requests)
  • 502 (Bad Gateway)
  • 503 (Service Unavailable)
  • 504 (Gateway Timeout)

Use the max_retries request option to configure this behavior.

client.jobs.create(..., request_options={
    "max_retries": 1
})

Timeouts

The SDK defaults to a 60 second timeout. You can configure this with a timeout option at the client or request level.

from tillcast import Tillcast

client = Tillcast(..., timeout=20.0)

# Override timeout for a specific method
client.jobs.create(..., request_options={
    "timeout": 1
})

Custom Client

You can override the httpx client to customize it for your use-case. Some common use-cases include support for proxies and transports.

import httpx
from tillcast import Tillcast

client = Tillcast(
    ...,
    httpx_client=httpx.Client(
        proxy="http://my.test.proxy.example.com",
        transport=httpx.HTTPTransport(local_address="0.0.0.0"),
    ),
)

Contributing

While we value open-source contributions to this SDK, this library is generated programmatically. Additions made directly to this library would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!

Metadata

Release files for tillcast 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tillcast 0.2.1
File Size Uploaded Provenance Actions
tillcast-0.2.1.tar.gz 108.2 kB Without provenance Details for tillcast-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tillcast 0.2.1
File Interpreter ABI Platform Actions
tillcast-0.2.1-py3-none-any.whl Python 3 none any Details for tillcast-0.2.1-py3-none-any.whl

Total release size: 309.0 kB

Release files / tillcast-0.2.1.tar.gz

Download URL tillcast-0.2.1.tar.gz
Size 108.2 kB
Tags Source
SHA-256 checksum
How to use checksums
ca5a33803509a6527e9a71891240ff446214363edb7c13712e80512e33ce37dd
BLAKE2b-256 checksum
How to use checksums
d5979f831c8251e77ed16ece66d33893d1b5fe362edd43a040645f0fee8cbade
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Release files / tillcast-0.2.1-py3-none-any.whl

Download URL tillcast-0.2.1-py3-none-any.whl
Size 200.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ab16e11390e78dd07c4646388bec9e74bd8d6fefef442c8feb2bc10333f9cc3e
BLAKE2b-256 checksum
How to use checksums
e32c5d6692843c4ef11c873e18700ba984d9e4cf0fe80392e8beab615baec661
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Security for tillcast 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page