Skip to main content

legalize

python-ci PyPI Python versions License: MIT

Official Python client for the Legalize API — legal texts as structured, versioned data.

pip install legalize
from legalize import Legalize

client = Legalize(api_key="leg_...")

for law in client.laws.iter(country="es", law_type="ley_organica"):
    print(law.id, law.title)

Why this SDK

  • Typed end-to-end. Pydantic v2 models generated from the canonical OpenAPI spec. py.typed ships in the wheel. mypy --strict clean.
  • Sync by default, async when you need it. Legalize and AsyncLegalize expose the same resource API and error types — swap one for the other without rewriting your call sites.
  • Retries with backoff built in. Honors Retry-After, handles 429/5xx, exponential delay with jitter, all configurable.
  • Webhook verification is a one-liner. Constant-time HMAC compare, 5-minute anti-replay window, clock-skew tolerant.
  • No magic, no frameworks. One client, one method per endpoint.

Quick tour

# One page
page = client.laws.list(country="es", page=1, per_page=50)
print(page.total, len(page.items))

# Auto-paginated iterator (fetches pages as needed)
for law in client.laws.iter(country="es", status="vigente"):
    ...

# Full-text search
results = client.laws.search(country="es", q="protección de datos")

# ...page by page
page2 = client.laws.search(country="es", q="protección de datos", page=2)

# ...or every match, paginated for you
for law in client.laws.search_iter(country="es", q="protección de datos"):
    ...

Time-travel

Every law has a git-tracked history. Retrieve it at any past revision:

commits = client.laws.commits(country="es", law_id="ley_organica_3_2018")
past = client.laws.at_commit(
    country="es",
    law_id="ley_organica_3_2018",
    sha=commits.items[-1].sha,
)
print(past.content)  # Markdown at that revision

Or skip the SHA lookup entirely and ask by date:

at = client.laws.at_date(country="es", law_id="ley_organica_3_2018", date="2019-05-13")
print(at.sha, at.version_date)  # which version answered, so you can cite it

Resolution uses the source's publication date where known, or the version's explicit cutoff when no publication date is recorded. Selection does not establish entry into force. Read text_state and warning: a current snapshot does not establish historical wording.

XML (and other raw formats)

The typed methods always return JSON-parsed models. When your app speaks XML, use request_raw to fetch any endpoint in another wire format via content negotiation — it sets Accept and hands you the body untouched:

res = client.request_raw("GET", "/api/v1/es/laws/BOE-A-1978-31229")
res.content_type  # "application/xml; charset=utf-8"
xml_text = res.text  # the raw XML string
root = res.xml()  # parsed into an ElementTree element

# format="json" or any explicit media type works the same way:
data = client.request_raw("GET", "/api/v1/countries", format="json").json()

request_raw defaults to format="xml". Errors raise the same typed exceptions as the JSON methods (the error body is in the negotiated format). See the Response formats docs.

Async

import asyncio
from legalize import AsyncLegalize


async def main():
    async with AsyncLegalize(api_key="leg_...") as client:
        page = await client.laws.list(country="es")
        async for law in client.laws.iter(country="fr"):
            print(law.id)


asyncio.run(main())

Webhooks

Verify a signed delivery in one call:

from legalize import Webhook, WebhookVerificationError

try:
    event = Webhook.verify(
        payload=request.body,  # raw bytes
        sig_header=request.headers["X-Legalize-Signature"],
        timestamp=request.headers["X-Legalize-Timestamp"],
        secret=os.environ["LEGALIZE_WHSEC"],
    )
except WebhookVerificationError:
    return Response(status_code=400)

if event.type == "law.updated":
    ...

Working Flask and FastAPI receivers in examples/.

Configuration

Set the environment and just instantiate:

export LEGALIZE_API_KEY=leg_live_...
# Optional:
export LEGALIZE_BASE_URL=https://legalize.dev
export LEGALIZE_API_VERSION=v1
from legalize import Legalize

client = Legalize()  # picks everything up from the environment

Explicit

from legalize import Legalize, RetryPolicy

client = Legalize(
    api_key="leg_...",
    base_url="https://legalize.dev",
    api_version="v1",  # negotiated via Legalize-API-Version
    timeout=30.0,
    retry=RetryPolicy(max_retries=5, initial_delay=0.5, max_delay=10.0),
    default_headers={"X-Correlation-Id": "..."},
)

Precedence: explicit argument > environment variable > built-in default. The full cross-SDK contract is documented in ENVIRONMENT.md.

Read rate-limit headers from the last response:

client.countries.list()
resp = client.last_response
print(resp.headers.get("X-RateLimit-Remaining"))

Errors

All errors inherit from LegalizeError. Catch the specific one you care about and let the rest bubble:

from legalize import (
    AuthenticationError,  # 401 — bad/missing key
    ForbiddenError,  # 403
    NotFoundError,  # 404
    InvalidRequestError,  # 400
    ValidationError,  # 422
    RateLimitError,  # 429 — retried automatically by default
    ServerError,  # 5xx
    APIConnectionError,  # network failure
    APITimeoutError,  # timeout
    WebhookVerificationError,
)

Every APIError exposes .status_code, .code, .body, and .response for debugging.

Compatibility

  • Python 3.10, 3.11, 3.12, 3.13
  • Linux, macOS, Windows
  • httpx ≥ 0.27, pydantic ≥ 2.6

License

MIT

Metadata

Release files for legalize 0.4.0

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

Source distribution (sdist)

Source distribution for legalize 0.4.0
File Size Uploaded Provenance Actions
legalize-0.4.0.tar.gz 30.0 kB With provenance Details for legalize-0.4.0.tar.gz

Built distribution (wheel)

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

Total release size: 63.7 kB

Release files / legalize-0.4.0.tar.gz

Download URL legalize-0.4.0.tar.gz
Size 30.0 kB
Tags Source
SHA-256 checksum
How to use checksums
71936e254222c0967e9b69bc9054b27603ddabf2f5b1d85b23e87f44987779b7
BLAKE2b-256 checksum
How to use checksums
68db643100e7a49a80d4971cd95d6c15857ab9c32de28f58f0813cb4e9c05182
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Release files / legalize-0.4.0-py3-none-any.whl

Download URL legalize-0.4.0-py3-none-any.whl
Size 33.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ac01786a8631bf52f55edbf92bd0b611d8e73d5254367e3e33f80d2096ec900a
BLAKE2b-256 checksum
How to use checksums
fac8eb95a25cc292bd5c91087e43b428dd305ae99f1a6bd909bbf772c795cf44
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Security for legalize 0.4.0

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for legalize-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

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