我想限制将所有API控制器重定向到JSON路径的请求。我想使用重定向,因为URL也会根据响应而改变。
一种选择是使用before_filter
,该请求将请求重定向到相同的动作但强制使用JSON格式。该示例尚未运行!Rails:将API请求限制为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
...
,你会推荐哪种策略?
+1的评论开始。根据我的经验,添加格式并不容易,尽管Rails使其易于实现。 API设计者仍然需要考虑支持其他格式的含义以及所有的影响。 –