Metadata-Version: 2.4
Name: hawkapi-pagination
Version: 0.1.0
Summary: Pagination helpers for HawkAPI — cursor + offset, Page[T] response model, SQLAlchemy integration
Project-URL: Homepage, https://pypi.org/project/hawkapi-pagination/
Project-URL: Repository, https://github.com/Hawk-API/hawkapi-pagination
Project-URL: Issues, https://github.com/Hawk-API/hawkapi-pagination/issues
Author-email: HawkAPI Contributors <hawkapi@users.noreply.github.com>
License: MIT License
        
        Copyright (c) 2026 HawkAPI Contributors
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: cursor,hawkapi,offset,pagination,sqlalchemy
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: hawkapi>=0.1.7
Requires-Dist: msgspec>=0.19
Provides-Extra: dev
Requires-Dist: aiosqlite>=0.20; extra == 'dev'
Requires-Dist: hawkapi-sqlalchemy>=0.2.0; extra == 'dev'
Requires-Dist: pyright>=1.1; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.8; extra == 'dev'
Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'dev'
Provides-Extra: sqlalchemy
Requires-Dist: hawkapi-sqlalchemy>=0.2.0; extra == 'sqlalchemy'
Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'sqlalchemy'
Description-Content-Type: text/markdown

# hawkapi-pagination

Pagination helpers for [HawkAPI](https://github.com/Hawk-API/HawkAPI). Offset and cursor strategies. `Page[T]` / `CursorPage[T]` response envelopes. SQLAlchemy integration. In-memory iterable pagination.

## Install

```bash
pip install hawkapi-pagination
pip install 'hawkapi-pagination[sqlalchemy]'   # adds SQLAlchemy + hawkapi-sqlalchemy helpers
```

## Offset pagination

```python
from hawkapi import Depends, HawkAPI
from hawkapi_sqlalchemy import get_session
from hawkapi_pagination import Page, OffsetParams, pagination_params, paginate_query
from sqlalchemy import select


@app.get("/items")
async def list_items(
    params: OffsetParams = Depends(pagination_params),
    session = Depends(get_session),
) -> Page[Item]:
    return await paginate_query(session, select(Item), params)
```

The route accepts `?page=N&size=M`. Defaults: `page=1`, `size=50`, `max_size=200`. Out-of-range values are clamped (`size > max_size` → `max_size`) or rejected (`page < 1` raises `400`).

`Page[T]` shape:

```json
{ "items": [...], "total": 137, "page": 1, "size": 50, "pages": 3 }
```

### Skipping the COUNT

For large tables where `SELECT COUNT(*)` is expensive:

```python
page = await paginate_query(session, stmt, params, include_total=False)
# page.total == -1, page.pages == -1
```

Clients can detect "more pages" by comparing `len(items)` to `size`.

## Cursor pagination

Cursor pagination is the right choice for large tables that change under you (offset pages skip/duplicate rows when items are inserted/deleted between requests). The cursor is an HMAC-signed opaque token bound to:
- the **endpoint path** (replay across routes rejected),
- a **TTL** (default 1 hour),
- a **direction** (`asc` / `desc`).

```python
from hawkapi_pagination import CursorPage, CursorParams, cursor_params, paginate_cursor


@app.get("/items")
async def list_items(
    params: CursorParams = Depends(cursor_params),
    session = Depends(get_session),
) -> CursorPage[Item]:
    return await paginate_cursor(
        session,
        select(Item),
        order_by=Item.id,         # MUST be unique + sortable (PK is the usual choice)
        params=params,
        cursor_secret="stable secret, ≥32 chars",
        endpoint="/items",
        direction="asc",
    )
```

`CursorPage[T]` shape:

```json
{ "items": [...], "next_cursor": "eyJrI...", "prev_cursor": "" }
```

When `next_cursor` is `""`, there are no more pages. Send the cursor back as `?cursor=...` for the next call.

## In-memory iterables

```python
from hawkapi_pagination import paginate_iterable


page = await paginate_iterable(some_list, params)
# Works with sync iterables AND async generators.
```

## Security notes

- **Cursor signing** — HMAC-SHA256 over the JSON payload + `hmac.compare_digest` for verification.
- **Endpoint binding** — a cursor minted for `/api/items` cannot be used at `/api/users`. Always pass an `endpoint` string that is stable across requests for the same route.
- **TTL** — default 1 hour. Override per route via `ttl=` to `paginate_cursor`.
- **`max_size` cap** — every params class enforces it; clients cannot ask for an unbounded page. Default 200.
- **Negative-int guard** — `page < 1` and `size < 1` raise `ValueError` (which HawkAPI surfaces as 400).

## Development

```bash
git clone https://github.com/Hawk-API/hawkapi-pagination.git
cd hawkapi-pagination
uv sync --extra dev
uv run pytest -q
uv run ruff check . && uv run ruff format --check .
uv run pyright src/
```

## License

MIT.
