Rails: Restrict API requests to JSON format

三世轮回 提交于 2019-12-02 22:08:27

Setting a default in your routes won't turn all requests into a JSON request.

What you want is to make sure that whatever you're rendering is a JSON response

You pretty much had it in the first option except you need to do this

before_filter :set_default_response_format

private
  def set_default_response_format
    request.format = :json
  end

That would go under your Base API controller so that when it gets to your actual action the format will always be JSON.

PeppyHeppy

If you want to return a 404, or raise a RouteNotFound error if the format is not :json, I would add a route constraint like this:

Require JSON format:

# routes.rb
MyApp::Application.routes.draw do
  namespace :api, constraints: { format: 'json' } do
    namespace :v1 do
      resources :posts
    end
  end
end

More information can be found here: http://edgeguides.rubyonrails.org/routing.html#request-based-constraints

mathieugagne

Second option, using routes format. If a user explicitly requests a XML format, he should not receive a JSON response. He should get a message saying that this URL doesn't answer to XML format, or 404.

By the way, it would be rather easy to respond to all which is what you should do in my opinion.

class FooController
  respond_to :xml, :json
  def show
    @bar = Bar.find(params[:id])
    respond_with(@bar)
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!