Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 439
X.Creates Avatar asked Dec 11 '22 13:12

X.Creates


1 Answers

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
like image 106
Shannon Avatar answered Mar 04 '23 02:03

Shannon