API Reference
Core Decorators & Execution
monk.decorators.monk(obj=None, *, defer=None, **dataclass_kwargs)
The primary decorator for iron-monk.
Transforms a class into a validated, guarded dataclass, OR validates function arguments and return values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
The class or function to decorate. |
None
|
defer
|
bool | None
|
Whether to defer validation until |
None
|
**dataclass_kwargs
|
Any
|
Additional keyword arguments passed to dataclasses.dataclass when decorating a class. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The wrapped class or function. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the decorated object is neither a class nor a function. |
monk.operations.validate(instance)
Validates a Monk dataclass instance.
Executes all field-level constraints. If all field-level constraints pass, it then executes
the model-level __monk_validate__ hook if present. Returns the instance so it can be used inline or reassigned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
T
|
The instantiated Monk dataclass to validate. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The validated dataclass instance, which is now fully unlocked for attribute access. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the provided instance is not a valid Monk dataclass, or if an async cross-field hook is used. |
ValidationError
|
If the instance fails validation. |
monk.operations.validate_dict(data, schema, *, partial=False, drop_extra_keys=False)
Validates a raw dictionary against a TypedDict or Dataclass schema without instantiating an object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
The raw dictionary payload to validate. |
required |
schema
|
type
|
The TypedDict or Dataclass schema containing the validation rules. |
required |
partial
|
bool
|
If True, ignores keys that are missing from the payload (useful for PATCH requests). Defaults to False. |
False
|
drop_extra_keys
|
bool
|
If True, strips any keys not explicitly defined in the schema. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The validated (and optionally sanitized) dictionary. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the dictionary fails any validation constraints or contains unrecognized keys (when drop_extra_keys is False). |
monk.operations.validate_stream(stream, *constraints)
Lazily validates an iterable/generator on the fly without consuming it entirely.
Yields items one by one, raising a ValidationError instantly if an item fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
Iterable[Any]
|
The iterable or generator to validate. |
required |
*constraints
|
Any
|
A variable number of constraint instances or classes to apply to each item. |
()
|
Yields:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The original item from the stream, assuming it passed validation. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If any individual item fails validation. |
monk.operations.validate_async_stream(stream, *constraints)
async
Lazily validates an async iterable/generator on the fly without consuming it entirely.
Yields items one by one, raising a ValidationError instantly if an item fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
AsyncIterable[Any]
|
The asynchronous iterable or generator to validate. |
required |
*constraints
|
Any
|
A variable number of constraint instances or classes to apply to each item. |
()
|
Yields:
| Name | Type | Description |
|---|---|---|
Any |
AsyncIterator[Any]
|
The original item from the async stream, assuming it passed validation. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If any individual item fails validation. |
The Constraint Toolkit
monk.constraints
AllOf
Validates that a value satisfies all of the given constraints.
AnyOf
Validates that a value satisfies at least one of the given constraints.
Base64
Validates a Base64 encoded string structurally.
CSV
Validates a delimited string and applies constraints to each extracted element.
Contains
Validates that a collection or string contains a specific item/substring.
ContainsKeys
Validates that a dictionary contains all the specified keys.
Cron
Validates a cron expression structurally (supports standard 5-field and AWS 6-field formats).
DictOf
Validates arbitrary dictionaries by applying constraints to their keys and/or values.
Each
Validates that every element in an iterable satisfies all the given constraints.
Email
Validates an email address using a standard structural regex.
ExactLen
Validates that a sized collection or string is exactly a specific length.
Future
Validates that a datetime or date is in the future.
HexColor
Validates a hexadecimal color string (e.g., #FFF, #123456).
IPAddress
Validates that a value is a valid IPv4 or IPv6 address
Interval
Numeric or Comparable Interval bounds
IsDir
Validates that a string or Path object points to an existing directory.
IsFile
Validates that a string or Path object points to an existing file.
IsISO8601
Validates that a string is a valid ISO 8601 date or datetime.
JSON
Validates that a string can be safely parsed as JSON.
JWT
Validates a JSON Web Token (JWT) structurally (Header.Payload.Signature).
LatLong
Validates a tuple or list of exactly two floats: (latitude, longitude).
MacAddress
Validates a standard MAC address (e.g., 00:1A:2B:3C:4D:5E).
Match
Validates that a string matches a specific Regular Expression.
Nested
Validates a nested dictionary against a TypedDict or Dataclass schema.
Not
Inverts the logic of another constraint.
NotNull
A marker constraint to explicitly forbid None values.
Nullable
A marker constraint to explicitly allow None values.
OneOf
Validates that a value is an exact member of a predefined set of choices.
Past
Validates that a datetime or date is in the past.
Port
Validates a standard network port number (1-65535).
Predicate
Validates that a value satisfies a given boolean-returning function.
SemVer
Validates standard Semantic Versioning.
Slug
Validates a URL-safe slug (lowercase alphanumeric and hyphens).
Subset
Validates that all elements in a collection are within a predefined set of choices.
Trimmed
Validates that a string has no leading or trailing whitespace.
URL
Validates that a string is a properly formatted URL
UUID
Validates that a value is a valid UUID string or object
Unique
Validates that all elements in a collection are unique.
Exceptions
monk.exceptions
UnvalidatedAccessError
Bases: Exception
Raised when attempting to access an attribute on a Monk object before validate() has been successfully called.
ValidationError
Bases: Exception
flatten()
Returns a flat list of formatted error strings.
to_rfc7807(status=400, title='Validation Error', type_uri='about:blank', detail="The provided data is invalid. See 'errors' for specific details.", instance=None)
Formats the errors into an RFC 7807 compliant dictionary for HTTP APIs.