3

What I am trying to do is pretty simple. There are multiple versions of a Rails REST API. So, there are routes like:

http://www.example.com/v1/user.json
http://www.example.com/v2/user.json
http://www.example.com/v3/user.json 

What I want to do is add custom http headers to the response based on the API version endpoint that is requested.

In my config/application.rb file, I tried:

config.action_dispatch.default_headers.merge!('my_header_1' => 'my_value_1', 'my_header_2' => 'my_value_2')

I have also tried this in my config/routes.rb file:

scope path: "v1", controller: :test do
    get "action_1" => :action_1
    get "action_2" => :action_2
    Rails.application.config.action_dispatch.default_headers.merge!('my_header_1' => 'my_value_1', 'my_header_2' => 'my_value_2')
end

But both of these snippets append custom headers to the response irrespective of the API version endpoint.

I think I can write a middleware that checks the request url and appends the response headers based on that but it sounds a bit hackish.

Is there a better way to achieve this? Preferably via config or some central piece of code?

1 Answer 1

10

What about using a before_action on your controllers? I imagine each API version has its own controllers? That way you could do something like:

class API::V1::BaseController < ApplicationController
  before_action :set_headers

  protected

  def set_headers
    response.headers['X-Foo'] = 'V1'
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

In case before_action doesn't work, try prepend_before_action.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.