Ruby on Rails - Respond to JSON Only

You might have a Rails controller that is only meant to respond to JSON requests.

I was integrating the FedEx API into a Rails app I'm working on for address validation. I created an Addresses controller with an action called validate_address which will query the FedEx API with an address and send back the results in JSON.

1
2
3
4
5
6
7
8
9
10
11
12
13
class AddressesController < ApplicationController

  def validate_address

    @api = FedexApi.new AppName::Application.config.fedex_config.symbolize_keys
    validated_address = @api.verify_address(params)
    
    respond_to do |format|
      format.json { render json: validated_address }
    end
  end

end

Solution

Add to following to the top of your controller:

1
2
3
4
5
6
# only accept json requests
before_filter :check_format

def check_format
  redirect_to root_url unless params[:format] == 'json' || request.headers["Accept"] =~ /json/
end

I can't take full credit for this. Thank you Stack Overflow.