rails与第三方API交互?

时间:2015-10-29 09:12:44

标签: ruby-on-rails api redmine

我的应用经常需要使用第三方API并使用大量来自响应的数据, redmine 就是其中之一。(可能会使用 3~4 3rd API) 我尝试使用 Net :: HTTP ,例如:

我的控制员:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  def get_request (request)
    uri = URI.parse(request)
    res = Net::HTTP.get_response(uri)
  end
end

require 'net/http'
class LogsController < ApplicationController
    def new
        redmine_api_key = 'key=' + 'my key'
        redmine_api_url = 'http://redmine/users/1.json?'
        request_user = redmine_api_url + redmine_api_key
        @user_get = get_request(request_user)
        @user_data = JSON.parse(@user_get.body)['user']
    end
end

我的观点:(只是测试以显示我得到的东西)

<div class="container-fluid">

  <h1>Account data</h1>

  <%= @user_data %><br>

  <%= @user_get.code %><br>
  <%= @user_get.message %><br>
  <%= @user_get.class.name %><br>

  <div class="table-responsive">
    <table class="table">
      <thead>
        <th>ID</th>
        <th>login</th>
        <th>firstname</th>
        <th>lastname</th>
        <th>mail</th>
        <th>created_on</th>
        <th>last_login_on</th>
        <th>api_key</th>
      </thead>
      <tbody>
          <tr>
            <td><%= @user_data['id'] %></td>
            <td><%= @user_data['login'] %></td>
            <td><%= @user_data['firstname'] %></td>

            <td><%= @user_data['custom_fields'][0]['id'] %></td>
          </tr>
      </tbody> 
    </table>
  </div>
</div>

我可以获得我想要的数据,但我不知道我的方法是正确的还是愚蠢的(我的意思是一些代码,如JSON.parse(@ user_get.body)[&#39; user&# 39] )。 我做了一些研究,在一些文章中,他们说:如果应用程序使用多个API,写入 lib文件夹是一种更好的方法。 并且有人建议:从第3个API获取所有数据,然后创建自己的数据库来管理数据。 但我无法找到有关如何使用第三方API的完整教程...

1 个答案:

答案 0 :(得分:1)

因为您可能需要经常对第三方进行API调用。您可以在lib文件夹中编写该代码。 在Api.rb

module Api

def self.do_get_request(url, params={})
  request = request + '?' + params.to_query
  uri = URI.parse(request)
  response = Net::HTTP.get_response(uri)
  JSON.parse(response) if response
end

现在在你的控制器中你可以调用这个函数:

require 'net/http'
class LogsController < ApplicationController
    def new
        params = {key: 'my key'}
        redmine_api_url = 'http://redmine/users/1.json'
        response = Api.do_get_request(redmine_api_url, params)
        @user_data = response['user'] if response.present?
    end
end

do_get_request可以是一般功能。您还可以在lib中的API模块中创建第三方特定功能,然后您不必在每个请求结束时添加密钥。 无论响应是什么,您总是使用JSON.parse解析它,因此可以将代码推送到Api模块。

如果您经常使用此数据,则可以将其存储在数据库中。为此,您必须创建一个模型(阅读轨道指南:http://guides.rubyonrails.org/getting_started.html)。

相关问题