Ruby API - Accept parameters and execute script

2019-08-15 10:51发布

问题:

I have created a rails project that has some code that I would like to execute as an API. I am using the rails-api gem.

The file is located in app/controllers/api/stats.rb.

I would like to be able to execute that script and return json output by visiting a link such as this - http://sampleapi.com/stats/?location=USA?state=Florida.

How should I configure my project so that when I visit that link it runs my code?

回答1:

the file should be called stats_controller.rb app/controllers/api/stats_controller.rb

you can create an index method where you can add your code

  class API::StatsController < ApplicationController  
    def index
       #your code here
       render json: your_result
    end    
  end

in the file config/routes.rb you should add

get 'stats' => 'api/stats#index', as: 'stats'

To access the params in the url you can do it in your index method with params[:location] ,params[:state]



回答2:

Here's how I would think of this:

in app/controllers/api/stats_controller.rb

module Api
  class StatsController
    def index
      # your code implementation
      # you can also fetch/filter your query strings here params[:location] or params[:state]
      render json: result # dependent on if you have a view
    end
  end
end

in config/routes.rb

# the path option changes the path from `/api` to `/` so in this case instead of /api/stats you get /stats
namespace :api, path: '/', defaults: { format: :json } do
  resources :stats, only: [:index] # or other actions that should be allowed here
end

Let me know if this works