Hanami::API - 用于HTTP API最小、极其快速、轻便的Ruby框架

网友投稿 717 2022-10-12

Hanami::API - 用于HTTP API最小、极其快速、轻便的Ruby框架

Hanami::API - 用于HTTP API最小、极其快速、轻便的Ruby框架

Hanami::API

Minimal, extremely fast, lightweight Ruby framework for HTTP APIs.

Installation

Add this line to your application's Gemfile:

gem "hanami-api"

And then execute:

$ bundle install

Or install it yourself as:

$ gem install hanami-api

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

FrameworkSeconds to complete
hanami-api0.11628299998119473
watts0.23525599995628
roda0.348202999914065
syro0.355627000099048
rack-app0.6226229998283088
cuba1.2913489998318255
rails17.04722599987872
sinatra197.47695700009353

Memory

Memory footprint for 10,000 routes app (lower is better).

FrameworkBytes
roda47252
hanami-api53988
cuba55420
syro60256
rack-app82976
watts84956
sinatra124980
rails143048

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

Framework1st route10,000th route
hanami-api14719.9514290.20
watts13912.3112609.68
roda13965.2011051.27
syro13079.1210689.51
rack-app10274.0110306.46
cuba13061.827084.33
rails1345.27303.06
sinatra5038.7428.14

Usage

Create config.ru at the root of your project:

# frozen_string_literal: truerequire "bundler/setup"require "hanami/api"class App < Hanami::API get "/" do "Hello, world" endendrun App.new

Start 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.new

HTTP methods

Hanami::API supports the following HTTP methods:

getheadpostpatchputoptionstracelinkunlink

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

Block 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

get "/" do "Hello, world"end

It will return [200, {}, ["Hello, world"]]

Integer

get "/" do 418end

It will return [418, {}, ["I'm a teapot"]]

Integer, String

get "/" do [401, "You shall not pass"]end

It will return [401, {}, ["You shall not pass"]]

Integer, Hash, String

get "/" do [401, {"X-Custom-Header" => "foo"}, "You shall not pass"]end

It will return [401, {"X-Custom-Header" => "foo"}, ["You shall not pass"]]

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 # => 200end

Set HTTP status

get "/" do status(201)end

headers

Get HTTP response headers

get "/" do puts headers # => {}end

Set HTTP status

get "/" do headers["X-My-Header"] = "OK"end

body

Get HTTP response body

get "/" do puts body # => nilend

Get HTTP response body

get "/" do body "Hello, world"end

params

Access params for current request

get "/" do id = params[:id] # ...end

halt

Halts the flow of the block and immediately returns with the current HTTP status

get "/authenticate" do halt(401) # this code will never be reachedend

It sets a Rack response: [401, {}, ["Unauthorized"]]

get "/authenticate" do halt(401, "You shall not pass") # this code will never be reachedend

It sets a Rack response: [401, {}, ["You shall not pass"]]

redirect

Redirects request and immediately halts it

get "/legacy" do redirect "/dashboard" # this code will never be reachedend

It sets a Rack response: [301, {"Location" => "/new"}, ["Moved Permanently"]]

get "/legacy" do redirect "/dashboard", 302 # this code will never be reachedend

It 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 # ... endend

json

Sets a JSON response for the given object

get "/user/:id" do user = UserRepository.new.find(params[:id]) json(user)end

get "/user/:id" do user = UserRepository.new.find(params[:id]) json(user, "application/vnd.api+json")end

Scope

Prefixing routes is possible with routing scopes:

scope "api" do scope "v1" do get "/users", to: Actions::V1::Users::Index.new endend

It will generate a route with "/api/v1/users" as path.

Rack Middleware

To mount a Rack middleware it's possible with .use

# frozen_string_literal: truerequire "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 endend

Middleware 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".

Development

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.

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Docker定制镜像
下一篇:远程连接mongodb时,27017端口连接不上的解决办法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~