如何访问没有Ruby gem的API服务?

时间:2016-05-27 23:49:28

标签: ruby-on-rails ruby curl

所以我想从我的Rails应用程序中访问只有barebones RESTful API的Glot.io。

Glot.io要求我创建一个帐户并为我生成一个API密钥 - 非常标准。

在高层,我最好的办法是什么?

创建一个名为glot.rb的初始化文件,我应该包含哪些内容?我的ENV_VARS只能访问API服务吗?或者我不需要那个?

然后使用可用的文档to CREATE a snippet,实际执行此操作的最佳方法是什么?我应该使用像curb这样的CURL gem重新创建此POST请求吗?

curl --request POST \
     --header 'Authorization: Token 99090-7abba-12389abcde' \
     --header 'Content-type: application/json' \
     --data '{"language": "python", "title": "test", "public": false, "files": [{"name": "main.py", "content": "print(42)"}]}' \
     --url 'https://snippets.glot.io/snippets'

如果是这样,上面的内容会是什么样的?

理想情况下,我希望能够对该方法进行高级概述,然后介绍一些我可能会如何进行的代码片段。

1 个答案:

答案 0 :(得分:2)

我会创建一个库(或者创建我自己的gem,或者如果只是在这里使用它,那么在/ lib中)使用net / http。

http://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTP.html

这是一个非常基本的例子,可以通过多种方式完成。此示例将允许您实例化SnippetApi并设置URL。然后,您可以调用new_snippet,它将获取您提供的URL,并进行API调用。

要继续扩展,您可以将 def new_snippet 更改为 def new_snippet(data),然后通过您的电话提供数据。

注意:文件名应为 snippet_api.rb ,以确保" rails magic"适用于自动加载。

LIB / snippet_api.rb

require 'uri'
require 'net/http'
require 'net/https'

class SnippetApi

   def initialize(url, api_token = ENV['API_TOKEN'])
      @url = url
      @api_token = api_token
    end

    def url
      @url
    end

    def api_token
      @api_token
    end

  def new_snippet

    # https://snippets.glot.io/snippets
    uri = URI.parse(self.url)
    post_object = {'language': 'python', 'title': 'test', 'public': false, 'files': [{'name': 'main.py', 'content': 'print(42)'}]}

    https = Net::HTTP.new(uri.host, uri.port)
    https.use_ssl = true
    req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' => 'application/json', 'Authorization': "Token #{self.api_token}"})
    req.body = "[ #{post_object} ]"
    res = https.request(req)
    puts "Response #{res.code} #{res.message}: #{res.body}"
  end

end

用法

2.3.0 :001 > snippet_api = SnippetApi.new('https://snippets.glot.io/snippets')
 => #<SnippetApi:0x00000003b6bc20 @url="https://snippets.glot.io/snippets"> 
2.3.0 :002 > snippet_api.new_snippet
Response 404 Not Found: {"message":"Wrong auth token"}

要确保加载/ lib中的文件,请务必将其添加到application.rb:

config.autoload_paths += Dir["#{config.root}/lib/**/"]

使用API​​令牌

[brian@...]$ export API_TOKEN='token from env'

2.3.0 :001 > snippet_api = SnippetApi.new('https://snippets.glot.io/snippets')
 => #<SnippetApi:0x0000000342e8e0 @url="https://snippets.glot.io/snippets", @api_token="token from env"> 
2.3.0 :002 > snippet_api.api_token
 => "token from env" 
2.3.0 :003 > snippet_api = SnippetApi.new('https://snippets.glot.io/snippets','from init')
 => #<SnippetApi:0x000000033a60d0 @url="https://snippets.glot.io/snippets", @api_token="from init"> 
2.3.0 :004 > snippet_api.api_token
 => "from init" 

编辑1:添加了有关加载lib文件的信息。