It’s important to highlight the correlation between the format and template name. For a given MIME Type, Rack (and then Hanami) associate a format for it. XML is mapped from to :xml, HTML is text/html and becomes :html for us.

    Format MUST be the first extension of the template file name. Eg dashboard/index.html.*.

    1. % curl -H "Accept: application/json" http://localhost:2300/dashboard
    2. {"foo":"bar"}

    We’re still able to request HTML format.

    1. % curl -H "Accept: text/html" http://localhost:2300/dashboard

    In case we request an unsupported MIME Type, our application will raise an error.

    View For Specific Format

    We can inherit from our view and declare that our subclass only handles a specific format.

    1. # apps/web/views/dashboard/json_index.rb
    2. module Web
    3. module Views
    4. module Dashboard
    5. class JsonIndex < Index
    6. format :json
    7. raw JSON.generate({foo: 'bar'})
    8. end
    9. end
    10. end
    11. end

    JSON requests for /dashboard, will be handled by our JsonIndex.

    With the example above we took advantage of custom rendering to not use the template and let our serializer to return JSON for us.