Metadata-Version: 2.5
Name: sendurl
Version: 0.1.0
Summary: Official Python client for the SendURL REST API: short links, QR codes and click analytics.
Project-URL: Homepage, https://sendurl.to
Project-URL: Documentation, https://sendurl.to/docs
Project-URL: API, https://sendurl.to/features/api
Project-URL: Pricing, https://sendurl.to/pricing
Project-URL: Repository, https://github.com/sendurl-to/sendurl-python
Project-URL: Issues, https://github.com/sendurl-to/sendurl-python/issues
Project-URL: Changelog, https://github.com/sendurl-to/sendurl-python/blob/main/CHANGELOG.md
Author: DRG Technologies and Consultancy
License-Expression: MIT
License-File: LICENSE
Keywords: analytics,api,qr codes,sdk,sendurl,short links,url shortener
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.24
Description-Content-Type: text/markdown

# SendURL Python SDK

[SendURL](https://sendurl.to) is a URL shortener with click analytics, QR codes and custom domains. This is the
official Python client for its [REST API](https://sendurl.to/features/api) ([API reference](https://sendurl.to/docs)): create short links
and QR codes, organize them in folders and tags, and read click analytics.

- Sync (`SendURL`) and async (`AsyncSendURL`) clients with the same methods
- Typed responses (`TypedDict`s) and a `py.typed` marker
- Lists you can iterate, with pagination handled for you
- One exception class per kind of error, carrying the API's stable error `code`
- GET requests retried on network errors, 429, 502, 503 and 504, honouring `Retry-After`
- Python 3.9 or later; its only dependency is [`httpx`](https://www.python-httpx.org/)

## Install

```sh
pip install sendurl
```

## Quick start

[Create a free SendURL account](https://console.sendurl.to/signup), then create an API key on the console's [API keys page](https://console.sendurl.to/api-keys), then:

```python
from sendurl import SendURL

client = SendURL(api_key="snu_...")  # or set SENDURL_API_KEY and call SendURL()

link = client.links.create(destination_url="https://example.com/launch", slug="launch")
print(link["shortUrl"])  # https://snu.to/launch
print(link["qrUrl"])  # the URL a QR code of this link should encode

for link in client.links.list(status="active"):
    print(link["slug"], link["totalClicks"])

client.close()
```

You can use the client as a context manager instead, so it closes itself:

```python
with SendURL() as client:
    me = client.account.get()
    print(me["plan"]["name"], me["usage"]["linksUsed"], "/", me["plan"]["linksLimit"])
```

### Async

```python
import asyncio
from sendurl import AsyncSendURL


async def main() -> None:
    async with AsyncSendURL() as client:
        link = await client.links.create(destination_url="https://example.com")
        async for click in client.links.clicks.list(link["id"]):
            print(click["clickedAt"], click["country"])


asyncio.run(main())
```

The async client has the same methods as the sync one. Await every call, and use `async for`
with the `list()` methods.

## Responses

Every method returns the API's JSON as plain Python dicts and lists. The keys are **camelCase,
as they are on the wire** (`link["shortUrl"]`, `link["destinationUrl"]`), so the
[API reference](https://sendurl.to/docs) applies as written. The `TypedDict`s in `sendurl`
(`Link`, `LinkList`, `Click`, `Account`, `Overview`, ...) describe them for your editor and type
checker. They are all `total=False`, so a field the server adds later shows up in the dict
and never breaks your code.

Arguments are snake_case keyword arguments and are mapped to the API's camelCase for you
(`destination_url` becomes `destinationUrl`, `folder_id` becomes `folderId`).

## Reference

The examples below use the sync client; for the async client, add `await` (or `async for`).

### Account

```python
me = client.account.get()  # GET /me
me["org"]["name"], me["plan"]["linksLimit"], me["usage"]["linksUsed"]
me["key"]["scopes"]  # None = every scope
me["folder"]  # the folder a folder-level key is limited to, else None
```

### Links

A link can also send phones to [mobile app targets](https://sendurl.to/features/mobile-targets), [expire](https://sendurl.to/features/link-expiration) or ask for a [password](https://sendurl.to/features/password-protected-links), carry a [styled QR code](https://sendurl.to/features/qr-codes) and a [custom link preview](https://sendurl.to/features/link-previews), and split its visitors in an [A/B test](https://sendurl.to/features/ab-testing).

```python
from datetime import datetime, timezone

link = client.links.create(
    destination_url="https://example.com/spring",  # required
    slug="spring",  # default: a random slug
    title="Spring campaign",
    folder_id="…",  # default: the Default folder (or a folder key's own)
    domain_id="…",  # a live domain (client.domains); can't be changed later
    tag_ids=["…", "…"],
    ios_url="https://apps.apple.com/app/id123",  # where iPhone and iPad visitors go
    android_url="https://play.google.com/store/apps/details?id=x",
    expires_at=datetime(2027, 1, 1, tzinfo=timezone.utc),  # Pro and above
    password="s3cret!",  # Pro and above; never returned to an API key
    qr_style={"fg": "#1a1a2e", "bg": "#ffffff", "dots": "rounded", "corners": "dots"},  # "v": 1 is added
    preview={"title": "Spring sale", "description": "Up to 40% off", "image": "https://…/card.png"},
    ab_test={
        "variants": [
            {"id": "a", "url": "https://example.com/spring", "weight": 50},
            {"id": "b", "url": "https://example.com/spring-b", "weight": 50},
        ]
    },
)

link = client.links.get(link["id"])  # adds totalClicks, qrScans, tags, domain
client.links.delete(link["id"])  # paid plans; on Free, disable it instead
```

`expires_at` takes a timezone-aware `datetime` or an ISO 8601 string with an offset
(`"2027-01-01T00:00:00Z"`). A naive `datetime` raises `ValueError`, because the API needs to
know the time zone.

**Update** changes only the fields you pass. Passing `None` clears a field (it is sent as JSON
`null`); leaving a field out leaves it as it is:

```python
client.links.update(link_id, title="New title")  # only the title changes
client.links.update(link_id, ios_url=None)  # remove the iOS target
client.links.update(link_id, expires_at=None)  # never expire
client.links.update(link_id, active=False)  # disable the link
client.links.update(link_id, destination_url="https://…")  # Pro and above
client.links.update(link_id, ab_test=None)  # end the A/B test without a winner
```

The default of every `update()` argument is `sendurl.NOT_GIVEN`, which means "not passed".

**A/B test winner**: end a running test and make one variant's URL the destination:

```python
client.links.pick_winner(link_id, variant_id="b")  # POST /links/:id/ab-test/winner
```

**List and search**:

```python
for link in client.links.list(
    status=["active", "expired"],  # any of: active, disabled, expired, protected, limit_reached
    q="spring",  # searches slug, destination and title
    sort="clicks_desc",  # created_desc (default), clicks_desc, clicks_asc
    folder_id="…",
    tag_ids=["…"],  # links with any of these tags
):
    ...

page = client.links.list_page(limit=10)  # one page, with summary, usage and pagination
page["summary"]  # {"totalLinks", "activeLinks", "totalClicks"}, or None for very large workspaces
page["usage"]  # {"linksUsed", "linksLimit"}
```

The clicks sorts follow the live click counter, so a link can move between pages while you
page through them; deduplicate by `id` if that matters.

**Stats and clicks**:

```python
client.links.stats(link_id)  # [{"date": "2026-11-01", "count": 12}, ...] all-time, UTC days with clicks

for click in client.links.clicks.list(link_id):  # newest first
    click["clickedAt"], click["country"], click["device"], click["source"]  # "qr" for a QR scan

page = client.links.clicks.list_page(link_id, limit=10)
click = client.links.clicks.get(link_id, click_id)
```

A click never includes the visitor's IP address. On the Free plan `city` is `None` and
`cityLocked` is `True`.

**[CSV export](https://sendurl.to/features/export)** of every link matching the filters, streamed:

```python
with client.links.export(status="active") as csv:  # GET /links/export.csv
    for chunk in csv:  # bytes
        ...

client.links.export_to_file("links.csv", folder_id="…")  # returns the number of bytes written
```

On the async client, `csv = await client.links.export()`, then `async with csv:` and
`async for chunk in csv:`.

### Analytics

[Analytics](https://sendurl.to/features/link-analytics) dates are `datetime.date` objects or `"YYYY-MM-DD"` strings, inclusive, in `tz` (an IANA
name such as `"Europe/Paris"`, default UTC). The range must lie within your plan's analytics
history (otherwise you get `BadRequestError` with code `range_outside_history`). Pass
`folder_id` or `link_id` to narrow the scope; without either an org key reads the whole
workspace.

```python
from datetime import date

overview = client.analytics.overview(from_=date(2026, 11, 1), to=date(2026, 11, 7), tz="Europe/Paris")
overview["kpis"]["clicks"], overview["series"], overview["topLinks"], overview["breakdowns"]["country"]

top = client.analytics.breakdown(
    from_="2026-11-01",
    to="2026-11-07",
    # link, country, device, browser, os, referrer, variant (needs link_id),
    # and on Pro and above city and utm
    dimension="country",
    order="desc",
    limit=10,
)
client.analytics.breakdown(from_="2026-11-01", to="2026-11-07", dimension="utm", by="campaign")
client.analytics.breakdown(from_="2026-11-01", to="2026-11-07", dimension="referrer", category="social")
client.analytics.breakdown(from_="2026-11-01", to="2026-11-07", dimension="city", count_only=True)

for click in client.analytics.clicks(from_="2026-11-01", to="2026-11-07", link_id=link_id):
    click["clickedAt"], click["referrer"]["label"]

page = client.analytics.clicks_page(from_="2026-11-01", to="2026-11-07")  # pagination.total on page 1
```

The `utm` breakdown reads the [UTM parameters](https://sendurl.to/features/utm) in each link's destination URL; the free [UTM builder](https://sendurl.to/tools/utm-builder) writes them for you.

`from_` has a trailing underscore because `from` is a Python keyword. Send analytics requests
one at a time: when analytics are busy the API answers 503 `analytics_unavailable`, which the
client retries for you after `Retry-After` seconds.

### Folders

```python
for folder in client.folders.list():  # Default first; org-level keys only
    folder["name"], folder["linksCount"]

page = client.folders.list_page()
folder = client.folders.create(name="Marketing")
```

### Tags

```python
for tag in client.tags.list():
    tag["id"], tag["name"], tag["color"], tag["linksCount"]

page = client.tags.list_page()  # adds usage: {"tagsUsed", "tagsLimit"}
```

[Tags](https://sendurl.to/features/folders-and-tags) are created and edited in the console; use their ids in `tag_ids`.

### Domains

Read only for API keys: [custom domains](https://sendurl.to/features/custom-domains) are added in the console.

```python
for domain in client.domains.list():
    domain["hostname"], domain["type"], domain["status"]  # subdomain | custom; pending | active | failed

page = client.domains.list_page()
domain = client.domains.get(domain_id)
```

## Pagination

Every list endpoint returns at most 10 items per page. Each resource gives you two ways to
read it:

- `list(...)` returns an iterator over **every** item. It fetches the next page (following
  `pagination.nextCursor`) only when you reach the end of the current one, and nothing at all
  until you start iterating. Its `limit` argument is the page size (1-10), not a total.
- `list_page(..., cursor=None)` returns one page as the API sends it (the items, `pagination`,
  and extras such as `summary` and `usage`). Pass `page["pagination"]["nextCursor"]` as
  `cursor` to read the next page.

```python
page = client.links.list_page()
while True:
    for link in page["links"]:
        ...
    if not page["pagination"]["hasMore"]:
        break
    page = client.links.list_page(cursor=page["pagination"]["nextCursor"])
```

## Errors

Every API error raises a subclass of `sendurl.SendURLError`:

| Exception | When |
|---|---|
| `BadRequestError` | 400: `validation_error` (see `issues`), `range_outside_history`, ... |
| `AuthenticationError` | 401: missing, invalid, revoked or expired API key |
| `PermissionDeniedError` | 403: `insufficient_scope`, `plan_upgrade_required` (a [paid plan](https://sendurl.to/pricing) feature), `link_limit_reached`, ... |
| `NotFoundError` | 404: `link_not_found`, `click_not_found`, `domain_not_found`, ... |
| `ConflictError` | 409: `slug_taken`, `project_name_taken`, `domain_not_active` |
| `UnprocessableEntityError` | 422: `unsafe_destination`, `too_many_urls` |
| `RateLimitError` | 429 |
| `InternalServerError` | 5xx |
| `ServiceUnavailableError` | 503 (a subclass of `InternalServerError`): `analytics_unavailable`, `export_unavailable`, `domains_unavailable` |
| `APIConnectionError` | no response: DNS failure, refused or reset connection |
| `APITimeoutError` | the request timed out (a subclass of `APIConnectionError`) |

Each error carries:

- `status_code`: the HTTP status (`None` for connection errors)
- `code`: the API's stable error code. **Branch on `code`, never on `message`.**
- `message`: a sentence for a person
- `issues`: the field issues of a `validation_error`
- `body`: the whole JSON error body, with extra fields such as `limit`, `current`, `feature`
  and `requiredPlan`
- `retry_after`: seconds to wait, when the API said so

```python
from sendurl import ConflictError, PermissionDeniedError

try:
    client.links.create(destination_url="https://example.com", slug="launch")
except ConflictError as e:
    if e.code == "slug_taken":
        ...
except PermissionDeniedError as e:
    if e.code == "link_limit_reached":
        print(f"{e.body['current']} of {e.body['limit']} links used")
    elif e.code == "plan_upgrade_required":
        print("Needs the", e.body["requiredPlan"], "plan")
```

## Retries and timeouts

GET requests are retried up to `max_retries` times (default 2) on connection errors and
timeouts, and on 429, 502, 503 and 504 responses. The client waits for `Retry-After` seconds
when the API sends it (at most 60), otherwise it backs off exponentially with jitter
(about 0.5 s, then 1 s, then 2 s, ...).

**POST, PATCH and DELETE are never retried**: the API has no idempotency key, so retrying a
create could make the same link twice. If one of them fails with a connection error, check
whether it went through (for example with `links.list(q=slug)`) before trying again.

Each request times out after `timeout` seconds (default 30).

## Configuration

```python
import httpx
from sendurl import SendURL

client = SendURL(
    api_key="snu_...",  # default: the SENDURL_API_KEY environment variable
    base_url="https://api.sendurl.to/api/v1",  # default: SENDURL_BASE_URL, else production
    timeout=30.0,  # seconds, or an httpx.Timeout
    max_retries=2,  # retries for GET requests; 0 turns them off
    http_client=httpx.Client(proxy="http://proxy:8080"),  # optional: your own httpx client
)
```

`AsyncSendURL` takes the same arguments, with an `httpx.AsyncClient` as `http_client`. A client
you pass in is yours to close: `close()` / `aclose()` close only the one the SDK created.

`base_url` must be `https://`; plain `http://` is accepted only for `localhost`, `127.0.0.1`
and `::1` (a local platform), so the key never crosses a network in clear text. Redirects are
never followed, even by an `http_client` created with `follow_redirects=True`: a 3xx answer
raises `SendURLError` (usually a wrong `base_url`).

The API key is never included in `repr(client)` or in any error message. Keep it on the server:
a key shipped in browser or mobile code can be read by anyone.

### Scopes

An API key can be limited to some scopes. Each method needs one:

| Scope | Methods |
|---|---|
| `links:read` | `links.list`, `list_page`, `get`, `stats`, `export`, `links.clicks.*` |
| `links:write` | `links.create`, `update`, `pick_winner` |
| `links:delete` | `links.delete` |
| `analytics:read` | `analytics.*` |
| `workspace:read` | `account.get`, `folders.list`, `tags.list`, `domains.*` |
| `folders:write` | `folders.create` |

A key without the scope gets `PermissionDeniedError` with code `insufficient_scope`.

## Local development

To point the client at a SendURL platform running on your machine:

```python
client = SendURL(api_key="snu_...", base_url="http://localhost:1911/api/v1")
```

To work on this library:

```sh
uv sync                      # create .venv with the dev tools
uv run ruff check .
uv run ruff format --check .
uv run mypy
uv run pytest
uv build
```

The integration tests in `tests/test_integration.py` run against a real platform and are
skipped unless both variables are set:

```sh
SENDURL_BASE_URL=http://localhost:1911/api/v1 SENDURL_API_KEY=snu_... uv run pytest tests/test_integration.py -v
```

They create one link and delete it at the end (on the Free plan, where deleting isn't
allowed, they disable it instead).

## Releasing

For maintainers. Releases are published from GitHub, never from a laptop:

1. Bump the version in **both** `pyproject.toml` (`version`) and `src/sendurl/_version.py`
   (`__version__`, which the `User-Agent` carries) to the same
   [PEP 440](https://peps.python.org/pep-0440/) version, such as `0.2.0` or `0.2.0rc1`, and add
   its section to `CHANGELOG.md` (`## [x.y.z] - YYYY-MM-DD`). A unit test and the release build
   both fail when the two differ, so a mismatched version is never published.
2. Merge to `main`.
3. The Release workflow (`.github/workflows/release.yml`) runs on any `pyproject.toml` change on
   `main`. If that exact version isn't on PyPI yet, it runs ruff, mypy and the tests, builds the
   sdist and wheel, publishes them to PyPI with
   [Trusted Publishing](https://docs.pypi.org/trusted-publishers/) (no PyPI token exists), and
   creates the `vx.y.z` tag on that commit with a GitHub Release whose notes are the version's
   CHANGELOG section. An `a`, `b`, `rc` or `dev` version is marked as a prerelease on GitHub
   (pip installs it only when asked for it explicitly). A version already on PyPI is not
   published again, so other `pyproject.toml` edits publish nothing.

It can also be started by hand (Actions → Release → Run workflow, on `main`). PyPI records no
commit for a release, so when a version is already on PyPI but has no GitHub Release yet (a
failed run), the run creates it only when you give `target_sha`: the full SHA of the commit on
`main` it was published from. Without it, the run only warns.

**The very first release (0.1.0)** needs two one-time steps: register a *pending* trusted
publisher on PyPI (PyPI project name `sendurl`, owner `sendurl-to`, repository `sendurl-python`,
workflow `release.yml`, environment `pypi`), then run the workflow once by hand (Actions → Release → Run workflow, on
`main`). The commit that added the workflow doesn't change `pyproject.toml`, so pushing it starts
no run.

Releases run from `main` only. PyPI trusts exactly this repository, the workflow file
`release.yml` and the GitHub environment `pypi`, whose deployment branch policy allows only
`main`. Renaming the workflow file breaks publishing until the trusted publisher is updated.

## Links

- [SendURL website](https://sendurl.to): the URL shortener this SDK talks to
- [API reference](https://sendurl.to/docs): every endpoint, field and error code
- [Plans and pricing](https://sendurl.to/pricing): limits and the features each plan includes
- [Free URL shortener](https://sendurl.to/free-url-shortener): shorten a link without an account
- [Free link tools](https://sendurl.to/tools): a [UTM builder](https://sendurl.to/tools/utm-builder), a [QR code generator](https://sendurl.to/tools/qr-code-generator) and more
- [Guides](https://sendurl.to/guides) and the [SendURL blog](https://sendurl.to/blog)
- [SendURL console](https://console.sendurl.to): your links, analytics and API keys

## License

MIT, see [LICENSE](LICENSE).
