Skip to main content

No project description provided

Project description

Square Python Library

fern shield pypi

The Square Python library provides convenient access to the Square API from Python.

Installation

pip install squareup

Requirements

Use of the Square Python SDK requires:

  • Python 3.8+

Usage

Instantiate and use the client with the following:

from square import Square

client = Square(
    # This is the default and can be omitted.
    token=os.environ.get("SQUARE_TOKEN"),
)
client.payments.create(
    source_id="ccof:GaJGNaZa8x4OgDJn4GB",
    idempotency_key="7b0f3ec5-086a-4871-8f13-3c81b3875218",
    amount_money={
        "amount": 1000,
        "currency": "USD"
    },
    app_fee_money={
        "amount": 10,
        "currency": "USD"
    },
    autocomplete=True,
    customer_id="W92WH6P11H4Z77CTET0RNTGFW8",
    location_id="L88917AVBK2S5",
    reference_id="123456",
    note="Brief description"
)

Async Client

The SDK also exports an async client so that you can make non-blocking calls to our API.

import asyncio

from square import AsyncSquare

async def main() -> None:
    client = AsyncSquare(
        # This is the default and can be omitted.
        token=os.environ.get("SQUARE_TOKEN"),
    )
    await client.payments.create(
        source_id="ccof:GaJGNaZa8x4OgDJn4GB",
        idempotency_key="7b0f3ec5-086a-4871-8f13-3c81b3875218",
        amount_money={
            "amount": 1000,
            "currency": "USD"
        },
        app_fee_money={
            "amount": 10,
            "currency": "USD"
        },
        autocomplete=True,
        customer_id="W92WH6P11H4Z77CTET0RNTGFW8",
        location_id="L88917AVBK2S5",
        reference_id="123456",
        note="Brief description"
    )


asyncio.run(main())

Legacy SDK

While the new SDK has a lot of improvements, we at Square understand that it takes time to upgrade when there are breaking changes. To make the migration easier, the old SDK is published as squareup_legacy so that the two SDKs can be used side-by-side in the same project.

Check out the example for a full demonstration, but the gist is shown below:

from square import Square
from square_legacy.client import Client as LegacySquare


def main():
    client = Square(token=os.environ.get("SQUARE_TOKEN"))
    legacy_client = LegacySquare(access_token=os.environ.get("SQUARE_TOKEN"))

    ...

We recommend migrating to the new SDK using the following steps:

  1. Upgrade the PyPi package to ^42.0.0
  2. Run pip install squareup_legacy
  3. Search and replace all requires and imports from square to square_legacy
  4. Gradually move over to use the new SDK by importing it from the square module

Versioning

By default, the SDK is pinned to the latest version. If you would like to override this version you can specify it like so:

client = Square(
    version="2025-03-19"
)

Automatic Pagination

Paginated requests will return a SyncPager or AsyncPager, which can be used as generators for the underlying object.

from square import Square

client = Square()
response = client.payments.list()
for item in response:
    yield item
# Alternatively, you can paginate page-by-page.
for page in response.iter_pages():
    yield page

File Uploads

Files are uploaded with the File type, which is constructed as a tuple in a variety of formats. You can customize the filename and Content-Type of the individual multipart/form-data part like so:

invoice_pdf = client.invoices.create_invoice_attachment(
    invoice_id="inv:0-ChA4-3sU9GPd-uOC3HgvFjMWEL4N",
    image_file=(
         os.path.basename(pdf_filepath), # The filename to include in the `multipart/form-data` part.
         open(pdf_filepath, "rb"),       # The file stream, read as binary data.
         "application/pdf"               # The Content-Type for this particular file.
    ),
    request={
        "idempotency_key": str(uuid.uuid4()),
        "description": f"Invoice-{pdf_filepath}",
    }
)

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 square.core.api_error import ApiError

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

Webhook Signature Verification

The SDK provides utility methods that allow you to verify webhook signatures and ensure that all webhook events originate from Square. The verify_signature method will verify the signature.

from square.utils.webhooks_helper import verify_signature

is_valid = verify_signature(
    request_body=request_body,
    signature_header=request.headers['x-square-hmacsha256-signature'],
    signature_key="YOUR_SIGNATURE_KEY",
    notification_url="https://example.com/webhook", # The URL where event notifications are sent.
)

Reporting API

The Reporting API lets you query aggregated reporting data. Call reporting.get_metadata first to discover the available cubes, measures, and dimensions, then run a query with reporting.load.

from square import Square

client = Square(token="YOUR_TOKEN")

# Discover what you can query.
metadata = client.reporting.get_metadata()

# Run a query against the discovered schema.
response = client.reporting.load(query={"measures": ["Orders.count"]})

load is asynchronous: while a query is still being computed, the API returns an HTTP 200 whose body is {"error": "Continue wait"} instead of results, and the client is expected to re-send the identical request — with backoff — until the results are ready. The load_and_wait helper owns that polling loop for you and returns the resolved results (never the "Continue wait" sentinel):

from square import Square
from square.utils.reporting_helper import load_and_wait

client = Square(token="YOUR_TOKEN")

response = load_and_wait(client, query={"measures": ["Orders.count"]})

print(response.data)

By default it polls up to 20 times with exponential backoff (2s → 20s). Tune the behavior — and pass a threading.Event to cancel — via the keyword arguments:

import threading

cancel_event = threading.Event()

response = load_and_wait(
    client,
    query={"measures": ["Orders.count"]},
    max_attempts=10,        # default 20
    initial_delay_s=1.0,    # default 2.0
    max_delay_s=20.0,       # default 20.0
    backoff_factor=2.0,     # default 2.0
    cancel_event=cancel_event,
)

For the async client, use load_and_wait_async (cancel it the idiomatic asyncio way — e.g. asyncio.wait_for or Task.cancel):

from square import AsyncSquare
from square.utils.reporting_helper import load_and_wait_async

client = AsyncSquare(token="YOUR_TOKEN")

response = await load_and_wait_async(client, query={"measures": ["Orders.count"]})

Advanced

Retries

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

A request is deemed retriable when any of the following HTTP status codes is returned:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Errors)

Use the max_retries request option to configure this behavior.

from square.core.request_options import RequestOptions

client.payments.create(
    ...,
    request_options=RequestOptions(
        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 square import Square

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

# Override timeout for a specific method
client.payments.create(
    ...,
    request_options=RequestOptions(
        timeout_in_seconds=20
    )
)

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 square import Square

client = Square(
    ...,
    httpx_client=httpx.Client(
        proxies="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!

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

squareup-45.0.1.20260715.tar.gz (829.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

squareup-45.0.1.20260715-py3-none-any.whl (2.3 MB view details)

Uploaded Python 3

File details

Details for the file squareup-45.0.1.20260715.tar.gz.

File metadata

  • Download URL: squareup-45.0.1.20260715.tar.gz
  • Upload date:
  • Size: 829.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.5.1 CPython/3.8.18 Linux/6.17.0-1018-azure

File hashes

Hashes for squareup-45.0.1.20260715.tar.gz
Algorithm Hash digest
SHA256 553dda841f349a53619d5280cc300cc6d57329ce6b0910a377f41d3ae02f6f6e
MD5 15df2014579a5f8af321988c0f8520f2
BLAKE2b-256 308346ff29e5b42c9b5b96193b8758f38ac0b264aa1f0cfc753acb401c7d2691

See more details on using hashes here.

File details

Details for the file squareup-45.0.1.20260715-py3-none-any.whl.

File metadata

  • Download URL: squareup-45.0.1.20260715-py3-none-any.whl
  • Upload date:
  • Size: 2.3 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.5.1 CPython/3.8.18 Linux/6.17.0-1018-azure

File hashes

Hashes for squareup-45.0.1.20260715-py3-none-any.whl
Algorithm Hash digest
SHA256 9d0c771ecce24213416ee15f8cc8d220450e76cb33140fcdc4b4992356bd72ac
MD5 1ba6f4762728db846403ec353aa63df7
BLAKE2b-256 c9dd6aac4aea608aa33689d85c51d01d046a4101ab8a5ac192d3aa5d0112ce46

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page