Rails API: make application controller serve JSON

666 views Asked by At

This tutorial, React + Flux Backed by Rails API, by Fancy Pixel, says:

Now we need to change the application controller so that it inherits from ActionController::API, and kiss the protect_from_forgery goodbye. Since we are serving only JSON, it makes sense to add

respond_to :json

to the applciation controller, helps DRYing all out. While we are at it, we might as well delete the assets and views folders, we won’t need them.

I am not sure about what I am supposed to do.

This is what my application controller looks like:

class ApplicationController < ActionController::API
    respond_to :json
end

Is it correct?

Also, should I keep or remove protect_from_forgery with: :null_session :

class ApplicationController < ActionController::API
  protect_from_forgery with: :null_session
  respond_to :json
end
1

There are 1 answers

3
Zubatman On BEST ANSWER

To communicate from any Rails Backend (not even necessarily just an API) all you have to do is write the following in your API's controller(s):

class Api::V1::SearchController < ApplicationController
#Run an Authentication Method on their API Key
before_action :authenticate

  def search
    #Performs your backend logic
    content_array = get_content_method
    render :json => content_array
    #Renders up a JSON that you can retrieve with an HTTP get request
  end
end

Also on the topic of serving data, you can send your params in an obscured JSON, allowing you to hide your API Key, thus protecting you from unwanted access. My favorite way of doing this is by using the .to_query method to send over the necessary params. I have done it like so:

BASE_URL = "http://yourwebsite.com/search?"

def generate_search_url(params)
    BASE_URL + params.to_query + "&Api-Key=#{ENV['API-KEY']}"
end

This way you can work with the data you're given just like any other params, but it would be more difficult to abuse the API without a granted key.