routewig

Lightweight Crystal router that turns an OpenAPI 3.x YAML into a trie-based route table with compile-time dispatch. Stdlib only.

Routewig

A lightweight, zero-dependency, OpenAPI-driven Web API router and controller framework for Crystal.

  • Zero external shard dependencies: Uses only Crystal's standard library (http/server, yaml, json, uri).
  • OpenAPI YAML as-is: Load an OpenAPI 3.x YAML file (or string) at startup. Missing/optional fields are tolerated gracefully (or use strict: true to fail fast).
  • In-memory optimized routing: Static paths resolve in $O(1)$ via Hash, and parameterized/templated paths resolve via a segment Trie prioritizing static segments.
  • Just include and return {status, headers_json, body}: Write handlers cleanly without boilerplate.
  • Safe defaults: Unmatched routes and unimplemented operations return 404, malformed header JSON falls back safely, and unhandled handler exceptions are caught by on_error so after_dispatch and default_headers still apply.

Installation

Add this to your application's shard.yml:

dependencies:
  routewig:
    github: minor-mn/routewig

Quick Start (Single-Class Style)

require "routewig"

class MyApi
  include Routewig::Router

  def initialize
    load_openapi_file("openapi.yml")
  end

  @[Routewig::Operation]
  def healthz
    {200, {"Cache-Control" => "no-store"}.to_json, %({"status":"ok"})}
  end

  def get_user(req : Routewig::Request)
    id = req.params["id"]
    {200, {"X-User" => id}.to_json, {id: id}.to_json}
  end
end

server = HTTP::Server.new([MyApi.new])
server.bind_tcp("0.0.0.0", 8080)
server.listen

With openapi.yml:

openapi: 3.0.3
paths:
  /healthz:
    get:
      operationId: healthz
  /users/{id}:
    get:
      operationId: getUser # matches get_user, getUser, or get-user automatically

Note on handler registration: For safety, only public methods with an explicit req : Routewig::Request parameter type or an @[Routewig::Operation] annotation are registered as API handlers. Regular public helper methods (e.g. def format_name(name)) are safely ignored.

Splitting Router & Controllers

You can separate your router and controllers using include Routewig::Controller (or inheriting Routewig::BaseController):

class UsersController
  include Routewig::Controller

  def list_users(req : Routewig::Request)
    {200, "{}", %(["alice","bob"])}
  end
end

class UserInfoController < Routewig::BaseController
  @[Routewig::Operation("fetchUserInfo")]
  def info(req)
    id = req.params["id"]
    {200, "{}", {id: id}.to_json}
  end
end

class AppRouter
  include Routewig::Router

  def initialize
    load_openapi_file("openapi.yml", base_path: "/api")
    mount UsersController.new
    mount UserInfoController.new
  end
end

Handler Return Formats

Handlers can return any of the following:

  • {Int32, String, String} — {status_code, headers_json, body} (JSON arrays like {"Set-Cookie": ["a=1", "b=2"]} produce multiple headers)
  • {Int32, Hash(String, String), String} or {Int32, Hash(String, Array(String)), String}
  • {Int32, NamedTuple, String}
  • {Int32, Nil, String}
  • Routewig::Response

Hooks, Safety & Diagnostics

Override or configure any of these in your Router class:

  • before_dispatch(req : Routewig::Request) — Run authentication/validation; return a response tuple to short-circuit, or nil to continue.
  • after_dispatch(req : Routewig::Request, res : Routewig::Response) : Routewig::Response — Add CORS headers, logging, etc.
  • on_error(req : Routewig::Request, ex : Exception) : Routewig::Response — Customize error responses (defaults to 413 for PayloadTooLargeError, 500 otherwise).
  • not_found_response(req : Routewig::Request) : Routewig::Response — Customize the default 404 JSON response.
  • payload_too_large_response(req : Routewig::Request) : Routewig::Response — Customize the default 413 JSON response.
  • max_body_size = 1_048_576_i64 — Limit request body size globally (defaults to 1 MiB; set nil for unlimited). Both Content-Length pre-check and LimitedIO stream counting are enforced even if req.context.request.body is read directly. Can be overridden per route in OpenAPI via x-max-body-size (e.g. 10485760, "10MB", or unlimited).
  • fallthrough = true — Forward unmatched requests to call_next instead of returning 404.
  • unresolved_operations / openapi_warnings — Inspect unmapped operationIds or parser warnings at startup.

Annotations

  • @[Routewig::Operation("customOperationId")] — Explicitly bind a method (0 or 1 arg) to an OpenAPI operationId.
  • @[Routewig::Ignore] — Exclude a public method from being registered as an API handler.

License

MIT

Repository

routewig

Owner
Statistic
  • 0
  • 0
  • 0
  • 0
  • 0
  • 30 minutes ago
  • December 1, 2026
License

MIT License

Links
Synced at

Tue, 01 Dec 2026 21:36:33 GMT

Languages