Respond with json format to all formats requests - ruby-on-rails

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!

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

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.

Related

How to set content type for JSON API in Rails 5 API only app

Follow the specification to use the JSON api, the content type must be set to application/vnd.api+json; however, setting the ContentType in every action in the controller seems tedious (see code below).
def foo
response.headers['Content-Type'] = 'application/vnd.api+json'
# ...
end
Is there a better way to achive the same result? Since this is an API only app is this possible to set content type at application level?
You can use the before_action directive:
class ApplicationController < ActionController::API
before_action :set_headers
def set_headers
response.headers['Content-Type'] = 'application/vnd.api+json'
end
end

Default client Content-Type under api-namespace in Rails?

How do I set a default Content-Type for all incoming requests to my Rails app under a given namespace?
In my case I have an /api namespace that always expects JSON, but I don't want to force the clients to always set it (they are of cause welcome to do so if they please in which case the Rails app should adhere to the set Content-Type). So it should just default to application/json.
This will make testing with curl etc A LOT EASIER.
How do I do that?
One way is to specify before action in API controller and set JSON format:
before_filter :default_request_format
private
def default_request_format
request.format = :json
end
or you can specify JSON format in routes.rb.
Let all your API-Controller inherit from a Api::Controller class, which only respond_to :json
Example:
class Api::Controller < ActionController::Base
respond_to :json
before_filter :default_request_format
private
def default_request_format
request.format = :json
end
end
Now your other Api Controllers can Inherit from it and will automatically respond with JSON.
For example you have a model called 'FooBar':
class Api::FooBarsController < Api::Controller
def index
#foobars = FooBar.all
respond_with(#foobars)
end
end

UnknownFormat in Devise::SessionsController#new

I have a Rails 4 app (that was upgraded from Rails 3) in which I decided to delete one of the controllers. I then moved the methods from that deleted controller to the ApplicationController, which included before_filter :authenticate_user!
Here's what my ApplicationController looks like now:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate_user!
respond_to :json
def index
gon.rabl
#user = current_user
gon.rabl "app/views/users/show.json.rabl", as: "current_user"
end
def markdown
require 'redcarpet'
renderer = Redcarpet::Render::HTML.new
extensions = {}
Redcarpet::Markdown.new(renderer, extensions)
end
helper_method :markdown
end
Now, I'm getting this error:
ActionController::UnknownFormat in Devise::SessionsController#new
I think this might be due to the fact that you have set your application controller to respond only to json. If your Devise Controller inherits from ApplicationController (I think this is the default), then it will expect to see a content-type: json header, or your urls must all end in .json
You shouldn't have the index method defined in application_controller. You should move it to the appropriate controller. If this is something you want to do before every action you might want to try something like this:
before_action :gon_user, only: :index
private
def gon_user
gon.rabl
#user = current_user
gon.rabl "app/views/users/show.json.rabl", as: "current_user"
end
Though i've to be honest that i'm not sure about the gon stuff, can't remember if it was for moving data from ruby to javascript or for responding to ajax/json request.
Thanks Slicedpan. Got me thinking about a
respond_to :json
Used in my Rails Application as an API with Angular. As in my Rails controllers I use for requests from my Angular Services.
respond_with
In my case I ended up adding html to the respond_to:
respond_to :json, :html
The Default Mime Types can be seen here:
http://apidock.com/rails/Mime

How to minify JSON output in Rails?

I am using .json.erb views instead of calling to_json method.
I've found several advices concerning JSON output minification. Ones tell about zipping all the output of web application, others recommend to use after filter or before render but they do not explain how to shrink spaces and tabs between JSON elements and where to take JSON input from and where to put the minified result. The third advices tell strictly about minifying JavaScript.
The easiest way is just to get Ruby to parse the whole response and spit it back out again using an after_filter. Try the following code in app/controllers/application_controller.rb.
class ApplicationController < ActionController::Base
after_filter :minify_json
private
def minify_json
response.body = JSON.parse(response.body).to_json if request.format.json?
end
end
If you decide that you want the JSON beautified instead of minified, you can use this code:
class ApplicationController < ActionController::Base
after_filter :beautify_json
private
def beautify_json
response.body = JSON.pretty_generate(JSON.parse(response.body)) if request.format.json?
end
end
Or, you could allow the requester to specify using a parameter:
class ApplicationController < ActionController::Base
after_filter :format_json
private
def format_json
if request.format.json?
json = JSON.parse(response.body)
response.body = params[:pretty] ? JSON.pretty_generate(json) : json.to_json
end
end
end

respond to only json in rails

In my rails app which is json only, I want to send a 406 code whenever someone calls my rails app with accept header set to anything except application/json. I also want it to send a 415 when I get the content type set to anything except application / json
My controllers have respond_to :json put on them. I only render json in all actions. However how do I ensure that I return error code 406/415 for all calls for anything that is called for all other accept headers/content-type and with format set to anything except json.
Eg. If I my resource is books/1 I want to allow
books/1.json or books/1 with application/json in accept header and content type
Any ideas on how I can do these two actions?
Basically, you can limit your responses in two ways.
First, there is respond_to for your controllers. This would automatically trigger a 406 Not Acceptable if a request for a format is made which is not defined.
Example:
class SomeController < ApplicationController
respond_to :json
def show
#record = Record.find params[:id]
respond_with #record
end
end
The other way would be to add a before_filter to check for the format and react accordingly.
Example:
class ApplicationController < ActionController::Base
before_filter :check_format
def check_format
render :nothing => true, :status => 406 unless params[:format] == 'json' || request.headers["Accept"] =~ /json/
end
end
You can do it with a before_filter in ApplicationController
before_filter :ensure_json_request
def ensure_json_request
return if params[:format] == "json" || request.headers["Accept"] =~ /json/
render :nothing => true, :status => 406
end
On rails 4.2+ respond_to has been removed, so unless you want to import the full responders gem just for this, your best bet is to roll your own. This is what I'm using in my rails 5 api:
class ApplicationController < ActionController::API
before_action :force_json
private
def force_json
# if params[_json] it means request was parsed as json
# if body.read.blank? there was no body (GET/DELETE) so content-type was meaningless anyway
head :not_acceptable unless params['_json'] || request.body.read.blank?
end
end

Resources