1

Im implementing a Rest API on Ruby on Rails. So i want to respond to all requests in json format. I made this:

include ActionController::MimeResponds


before_filter :force_json

def force_json
  response.format = "json"
  #also tried
  # response.content_type = Mime[:json]
end

Those two ways didn't worked. It gives me an html page with errors. Also is there a way to implement this for the whole api and not for each class? Thanks!

Fausto Sanchez
  • 483
  • 1
  • 7
  • 21
  • checkout the answer specified in http://stackoverflow.com/questions/23946630/rails-4-how-to-render-json-regardless-of-requested-format – Prasad Surase Jun 09 '16 at 13:19
  • While you most certainly *can* respond to all requests in json format, what you *should* do is that block any requests that do not request JSON as a format. This answer: http://stackoverflow.com/a/3679735/476712 illustrates how to do that. – lorefnon Jun 09 '16 at 13:55

2 Answers2

1

If you use the responders gem, you can define this at the top of your class:

class PostsController < ApplicationController
  respond_to :json
  ...

Then this controller will respond using JSON by default.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • Even using this gem and adding that code, if i request Content-Type text/html i get an html site. I want to get an error json – Fausto Sanchez Jun 09 '16 at 02:00
1

If you want it to happen application wide, you can do something like this in the application controller.

class ApplicationController < ActionController::Base
  before_action :force_json

  def force_json
     request.format = :json
  end
end
Larson B
  • 309
  • 2
  • 12