Skip to content

Schemas and validation

The validation system describes the data your application accepts through Schema classes. Every field declares a Python type and can add constraints and business rules. Validation converts compatible input into a typed instance or raises ValidationException with structured errors by field.

Schemas are reusable data contracts: they are not exclusive to controllers and do not depend on Request. Orionis integrates validation into HTTP actions, MCP tools, and Realtime remote methods. You can also explicitly validate WebSocket messages, imported records, or service and task data. Each entry point determines its data source and how errors are presented.

In an HTTP action, declare a parameter with your schema’s type. The container reads the request body, awaits asynchronous validation and injects the validated instance before invoking the method. Receive typed data directly instead of reading and validating it through Request. If you also need headers, cookies or the query string, you can receive both parameters.

In app/http/schemas/userschema.py, declare the accepted body:

from orionis.schemas import Schema
from orionis.schemas.constraints import Email, GreaterThanOrEqual, MinLength
from orionis.schemas.fields import Field
class UserSchema(Schema):
name: Field[str, MinLength(2)]
email: Field[str, Email()]
age: Field[int, GreaterThanOrEqual(18)]
newsletter: bool = False

In app/http/controllers/preview_user_controller.py, receive the schema through its type annotation:

from app.http.schemas.userschema import UserSchema
from orionis.http.base import BaseController
class PreviewUserController(BaseController):
async def __call__(self, payload: UserSchema) -> UserSchema:
return payload

Register the action in your configured API routes file, usually routes/api.py:

from app.http.controllers.preview_user_controller import PreviewUserController
from orionis.support.facades import Route
Route.post("/users/preview", PreviewUserController)

Send a POST /users/preview with Content-Type: application/json and this body:

{"name": "Ada", "email": "ada@example.com", "age": 36}

The container injects payload as a UserSchema; omitted newsletter defaults to False. The action returns the schema and Orionis serializes it as JSON with status 200. This example returns a preview; it does not save a user. An invalid email or an age under 18 prevents the action from running and produces the route’s validation response.

You do not need to call the validator in this action. The parameter annotation activates input validation; returning a Schema instance activates output validation before serialization. Its types, constraints, and rules are checked, including child schemas. A return annotation alone does not convert a dictionary into a schema. See input and output schemas in controllers for the complete behavior.

During injection, the container uses the validator’s single asynchronous entry point: await Validator.validate(data, UserSchema). Validator aliases the Schema utility in orionis.schemas.validator, separate from the declaration base imported from orionis.schemas. Type conversion runs directly; checks that require I/O can await their operations without blocking the request. An asynchronous validator does not mean all operations run in parallel.

The process runs in this order:

  1. Optional coercion. Since 1.4.0, Coerce() prepares marked values using their declared type, without changing the original payload.
  2. Types and structural constraints. msgspec converts data into the declared structure and checks types, required fields and constraints such as MinLength.
  3. Rules. Orionis awaits validation by each Rule instance, such as Email(), on converted values. All implement async def enforce(...), including simple checks and checks awaiting I/O. Rules can inspect other fields and use external services. A synchronous enforce is rejected when its class is defined.
ComponentResponsibility
SchemaDeclares fields on top of msgspec.Struct and exposes toDict().
SchemaMetaProcesses annotations when the class is created and prepares its metadata and rule plans. You do not need to use it directly.
Annotated / FieldAttaches constraints, rules and metadata to a type without changing the field type. Field aliases typing.Annotated.
Coerce()Enables conversion before type, constraint, and rule checks for the marked field and its descendant values; dictionary keys remain strict.
Metadata compilerTransforms constraints and documentation metadata into msgspec.Meta; detects incompatible declarations.
Rule executorTraverses child schemas and collections, awaits each field’s rules in declaration order, and collects their failures.
ValidationExceptionCollects failures and exposes lists of {rule, message} objects grouped by field.

Types, constraints and documentation metadata have different purposes. For example, str requires a string, MinLength(2) limits its length, Email() checks its format, and Description("...") describes the field without validating its contents.

Without Coerce(), conversion preserves msgspec’s strict behavior: "36" is not a valid int for age in the example above. Certain types accept string representations, such as ISO dates and UUIDs, according to the declared type. Declare Field[int, Coerce(), GreaterThanOrEqual(18)] and import Coerce from orionis.schemas.metadata to opt in for that field. A marker on a parent schema or collection also enables descendant values; unrelated fields remain strict.

Version 1.4.0 also adds Empty() and NoEmpty(), exact opposites for empty and present values. They cover None, blank strings, numeric zero, False, zero-length collections, and zero-byte uploads without modifying the value. They run after coercion: "0" is present as a string, while coerced numeric zero is empty. See the integrated order example for nested fields, payload preservation, custom messages, and error codes.

Orionis collects each field’s errors: failed constraints and rules returning False. If initial conversion fails, it inspects the fields to complete the diagnosis. An incompatible type or missing field prevents conditions that require its converted value from running; other fields and elements continue to be validated.

Each errors entry includes rule and message. Custom rules publish their __code__; constraints use codes such as ge, min_length, or pattern. The summary counts individual failures, including several on the same field:

{
"message": "Quantity must be positive. (and 1 more error)",
"errors": {
"quantity": [
{"rule": "ge", "message": "Quantity must be positive."},
{"rule": "multiple_of", "message": "Quantity must be a multiple of 2."}
]
}
}

After optional coercion, the fast path retains msgspec’s native conversion and constraint checks. Metadata and plans are prepared when the class is declared; detailed collection is reserved for invalid data. Python rules and their I/O have their own cost. HTTP output validation only activates for a directly returned Schema instance; other responses do not run the validator.

Child schemas’ rules also run inside lists, tuples, sets, and dictionary values, even when another field fails conversion. Errors retain their location, such as contacts[0].email or contacts['primary'].email. See the collection and partial error examples.

See the format of errors, failures and messages in Validation and errors.

  1. Declaring schemas and converting data: required fields, defaults, types, metadata and the make:http-schema generator.
  2. Schemas across HTTP, MCP, and Realtime: automatic injection, data sources, and explicit validation in other contexts.
  3. Complete native constraints and rules reference: signatures, parameters, accepted values, and examples for every public constraint and rule.
  4. Application rules and custom rules: the asynchronous contract, I/O, and reuse.
  5. Validation and errors: asynchronous execution, collections, failures, and messages.
  6. Schemas in HTTP controllers: automatic input validation, HTTP errors and schemas as responses. The HTTP introduction summarizes this integration.

File, network and database rules need the context or services described in their reference. A schema does not configure those services itself.

In HTTP, the parameter receives the request body. In MCP, Tool[InputSchema, OutputSchema] declares the arguments and structured output contract; use an Orionis Schema class as the root to run its rules. In Realtime, @remote method parameters are validated from invocation arguments.

In services and plain WebSocket handlers, explicitly supply decoded data to await Validator.validate(data, UserSchema). An annotation alone does not identify queue messages or console arguments. The integration guide provides complete examples and explains differences in errors and responses across these contexts.