Configuring Routes for the API
protect_from_forgery with: :exception to
protect_from_forgery with: :null_session.
CSRF is usually checked on non-GET requests, and by default if no CSRF token is
provided Rails will throw an exception, causing our requests to fail. The
:null_session setting will clear out our session variables instead of causing
an exception to be thrown.
Finally, per the API spec we're adhering to, we want our clients to be able to submit their payloads using lowerCamelCase and our responses should be lowerCamelCase as well. Since we'll be using Jbuilder for rendering JSON responses, we can use an initializer to configure Jbuilder to output all JSON keys in lowerCamelCase.
Create an initializer in
config/initializers/jbuilder.rb with the following code:
Jbuilder.key_format camelize: :lower
In order to keep using snake_case throughout our app, we'll have to convert
any incoming parameters in our application to snake_case. This can be achieved
by using a before_action filter
Create the following private method in
def underscore_params! params.deep_transform_keys!(&:underscore) end
Then, use a
before_action filter in
application_controller.rb to apply the filter
to every request.
Changing our parameters to snake_case has a couple advantages, it keeps our code
looking clean and Ruby-ish (instead of having to reference lowerCamelCase
parameters), and it allows us to pass our parameters to model methods like
update_attributes on our models without having to worry about case conversion.
respond_to :json after the
protect_from_forgery line in
This configuration ensures our controllers will respond with the correct MIME type and enables 3rd party controllers in gems (like Devise controllers) to respond using JSON.