Skip to content

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.

Collect
path · query · body
One contract covers the whole request.
Check
types · constraints · rules
Every problem is collected, not just the first.
Typed input
input.title : String
Or a 422 listing every error; call stops.

A contract sits next to its action, named after it (why):

src/actions/posts/create_post_contract.cr
crystal
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
end
src/actions/posts/create_post.cr
crystal
class Posts::CreatePost < Blog::BaseAction
  post "/posts"

  call do
    input = validate(CreatePostContract)
    input.author_id   # => Int64
    input.title       # => String
    input.summary     # => String?
    # ...
  end
end

Reading 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 requestExampleRead when
Path parameters/posts/:idAlways
Query string?page=2&status=draftAlways
JSON body{"title": "Hello"}Content-Type: application/json (or application/*+json), except on GET/HEAD
Form bodytitle=Helloapplication/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:

src/actions/posts/update_post_contract.cr
crystal
class Posts::UpdatePostContract < RequestValidation::Contract
  schema do
    required :id, Int64                          # from /posts/:id
    required :title, String, filled: true        # from the JSON body
  end
end

When 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 ​

crystal
schema do
  required :name, Type, **options
  optional :name, Type, **options
end

Types ​

TypeFrom query, path and formFrom JSON
StringKept as-isMust be a JSON string
Int32, Int64Decimal integer string, e.g. "42", "-7"Must be a JSON integer in range
Float64Decimal or exponent stringJSON integer or float
BoolExactly "true" or "false"Must be true or false
Array(T) of the aboveRepeated keys: ?tag=a&tag=bA 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 ​

DeclarationField missingField is nullOutput type
required :age, Int32❌ missing❌ null_not_allowedInt32
required :age, Int32, nullable: true❌ missing✅Int32?
optional :age, Int32✅❌ null_not_allowedInt32?
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:

crystal
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
end

Constraints ​

Common checks can be declared on the field:

crystal
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
OptionApplies toFails with
filled: truestrings, arraysfilled
min_size:, max_size:, size:strings, arraysmin_size, max_size, size
gt:, gteq:, lt:, lteq:numbersgt, gteq, lt, lteq
allowed_values: [...]stringsenum
strip: truestrings— ignores surrounding whitespace while checking; the value itself is unchanged
allow_blank: truestrings, 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 ​

crystal
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
end

input.shipping is an AddressContract::Output, not a hash. Errors inside nested values report their full path, including array indexes:

json
{"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:

crystal
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 as T?.
  • 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:

crystal
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:

src/actions/transfers/create_transfer_contract.cr
crystal
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
end
src/actions/transfers/create_transfer.cr
crystal
class 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
end

With 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:

json
{
  "errors": [
    {"source": "request", "path": ["id"],    "code": "gt",     "params": {"num": 0}},
    {"source": "request", "path": ["title"], "code": "filled", "params": {}}
  ]
}
FieldMeaning
sourcerequest for contract errors; json, form or body when the body itself can't be read; file for uploads
pathField names and array indexes to the offending value; [] means the input as a whole
codeA stable, machine-readable code — translate it on the client
paramsExtra details, such as the expected type or a limit

Status codes ​

StatusWhenCodes
422The input doesn't satisfy the contractmissing, invalid_type, null_not_allowed, multiple_values, unexpected_key, expected_object, constraint and rule codes
400The body can't be parsedinvalid_json, invalid_multipart
413The body is too largebody_too_large, too_many_files, too_many_fields
415A body with an unsupported Content-Typeunsupported_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:

crystal
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
end

Each 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.

Released under the MIT License.