Ruby API - Accept parameters and execute script

坚强是说给别人听的谎言 提交于 2019-12-11 13:09:34

问题


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



来源:https://stackoverflow.com/questions/36584789/ruby-api-accept-parameters-and-execute-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!