How to automatically add/set request headers to all requests using a custom format in Rails?

98 Views Asked by At

In my Rails 7 project I've registered the :custom_json mime type:

# config/initializers/mime_types.rb
Mime::Type.register_alias 'application/json', :custom_json

I would like to auto-add the request header "Content-Type: application/json" to all requests using that :custom_json format. That is, when I execute HTTP requests to /path/to/action.custom_json or any other path using the :custom_json format then I would like the "Content-Type: application/json" header to be added to the request.

It seems the header is not added to all requests depending on the HTTP verb. That is, for example, when I execute GET requests then the header is auto-added; but when I execute POST and PATCH requests (where JSON data is set in the request body) then the header is not auto-added, making the request flow to fail.

For instance, if I execute the following POST HTTP request without explicitly setting the "Content-Type: application/json" header for it

curl "http://192.168.x.x:3000/users/action.custom_json" \
    -X POST \
    -d '{"val":{"var1":"value1","var2":"value2"}}'

then I get the log below (notice unparsed Parameters):

Started POST "/users/action.custom_json" for 192.168.x.y at 2024-02-16 07:41:04 +0100
Processing by UsersController#create as CUSTOM_JSON
  Parameters: {"{\"val\":{\"var1\":\"value1\",\"var2\":\"value2\"}}"=>"[FILTERED]"}

I tried things like the following without success:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_custom_json_request_header, :if => :request_format_custom_json?

  private 

  def set_custom_json_request_header
    headers['Content-Type'] ||= 'application/json'
  end

  def request_format_custom_json?
    request.format.symbol == :custom_json
  end
end

How can I auto-add request headers such as Content-Type: application/json to all requests using a custom format such as custom_json in Rails?

0

There are 0 best solutions below