When a Hanami action is called, the incoming HTTP request and outgoing HTTP response are represented by the request and response objects provided to the action’s #handle method.

  1. module Bookshelf
  2. module Actions
  3. module Books
  4. class Index < Bookshelf::Action
  5. def handle(request, response)
  6. end
  7. end
  8. end
  9. end
  10. end

Request

The request object provides details about the incoming request. Use it to query information about the request, such as params and headers.

The object inherits from Rack::Request, which provides a range of methods like #path_info, #content_type and #get_header.

Here are some of the methods you can call on request:

  1. # app/actions/books/index.rb
  2. module Bookshelf
  3. module Actions
  4. module Books
  5. class Index < Bookshelf::Action
  6. def handle(request, response)
  7. request.path_info # => "/books"
  8. request.request_method # => "GET"
  9. request.get? # => true
  10. request.post? # => false
  11. request.xhr? # => false
  12. request.referer # => "http://example.com/"
  13. request.user_agent # => "Mozilla/5.0 Macintosh; ..."
  14. request.ip # => "127.0.0.1"
  15. request.get_header("HTTP_AUTHORIZATION") # => "Basic abc123"
  16. request.env["HTTP_AUTHORIZATION"] # => "Basic abc123"
  17. end
  18. end
  19. end
  20. end
  21. end

Response

The response object represents your action’s outgoing HTTP response.

Use it to control how your action responds to a request by setting an outgoing status, body or headers.

  1. # app/actions/books/create.rb
  2. module Bookshelf
  3. module Actions
  4. module Books
  5. class Create < Bookshelf::Action
  6. def handle(request, response)
  7. response.status = 201
  8. response.body = "Your resource has been created"
  9. response.headers["My-Header"] = "value"
  10. response.format = :json
  11. end
  12. end
  13. end
  14. end
  15. end

The response object inherits from Rack::Response.

Response status

By default, the response status is 200. Setting the response status via response.status is useful when setting statuses like 200 OK, 201 Created and 404 Not Found.

In situations where you want an action to halt, for example to return a 401 Unauthorized response, use the action’s halt method. To return a redirect, use response.redirect_to("/path"). See Control flow for details.

Response format

The value set using response.format can either be a format name (:json) or a content type string ("application/json"). Consult MIME types and formats for more information about setting response formats.