Skip to content

Instantly share code, notes, and snippets.

@rocLv
Created March 28, 2017 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rocLv/4f6cec67db1026d67b7278437ae81cfb to your computer and use it in GitHub Desktop.
Save rocLv/4f6cec67db1026d67b7278437ae81cfb to your computer and use it in GitHub Desktop.
Rails 4 - Respond only to JSON and not HTML
I believe there are 2 parts here:
1) json only requests in rails
2) json only responses in rails
1) Configure your application controller to ensure json requests only
# app/controller/application_controller.rb
before_action :ensure_json_request
def ensure_json_request
return if request.format == :json
render :nothing => true, :status => 406
end
2) Configure your Rails API routes to ensure json responses only
# config/routes.rb
MyApp::Application.routes.draw do
namespace :api, constraints: { format: 'json' } do
namespace :v1 do
resources :posts
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment