4
votes

I'm trying to build a JSON API for my Rails application, and have written the following method:

  def create
    organization = Organization.find(params[:organization][:node_id])
    node = organization.nodes.build(nodes_params.except[:id])
    if node.save
      render json: node, status: :ok
    else
      render json: node, status: :bad_request
    end
  end

Trying the method in Postman returns the error: "Can't verify CSRF token authenticity". Based on this post I added the code below to the base controller. Unfortunately this made no difference. Does anyone understand the cause of the error?

protect_from_forgery
skip_before_action :verify_authenticity_token, if: :json_request?
private
  def json_request?
    request.format.json?
  end
1
Which rails environment do you use to test your controller's method?DreamWalker
I'm using the development environment (using Cloud9 IDE). Right now trying to figure out the post @MaxWilliams suggested.Nick
If you want just to test the organization creation with json request try starting rails in test environment.DreamWalker
Thanks, I got it to work with protect_from_forgery with: :null_session, :if => Proc.new { |c| c.request.format == 'application/json' }Nick

1 Answers

4
votes

As per comment on application_controller.rb you need to put this line protect_from_forgery with: :null_session.

It will better if you make one more root controller for only all API's controller which is inherited from ApplicationController. i.e

class Api::ApiController < ApplicationController
  #TODO
  protect_from_forgery with: :null_session
end

Other API's controllers

class Api::V1::AddressesController < Api::ApiController
  #TODO
end

This controller class can help you to make changes only for API's root rather than whole application. You can also use this controller to make D.R.Y actions between various versions of API's.