使用Rails和HTTParty向API POST JSON

128
我希望我的 Ruby on Rails 应用程序中的用户能够向我的外部工单管理系统 squishlist.com 提交工单。他们有一个 API 和以下说明。您需要进行身份验证并获取令牌,然后使用该令牌提交工单。来自 squishlist。
# get the token

https://api.squishlist.com/auth/?cfg=testcorp&user_key=privatekey&api_key=TEST-KEY-12345
  => {"token": "authtoken",
      "expires": "2010-06-16 13:31:56"}

# and then the ticket with the token

https://api.squishlist.com/rest/?cfg=testcorp&token=authtoken&method=squish.issue.submit&prj=demo
  POST data: {'issue_type': 1, 'subject': 'Hello, world.', 4: 'Open', 5: 10}

为了测试目的,我创建了一个控制器、路由和视图(页面)进行测试。在我的控制器上,我有以下内容:
require 'httparty'
require 'json'

class SubmitticketController < ApplicationController

    def submit_a_ticket

        @cfg = 'xxxsupport'
        @user_key = '4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b'
        @api_key = 'MrUser411'
        @project = 'excelm-manoke'
        @url_new_string = 'https://api.squishlist.com/auth/?cfg='+@cfg+'&user_key='+@user_key+'&api_key='+@api_key
        # https://api.squishlist.com/auth/?cfg=xxxsupport&user_key=4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b&api_key=MrUser411  - this is what is created by @url_new_string
        response =  HTTParty.get(@url_new_string.to_str)  #submit the string to get the token
        @parsed_and_a_hash = JSON.parse(response)
        @token = @parsed_and_a_hash["token"]


        #make a new string with the token

        @urlstring_to_post = 'https://api.squishlist.com/rest/?cfg='+@cfg+'&token='+@token+'&method=squish.issue.submit&prj='+@project

        #submit and get a result

        @result = HTTParty.post(@urlstring_to_post.to_str, :body => {:subject => 'This is the screen name', :issue_type => 'Application Problem', :status => 'Open', :priority => 'Normal', :description => 'This is the description for the problem'})

    end

end

然后我有一个页面,用于查看控制器操作的结果,它包含以下代码。

<p><%= @result %></p>

我知道它通常是有效的,因为我一路上收到了回应。我的json与示例不同,因为我在squishlist中定义了字段。有人能帮我解决这个问题吗?

我想真正的问题是我无法看到json的样子,也不知道它是否接近匹配。我对json并不了解。我应该使用一些可能很容易的东西吗?我应该使用ajax提交这个吗?非常感谢任何帮助。我喜欢这里的社区。

2个回答

309

我通过添加 .to_json 和一些标题信息来解决了这个问题。

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

12
一些API(如“GitLab API”)对“Accept”标头敏感。因此,标头应为:headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'}。请注意:标头不应转换为JSON,而应为散列格式。 - Devaroop
我部署了一个Rails引擎(打包成宝石)来调试Rails上的API,非常有用。你只需要挂载引擎并转到指定的网址,例如“localhost:3000/api_explorer”,就可以看到它了。这也是一种记录API的方式,从文件中读取Web服务规范。 这个宝石被命名为'api_explorer',仓库在 http://www.github.com/toptierlabs/api_explorer 欢迎任何评论或帮助改进该API :) - Tony
15
那不在文档中,这太荒谬了。 - Tyler Collier
1
想要像上面的格式一样推送包含90k条记录的集合数据。我能否在单个API调用中推送整个数据?请让我知道您的意见。 - Raju akula
2
:body => {}.to_json 后面加上 .to_json 解决了我在这个调用中的错误。 - user9869932
显示剩余2条评论

14

:query_string_normalizer选项也可用,它将覆盖默认规范化器HashConversions.to_params(query)

query_string_normalizer: ->(query){query.to_json}

太棒了!这允许将哈希值存储在“request.options [: body]”中,但发送正确的字符串。 这应该是问题的真正答案。 - freemanoid
该选项也可以在包括HTTParty的类中通过query_string_normalizer类方法设置为默认值,请参见:http://www.ruby-doc.org/gems/docs/h/httparty2-0.7.10/HTTParty/ClassMethods.html#method-i-query_string_normalizer - Fryie
可能还需要设置内容类型头:http://www.ruby-doc.org/gems/docs/h/httparty2-0.7.10/HTTParty/ClassMethods.html#method-i-headers - Fryie
1
应该使用“query_string_normalizer”来处理查询字符串,而不是POST数据。 - josephrider
ruby-doc.org 的链接已经失效,文档现在在 httparty doc 上。 - Yacc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接