routewig
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: trueto 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
includeand 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 byon_errorsoafter_dispatchanddefault_headersstill 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
publicmethods with an explicitreq : Routewig::Requestparameter 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, ornilto 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 to413forPayloadTooLargeError,500otherwise).not_found_response(req : Routewig::Request) : Routewig::Response— Customize the default404JSON response.payload_too_large_response(req : Routewig::Request) : Routewig::Response— Customize the default413JSON response.max_body_size = 1_048_576_i64— Limit request body size globally (defaults to 1 MiB; setnilfor unlimited). BothContent-Lengthpre-check andLimitedIOstream counting are enforced even ifreq.context.request.bodyis read directly. Can be overridden per route in OpenAPI viax-max-body-size(e.g.10485760,"10MB", orunlimited).fallthrough = true— Forward unmatched requests tocall_nextinstead of returning404.unresolved_operations/openapi_warnings— Inspect unmappedoperationIds or parser warnings at startup.
Annotations
@[Routewig::Operation("customOperationId")]— Explicitly bind a method (0 or 1 arg) to an OpenAPIoperationId.@[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