Hanami::API
Minimal, extremely fast, lightweight Ruby framework for HTTP APIs.
Status
Contact
- Home page: http://hanamirb.org
- Mailing List: http://hanamirb.org/mailing-list
- API Doc: http://rubydoc.info/gems/hanami-api
- Bugs/Issues: https://github.com/hanami/api/issues
- Chat: http://chat.hanamirb.org
Installation
Hanami::API supports Ruby (MRI) 3.2+
Add these lines to your application's Gemfile:
gem "hanami-api"
gem "puma" # or "webrick", or "thin", "falcon"And then execute:
$ bundle installOr install it yourself as:
$ gem install hanami-api- Performance
- Runtime
- Memory
- Requests per second
- Usage
- Routes
- HTTP methods
- Endpoints
- Rack endpoint
- Block endpoint
- String (body)
- Enumerator (body)
- Integer (status code)
- Integer, String (status code, body)
- Integer, Enumerator (status code, body)
- Integer, Hash, String (status code, headers, body)
- Integer, Hash, Enumerator (status code, headers, body)
- Block context
- env
- status
- headers
- body
- params
- halt
- redirect
- back
- json
- Scope
- Helpers
- Rack Middleware
- Streamed Responses
- Body Parsers
- Testing
- Development
- Contributing
Performance
Benchmark against an app with 10,000 routes, hitting the 10,000th to measure the worst case scenario.
Based on jeremyevans/r10k, Hanami::API scores first for speed, and second for memory footprint.
Runtime
Runtime to complete 20,000 requests (lower is better).
| Framework | Seconds to complete |
|---|---|
| hanami-api | 0.116 |
| watts | 0.235 |
| roda | 0.348 |
| syro | 0.356 |
| rack-app | 0.623 |
| cuba | 1.291 |
| rails | 17.047 |
| sinatra | 197.477 |
Memory
Memory footprint for 10,000 routes app (lower is better).
| Framework | Bytes |
|---|---|
| roda | 47252 |
| hanami-api | 53988 |
| cuba | 55420 |
| syro | 60256 |
| rack-app | 82976 |
| watts | 84956 |
| sinatra | 124980 |
| rails | 143048 |
Requests per second
For this benchmark there are two apps for each framework: one with the root route, and one with 10,000 routes. Requests per second hitting the 1st (and only route) and the 10,000th route to measure the best and worst case scenario (higher is better).
| Framework | 1st route | 10,000th route |
|---|---|---|
| hanami-api | 14719.95 | 14290.20 |
| watts | 13912.31 | 12609.68 |
| roda | 13965.20 | 11051.27 |
| syro | 13079.12 | 10689.51 |
| rack-app | 10274.01 | 10306.46 |
| cuba | 13061.82 | 7084.33 |
| rails | 1345.27 | 303.06 |
| sinatra | 5038.74 | 28.14 |
Usage
Create config.ru at the root of your project:
# frozen_string_literal: true
require "bundler/setup"
require "hanami/api"
class App < Hanami::API
get "/" do
"Hello, world"
end
end
run App.newStart the Rack server with bundle exec rackup
Routes
A route is a combination of three elements:
- HTTP method (e.g.
get) - Path (e.g.
"/") - Endpoint (e.g.
MyEndpoint.new)
get "/", to: MyEndpoint.newHTTP methods
Hanami::API supports the following HTTP methods:
getheadpostpatchputdeleteoptionstracelinkunlink
Endpoints
Hanami::API supports two kind of endpoints: block and Rack.
Rack endpoint
The framework is compatible with Rack. Any Rack endpoint, can be passed to the route:
get "/", to: MyRackEndpoint.newBlock endpoint
A block passed to the route definition is named a block endpoint. The returning value will compose the Rack response. It can be:
String (body)
get "/" do
"Hello, world"
endIt will return [200, {}, ["Hello, world"]]
Enumerator (body)
get "/" do
Enumerator.new { ... }
endIt will return [200, {}, Enumerator], see Streamed Responses
Integer (status code)
get "/" do
418
endIt will return [418, {}, ["I'm a teapot"]]
Integer, String (status code, body)
get "/" do
[401, "You shall not pass"]
endIt will return [401, {}, ["You shall not pass"]]
Integer, Enumerator (status code, body)
get "/" do
[401, Enumerator.new { ... }]
endIt will return [401, {}, Enumerator], see Streamed Responses
Integer, Hash, String (status code, headers, body)
get "/" do
[401, {"X-Custom-Header" => "foo"}, "You shall not pass"]
endIt will return [401, {"X-Custom-Header" => "foo"}, ["You shall not pass"]]
Integer, Hash, Enumerator (status code, headers, body)
get "/" do
[401, {"X-Custom-Header" => "foo"}, Enumerator.new { ... }]
endIt will return [401, {"X-Custom-Header" => "foo"}, Enumerator], see Streamed Responses
Block context
When using the block syntax there is a rich API to use.
env
The #env method exposes the Rack environment for the current request
status
Get HTTP status
get "/" do
puts status
# => 200
endSet HTTP status
get "/" do
status(201)
endheaders
Get HTTP response headers
get "/" do
puts headers
# => {}
endSet HTTP status
get "/" do
headers["X-My-Header"] = "OK"
endbody
Get HTTP response body
get "/" do
puts body
# => nil
endSet HTTP response body
get "/" do
body "Hello, world"
endSet HTTP response body using a Streamed Response
get "/" do
body Enumerator.new { ... }
endparams
Access params for current request
get "/" do
id = params[:id]
# ...
endhalt
Halts the flow of the block and immediately returns with the current HTTP status
get "/authenticate" do
halt(401)
# this code will never be reached
endIt sets a Rack response: [401, {}, ["Unauthorized"]]
get "/authenticate" do
halt(401, "You shall not pass")
# this code will never be reached
endIt sets a Rack response: [401, {}, ["You shall not pass"]]
You can also use a Streamed Response here
get "/authenticate" do
halt(401, Enumerator.new { ... })
endredirect
Redirects request and immediately halts it
get "/legacy" do
redirect "/dashboard"
# this code will never be reached
endIt sets a Rack response: [301, {"Location" => "/new"}, ["Moved Permanently"]]
get "/legacy" do
redirect "/dashboard", 302
# this code will never be reached
endIt sets a Rack response: [302, {"Location" => "/new"}, ["Moved"]]
back
Utility for redirect back using HTTP request header HTTP_REFERER
get "/authenticate" do
if authenticate(env)
redirect back
else
# ...
end
endjson
Sets a JSON response for the given object
get "/user/:id" do
user = UserRepository.new.find(params[:id])
json(user)
endget "/user/:id" do
user = UserRepository.new.find(params[:id])
json(user, "application/vnd.api+json")
endIf you want a Streamed Response
get "/users" do
users = Enumerator.new { ... }
json(users)
endScope
Prefixing routes is possible with routing scopes:
scope "api" do
scope "v1" do
get "/users", to: Actions::V1::Users::Index.new
end
endIt will generate a route with "/api/v1/users" as path.
Helpers
Define helper methods available within the block context.
Helper methods have access to default utilities available in block context (e.g. #halt).
Helpers can be defined inline by passing a block to the .helpers method:
require "hanami/api"
class MyAPI < Hanami::API
helpers do
def redirect_to_root
# redirect method is provided by Hanami::API block context
redirect "/"
end
end
root { "Hello, World" }
get "/legacy" do
redirect_to_root
end
endAlternatively, .helpers accepts a module.
require "hanami/api"
class MyAPI < Hanami::API
module Authentication
private
def unauthorized
halt(401)
end
end
helpers(Authentication)
root { "Hello, World" }
get "/secrets" do
unauthorized
end
endYou can use .helpers multiple times in the same app.
Rack Middleware
To mount a Rack middleware it's possible with .use
# frozen_string_literal: true
require "bundler/setup"
require "hanami/api"
class App < Hanami::API
use ElapsedTime
scope "api" do
use ApiAuthentication
scope "v1" do
use ApiV1Deprecation
end
scope "v2" do
# ...
end
end
endMiddleware are inherited from top level scope.
In the example above, ElapsedTime is used for each incoming request because
it's part of the top level scope. ApiAuthentication it's used for all the API
versions, because it's defined in the "api" scope. ApiV1Deprecation is used
only by the routes in "v1" scope, but not by "v2".
Streamed Responses
When the work to be done by the server takes time, it may be a good idea to
stream your response. For this, you just use an Enumerator anywhere you would
normally use a String as body or another Object as JSON response. Here's an
example of streaming JSON data:
scope "stream" do
use ::Rack::Chunked
get "/data" do
Enumerator.new do |yielder|
data = %w[a b c]
data.each do |item|
yielder << item
end
end
end
get "/to_enum" do
%w[a b c].to_enum
end
get "/json" do
result = Enumerator.new do |yielder|
data = %w[a b c]
data.each do |item|
yielder << item
end
end
json(result)
end
endNote:
- Returning an
Enumeratorwill also work withoutRack::Chunked, it just won't stream but return the whole body at the end instead. - Data pushed to
yielderMUST be aString. - Streaming does not work with WEBrick as it buffers its response. We recommend
using
puma, though you may find success with other servers. - To manual test this feature use a web browser or cURL:
$ curl --raw -i http://localhost:2300/stream/dataBody Parsers
Rack ignores request bodies unless they come from a form submission.
If you have an endpoint that accepts JSON, the request payload isn’t available in params.
In order to parse JSON payload and make it avaliable in params, you should add the following lines to config.ru:
# frozen_string_literal: true
require "hanami/middleware/body_parser"
use Hanami::Middleware::BodyParser, :jsonTesting
Unit testing
You can unit test your Hanami::API app by passing a env hash to your app's #call method.
The keys that (based on the Rack standard) Hanami::API uses for routing are:
PATH_INFOREQUEST_METHOD
For example, a spec for the basic app in the Usage section could be:
require "my_project/app"
RSpec.describe App do
describe "#call" do
it "returns successfully" do
response = subject.call({"PATH_INFO" => "/", "REQUEST_METHOD" => "GET"})
expect(response).to eq([200, {}, ["Hello, world"]])
end
end
endIntegration testing
Add this line to your application's Gemfile:
gem "rack-test", group: :testIn a test, load Rack::Test:
require "rack/test"and then, inside your spec/test, include its helper methods:
include Rack::Test::MethodsThen you can use its methods like get and last_response, e.g.:
it "returns the status 200" do
get "/"
expect(last_response.status).to eq 200
endDevelopment
After checking out the repo, run bin/setup to install dependencies. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/hanami/api.
Copyright
Copyright © 2014–2024 Hanami Team – Released under MIT License.