Skip to content

Five-minute quickstart

This complete example is executed by task docs_test:

"""Five-minute Talea quickstart used by the documentation."""

from typing import Annotated, cast

from talea import MinLength, Spec, ValidationError


class User(Spec):
    id: int
    name: Annotated[str, MinLength(1)]
    active: bool = True


user = User(id=1, name="Ada")
assert user.to_dict() == {"id": 1, "name": "Ada", "active": True}

decoded = User.from_json('{"id":2,"name":"Grace","active":false}')
assert decoded.to_dict() == {"id": 2, "name": "Grace", "active": False}

try:
    User(id=cast(int, "1"), name="Ada")
except ValidationError as error:
    assert error.errors()[0]["code"] == "type"
    assert error.errors()[0]["location"] == ["id"]
else:
    raise AssertionError("strict construction must reject a string identifier")

schema = User.json_schema()
assert schema["$schema"] == "https://json-schema.org/draft/2020-12/schema"

What happened

User(...) is the strict Python path. Talea accepts exact Python values and does not convert a string into an integer. The caught ValidationError exposes a stable type code and the field path id; application code should consume those structured values instead of parsing message text.

User.from_json(...) owns JSON decoding and schema-aware conversion. It can therefore construct standard-library Python values from documented JSON representations without weakening ordinary construction.

to_dict() returns a detached Python mapping and to_json() produces JSON text. json_schema() returns a fresh Draft 2020-12 document.

Next, follow the tutorial. Use the public API reference when you already know the operation you need.