Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

respond to only json in rails

In my rails app which is json only, I want to send a 406 code whenever someone calls my rails app with accept header set to anything except application/json. I also want it to send a 415 when I get the content type set to anything except application / json

My controllers have respond_to :json put on them. I only render json in all actions. However how do I ensure that I return error code 406/415 for all calls for anything that is called for all other accept headers/content-type and with format set to anything except json.

Eg. If I my resource is books/1 I want to allow books/1.json or books/1 with application/json in accept header and content type

Any ideas on how I can do these two actions?

like image 959
av501 Avatar asked Jan 29 '13 09:01

av501


Video Answer


2 Answers

Basically, you can limit your responses in two ways.

First, there is respond_to for your controllers. This would automatically trigger a 406 Not Acceptable if a request for a format is made which is not defined.

Example:

class SomeController < ApplicationController
  respond_to :json


  def show
    @record = Record.find params[:id]

    respond_with @record
  end
end

The other way would be to add a before_filter to check for the format and react accordingly.

Example:

class ApplicationController < ActionController::Base
  before_filter :check_format


  def check_format
    render :nothing => true, :status => 406 unless params[:format] == 'json' || request.headers["Accept"] =~ /json/
  end
end
like image 196
pdu Avatar answered Sep 22 '22 18:09

pdu


You can do it with a before_filter in ApplicationController

before_filter :ensure_json_request

def ensure_json_request
  return if params[:format] == "json" || request.headers["Accept"] =~ /json/
  render :nothing => true, :status => 406
end
like image 23
Erez Rabih Avatar answered Sep 22 '22 18:09

Erez Rabih