Metadata-Version: 2.5
Name: recuut
Version: 0.23.0
Summary: Typed merchant integrations for the Recuut Merchant API
Project-URL: Homepage, https://recuut.com
Project-URL: Documentation, https://docs.recuut.com/sdks/python
Project-URL: Changelog, https://docs.recuut.com/sdks/python/changelog
Author: Recuut
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: <3.15,>=3.11
Requires-Dist: datamodel-code-generator==0.81.0
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic-core<3,>=2.27
Requires-Dist: pydantic<3,>=2.10
Requires-Dist: python-dateutil<3,>=2.9
Requires-Dist: typing-extensions<5,>=4.12
Provides-Extra: django
Requires-Dist: asgiref<4,>=3.8; extra == 'django'
Requires-Dist: django<7,>=5.2; extra == 'django'
Requires-Dist: sqlparse<0.7,>=0.6; extra == 'django'
Provides-Extra: fastapi
Requires-Dist: anyio<5,>=4; extra == 'fastapi'
Requires-Dist: fastapi<1,>=0.115; extra == 'fastapi'
Requires-Dist: starlette<2,>=0.46; extra == 'fastapi'
Description-Content-Type: text/markdown

# recuut Python SDK

Typed Merchant API client and optional FastAPI and Django integrations. Supports
Python 3.11 through 3.14. The SDK is Alpha; 0.23.0 is an upcoming release. See the
[changelog](https://docs.recuut.com/sdks/python/changelog/) before upgrading.

```bash
pip install "recuut>=0.23.0,<1"
export RECUUT_API_KEY="recuut_test_..."
```

The examples require that SDK version. Until publication, use a supplied candidate
wheel. `RECUUT_API_URL` defaults to `https://api.recuut.com`; set it for a supplied
local or staging API. The merchant key selects the account and Test or Live
environment. Keep it on your server.

## Python client

```python
from recuut import Recuut
from recuut.merchant_api import TransactionFilter, TransactionStatus

with Recuut() as client:
    for transaction in client.transactions.list(
        max=100,
        page_size=50,
        filter=TransactionFilter(status=TransactionStatus.SUCCEEDED),
    ):
        print(transaction.id, transaction.status)

    for resource in client.resources.list(max=100, page_size=25):
        print(resource.id, resource.name)
```

Use `AsyncRecuut` for async calls. Reuse and close clients with their context
managers. The raw client makes explicit API calls without automatic settlement
waiting or delivery policy. See the [client guide](https://docs.recuut.com/sdks/python/client/)
for payment requests, transport ownership, errors, pagination, and receipt checks.

Documented API failures raise generated errors from `recuut.merchant_api`.
`RecuutUnexpectedResponseError` means a response is outside the generated contract;
`RecuutTransportError` means a network operation failed. A lost commit response
does not prove payment failed. Follow [Errors and retries](https://docs.recuut.com/guides/operate/errors/).

## Pull typed contracts

Create a resource and publish a revision using [product setup](https://docs.recuut.com/guides/setup/).
Then configure the generator in your application's `pyproject.toml`:

```toml
[tool.recuut]
contracts-output-dir = "recuut_contracts"
```

```bash
recuut pull-contracts -v
```

Use the import names printed by the command. Commit the generated files and pull
fresh contracts after an SDK upgrade. [Pull contracts](https://docs.recuut.com/guides/pull-contracts/)
explains generation, drift checks, and compatibility.

## FastAPI

Install `recuut[fastapi]`. Declare the generated payment parameter. This example
uses matching output fields, so it needs no output extractor. FastAPI's
`response_model` excludes the measurement from the public response.

```python
from fastapi import FastAPI
from pydantic import BaseModel
from recuut.fastapi import recuut
from recuut_contracts import TextGenerationV1

app = FastAPI()


class GenerateRequest(BaseModel):
    prompt: str


class GenerateResponse(BaseModel):
    text: str


class GenerateResult(GenerateResponse):
    output_tokens: int


def measure_input_tokens(payload: GenerateRequest) -> int:
    return len(payload.prompt.split())


@app.post("/generate", response_model=GenerateResponse)
@recuut(
    TextGenerationV1,
    inputs=TextGenerationV1.input_extractors(input_tokens=measure_input_tokens),
)
def generate(payload: GenerateRequest, payment: TextGenerationV1.Payment) -> GenerateResult:
    text = payload.prompt.upper()
    return GenerateResult(text=text, output_tokens=len(text.split()))
```

Replace word counts with measurements in the revision's units before billing.
The [FastAPI guide](https://docs.recuut.com/guides/fastapi/) covers setup,
validation order, extractors, private measurements, and testing.

## Django REST framework

Install `recuut[django]` and `djangorestframework`. Add the decorator to an existing
endpoint while keeping its arguments, serializer validation, and response.

```python
from recuut.django import recuut
from recuut_contracts import TextGenerationV1
from rest_framework import serializers
from rest_framework.exceptions import ParseError
from rest_framework.generics import GenericAPIView
from rest_framework.request import Request
from rest_framework.response import Response


class GenerateSerializer(serializers.Serializer):
    prompt = serializers.CharField(max_length=10_000)


def measure_inputs(request: Request) -> TextGenerationV1.Inputs:
    data = request.data
    if not isinstance(data, dict) or not isinstance(data.get("prompt"), str):
        raise ParseError("Expected a JSON object with a string prompt.")
    return TextGenerationV1.Inputs(input_tokens=len(data["prompt"].split()))


class GenerateView(GenericAPIView):
    serializer_class = GenerateSerializer

    @recuut(
        TextGenerationV1,
        inputs=measure_inputs,
        outputs=TextGenerationV1.output_extractors(
            output_tokens=lambda data: data["usage"]["output_tokens"],
        ),
    )
    def post(self, request: Request) -> Response:
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        text = serializer.validated_data["prompt"].upper()
        return Response({"text": text, "usage": {"output_tokens": len(text.split())}})


generate = GenerateView.as_view()
```

Input extractors read existing handler arguments before in-handler validation.
Use explicit access if pricing depends on local validated values. The
[Django guide](https://docs.recuut.com/guides/django/) explains that ordering,
inherited actions, function views, native Django, and CSRF setup.

## Payment behavior

Decorators default to late payment, an 10-second settlement wait, and a pending error.
They validate receipt agreement before releasing paid success. A timeout does
not cancel settlement. Save responses in your application if users need to
fetch them later. Streaming is unsupported.

Configure lifecycle and pending behavior in code. `RecuutResult` is optional for
output measurements absent from the public response. Read [Python payment
behavior](https://docs.recuut.com/sdks/python/) for the shared configuration,
`PaymentCommit`, and lifecycle hooks. [Transactions and recovery](https://docs.recuut.com/guides/operate/transactions/)
explains how to save and return results later.
