Li Xinyang Li Xinyang - 4 years ago 160
Ruby Question

How to set content type for JSON API in Rails 5 API only app

Follow the specification to use the JSON api, the content type must be set to

application/vnd.api+json
; however, setting the
ContentType
in every action in the controller seems tedious (see code below).

def foo
response.headers['Content-Type'] = 'application/vnd.api+json'
# ...
end


Is there a better way to achive the same result? Since this is an API only app is this possible to set content type at application level?

Answer Source

You can use the before_action directive:

class ApplicationController < ActionController::API
  before_action :set_headers

  def set_headers
    response.headers['Content-Type'] = 'application/vnd.api+json'
  end

end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download