Request Contracts
A request contract describes the input an endpoint accepts. The action calls validate with it as the first line of call, and gets back a typed object — or, if the request doesn't fit, Runcobo answers with a structured error and the rest of call never runs. Contracts come from the request_validation library, which Runcobo installs for you.
path · query · bodytypes · constraints · rulesinput.title : StringA contract sits next to its action, named after it (why):
class Posts::CreatePostContract < RequestValidation::Contract
schema do
required :author_id, Int64
required :title, String, filled: true, strip: true, max_size: 200
optional :summary, String, nullable: true, max_size: 500
end
endclass Posts::CreatePost < Blog::BaseAction
post "/posts"
call do
input = validate(CreatePostContract)
input.author_id # => Int64
input.title # => String
input.summary # => String?
# ...
end
endReading input with validate
validate checks the whole request against the contract in one pass. Fields can come from any part of it:
| Part of the request | Example | Read when |
|---|---|---|
| Path parameters | /posts/:id | Always |
| Query string | ?page=2&status=draft | Always |
| JSON body | {"title": "Hello"} | Content-Type: application/json (or application/*+json), except on GET/HEAD |
| Form body | title=Hello | application/x-www-form-urlencoded or multipart/form-data, except on GET/HEAD |
So one contract describes everything an endpoint takes — an UpdatePost contract lists both the id from the path and the title from the body:
class Posts::UpdatePostContract < RequestValidation::Contract
schema do
required :id, Int64 # from /posts/:id
required :title, String, filled: true # from the JSON body
end
endWhen the same field name appears in more than one place:
- a path parameter always wins;
- a JSON body value replaces a query value;
- a form body value is added alongside the query value, so a field sent in both fails with
multiple_values.
A request body with any other Content-Type is rejected with 415. Bodies are size-limited — see Limits.
When validation fails
validate raises, the action stops, and Runcobo responds with every problem it found — see Error responses. Call it once, at the top of call, before doing any work.
Fields
schema do
required :name, Type, **options
optional :name, Type, **options
endTypes
| Type | From query, path and form | From JSON |
|---|---|---|
String | Kept as-is | Must be a JSON string |
Int32, Int64 | Decimal integer string, e.g. "42", "-7" | Must be a JSON integer in range |
Float64 | Decimal or exponent string | JSON integer or float |
Bool | Exactly "true" or "false" | Must be true or false |
Array(T) of the above | Repeated keys: ?tag=a&tag=b | A JSON array |
| Another contract | — | A nested JSON object |
JSON::Any | — | Any JSON value, unvalidated |
JSON input is never coerced: {"age": "42"} fails with invalid_type. Query and form values are strings by nature, so they are converted — strictly.
A scalar field sent twice (?id=1&id=2) fails with multiple_values instead of silently picking one.
Required, optional and null
| Declaration | Field missing | Field is null | Output type |
|---|---|---|---|
required :age, Int32 | ❌ missing | ❌ null_not_allowed | Int32 |
required :age, Int32, nullable: true | ❌ missing | ✅ | Int32? |
optional :age, Int32 | ✅ | ❌ null_not_allowed | Int32? |
optional :age, Int32, nullable: true | ✅ | ✅ | Int32? |
required only checks presence — an empty string "", 0 and false are all present. Use filled: true to reject empty strings.
Missing vs null
Every field gets a <name>_present? method. It tells "the client didn't send it" apart from "the client sent null" — essential for PATCH endpoints:
class UpdateProfileContract < RequestValidation::Contract
schema do
optional :bio, String, nullable: true
end
end
# {} → bio_present? == false → leave the bio alone
# {"bio": null} → bio_present? == true, bio == nil → clear the bio
# {"bio": "Hi"} → bio_present? == true, bio == "Hi" → update it
if input.bio_present?
profile.bio = input.bio
endConstraints
Common checks can be declared on the field:
schema do
required :title, String, filled: true, strip: true, min_size: 3, max_size: 80
required :quantity, Int64, gteq: 1, lteq: 100
optional :ratio, Float64, gt: 0.0, lt: 1.0
optional :tags, Array(String), max_size: 5
optional :status, String, allowed_values: ["draft", "published"]
end| Option | Applies to | Fails with |
|---|---|---|
filled: true | strings, arrays | filled |
min_size:, max_size:, size: | strings, arrays | min_size, max_size, size |
gt:, gteq:, lt:, lteq: | numbers | gt, gteq, lt, lteq |
allowed_values: [...] | strings | enum |
strip: true | strings | — ignores surrounding whitespace while checking; the value itself is unchanged |
allow_blank: true | strings, arrays | — skips the constraints for "" or [] |
Constraint errors carry their limit in params: {"code": "gteq", "params": {"num": 1}}, or for allowed_values, {"code": "enum", "params": {"list": "draft, published"}}.
Invalid declarations — an unknown option, gt: on a String, a negative size — are compile errors.
Arrays and nested contracts
class AddressContract < RequestValidation::Contract
schema do
required :city, String
optional :zip, String
end
end
class OrderContract < RequestValidation::Contract
schema do
required :items, Array(Int64), filled: true
required :shipping, AddressContract
end
endinput.shipping is an AddressContract::Output, not a hash. Errors inside nested values report their full path, including array indexes:
{"source": "request", "path": ["items", 1], "code": "invalid_type", "params": {"expected": "Int64"}}
{"source": "request", "path": ["shipping", "city"], "code": "missing", "params": {}}Arrays of objects and multi-dimensional arrays are not supported. JSON::Any is the escape hatch for free-form data; validate its shape yourself.
Rules
Use rule for checks that involve several fields or business logic. List the fields it depends on; the block receives their converted values, then an errors object:
class SignupContract < RequestValidation::Contract
schema do
required :password, String, min_size: 12
required :password_confirmation, String
optional :referral_code, String
end
rule :password, :password_confirmation do |password, confirmation, errors|
errors.add(:password_confirmation, :does_not_match) unless password == confirmation
end
rule :referral_code do |code, errors|
if code && !code.starts_with?("REF-")
errors.add(:referral_code, :invalid_format, {"prefix" => "REF-"} of String => RequestValidation::ErrorParam)
end
end
end- A rule runs only when all its fields passed their type and constraint checks — you never see half-validated values.
- Required non-nullable fields arrive as
T; optional or nullable ones asT?. errors.add(field, code, params)reports a field error;errors.base(code)reports an error about the whole input.errors.present?(:field)tells you whether a dependency was sent.- A rule without fields is written
rule do |errors| ... end. - Exceptions raised inside a rule are not turned into validation errors; they propagate as real errors.
Error codes are yours to choose. Runcobo never includes the submitted values in error responses, so rules can safely check passwords and tokens.
Unknown fields
By default, fields not declared in the contract are stripped: they're ignored and don't appear in input. To reject them with an unexpected_key error, pass strict: true:
input = validate(CreatePostContract, strict: true)Nested contracts always reject unknown keys, regardless of the parent's setting.
Contracts with dependencies
Contracts are ordinary classes, so they can take constructor arguments. Pass validate an instance instead of the class:
class Transfers::CreateTransferContract < RequestValidation::Contract
def initialize(@max_amount : Int64, unknown_keys : RequestValidation::UnknownKeys = :strip)
super(unknown_keys: unknown_keys)
end
schema do
required :amount, Int64, gt: 0
end
rule :amount do |amount, errors|
errors.add(:amount, :over_limit) if amount > @max_amount
end
endclass Transfers::CreateTransfer < Blog::BaseAction
post "/transfers"
call do
input = validate(CreateTransferContract.new(transfer_limit))
# ...
end
private def transfer_limit : Int64
10_000_i64 # e.g. looked up for the signed-in account
end
endWith an instance, the contract's own unknown_keys setting decides whether unknown fields are stripped or rejected.
Error responses
Every failure is answered with a JSON body listing all problems:
{
"errors": [
{"source": "request", "path": ["id"], "code": "gt", "params": {"num": 0}},
{"source": "request", "path": ["title"], "code": "filled", "params": {}}
]
}| Field | Meaning |
|---|---|
source | request for contract errors; json, form or body when the body itself can't be read; file for uploads |
path | Field names and array indexes to the offending value; [] means the input as a whole |
code | A stable, machine-readable code — translate it on the client |
params | Extra details, such as the expected type or a limit |
Status codes
| Status | When | Codes |
|---|---|---|
422 | The input doesn't satisfy the contract | missing, invalid_type, null_not_allowed, multiple_values, unexpected_key, expected_object, constraint and rule codes |
400 | The body can't be parsed | invalid_json, invalid_multipart |
413 | The body is too large | body_too_large, too_many_files, too_many_fields |
415 | A body with an unsupported Content-Type | unsupported_media_type |
If the body can't be read (400, 413, 415), that error is returned on its own; otherwise all contract errors are returned together.
Customizing the response
Override render_validation_errors — in Blog::BaseAction to change it everywhere:
abstract class Blog::BaseAction < ::BaseAction
protected def render_validation_errors(issues : Array(Runcobo::Validation::Issue), *, status_code : Int32) : HTTP::Server::Context
render_json({
error: "invalid_request",
details: issues.map { |issue| {field: issue.path.join("."), code: issue.code} },
}, status_code: status_code)
end
endEach Runcobo::Validation::Issue has source, path, code and params.
Limits
Request bodies are capped at 1 MiB by default. See Request Bodies & Uploads to change it per action.