Ruby API - 接受参数并执行脚本

Ruby API - Accept parameters and execute script

我创建了一个 rails 项目,其中包含一些我想作为 API 执行的代码。我正在使用 rails-api gem.

文件位于 app/controllers/api/stats.rb。

我希望能够通过访问 link 来执行该脚本和 return json 输出 - http://sampleapi.com/stats/?location=USA?state=Florida

我应该如何配置我的项目,以便在我访问 link 时它运行我的代码?

文件应命名为 stats_controller.rb app/controllers/api/stats_controller.rb

您可以创建一个 index 方法,您可以在其中添加您的代码

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

在文件 config/routes.rb 中你应该添加

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

要访问 url 中的参数,您可以在索引方法中使用 params[:location] ,params[:state]

以下是我的看法:

在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

在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

让我知道这是否有效