Pika::API
Class methods
present — serialize an object or collection through an Entity class. Call from inside a handler block: present user, using: UserEntity
Macros
before / after hooks — run around every route handler in this class
before do raise Pika::UnauthorizedError.new unless env.request.headers["X-Token"]? end
docs — mount Scalar UI and OpenAPI JSON endpoint
docs at: "/docs" # GET /docs → Scalar HTML # GET /docs/openapi.json → OpenAPI 3.1
error_formatter — select the active error serialization format
error_formatter :rfc7807 # default — application/problem+json error_formatter :grape # {"error": "message"} error_formatter :jsonapi # {"errors": [...]}
helpers — define class-level helper methods accessible inside handlers
helpers do def self.current_user(env) env.request.headers["X-User-Id"]? end end
info — set API metadata used in the OpenAPI document
info title: "My API", version: "2.0.0", description: "..."
mount — compose another Pika::API's routes into this one
mount AdminAPI # copies /admin/... routes verbatim
The current version + namespace prefix is applied to all mounted paths.
namespace — groups routes under a common path segment
namespace :admin do resource :users do ... end end
resource macro
The core DSL macro. Parses its block body as an AST to accumulate desc / params / verb triples, then generates:
- A typed DeclaredParams struct per route.
- A validate! class method with full constraint enforcement.
- A Pika::Router#add registration (path computed at class-init time).
- A Pika::OpenAPI::RouteSpec entry.
Supports nested route_param blocks one level deep:
resource :users do get do ... end # GET /users post do ... end # POST /users
route_param :id do
get do ... end # GET /users/:id
patch do ... end # PATCH /users/:id
delete do ... end # DELETE /users/:id
end
end
Params blocks support mutually_exclusive / at_least_one_of / exactly_one_of:
params do optional email : String? optional phone : String? mutually_exclusive :email, :phone end
version — sets a path prefix for the entire API