Rails:将API请求限制为JSON格式

我想限制所有API控制器的请求被重定向到JSON路径。 我想使用重定向,因为URL也应根据响应而改变。
一种选择是使用before_filter将请求重定向到相同的操作但强制JSON格式。 这个例子还没有用!

 # base_controller.rb class Api::V1::BaseController < InheritedResources::Base before_filter :force_response_format respond_to :json def force_response_format redirect_to, params[:format] = :json end end 

另一种选择是限制路线设置中的格式。

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

我希望所有请求最终都是JSON请求:

 http://localhost:3000/api/v1/posts http://localhost:3000/api/v1/posts.html http://localhost:3000/api/v1/posts.xml http://localhost:3000/api/v1/posts.json ... 

你会推荐哪种策略?

在路由中设置默认值不会将所有请求转换为JSON请求。

你想要的是确保你呈现的是JSON响应

除了你需要这样做之外,你在第一个选项中几乎拥有它

 before_filter :set_default_response_format private def set_default_response_format request.format = :json end 

这将在你的Base API控制器下进行,这样当它到达你的实际操作时,格式将永远是JSON。

如果你想返回404,或者如果格式不是:json则引发RouteNotFound错误,我会添加如下的路由约束:

需要JSON格式:

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

更多信息可以在这里找到: http : //edgeguides.rubyonrails.org/routing.html#request-based-constraints

第二种选择,使用路由格式。 如果用户明确请求XML格式,则不应该收到JSON响应。 他应该收到一条消息,说明此URL不符合XML格式或404。

顺便说一下,在我看来回应所有你应该做的事情是相当容易的。

 class FooController respond_to :xml, :json def show @bar = Bar.find(params[:id]) respond_with(@bar) end end