In order to understand what the requested MIME Type is, an action looks at the request header and exposes a high level API: #format and #accept?.

The first returns a symbol representation of the MIME Type (eg. :html, :json, :xml etc..), while the second is a query method that accepts a MIME type string and checks if it’s accepted by the current browser.

An action returns the Content-Type response header automatically according to the requested MIME Type and charset.

If a client asks for a generic Accept: */*, the action will fall back to the application default format. This is a setting that allows us to safely handle cases like our example; the default value is :html.

  1. # apps/web/application.rb
  2. module Web
  3. class Application < Hanami::Application
  4. configure do
  5. # ...
  6. end
  7. end

If we are building a JSON API app, it can be useful to specify a :json as default MIME Type for the response. The default value is :html.

Similarly, we can specify a different default charset to return. The standard value is utf-8, but we can change it in our settings.

  1. # apps/web/application.rb
  2. module Web
  3. class Application < Hanami::Application
  4. configure do
  5. # ...
  6. default_charset 'koi8-r'
  7. end
  8. end
  9. end

The example above will return Content-Type: application/json; charset=utf-8.

We can also restrict the range of accepted MIME Types. If the incoming request doesn’t satisfy this constraint, the application will return a Not Acceptable status (406).

  1. module Controllers
  2. module Dashboard
  3. class Index
  4. include Web::Action
  5. accept :html, :json
  6. def call(params)
  7. # ...
  8. end
  9. end
  10. end
  11. end

Hanami knows about more than 100 of the most common MIME types. However, we may want to add custom types in order to use them with #format= or .accept.