【问题标题】:How to format HTTParty POST request?如何格式化 HTTParty POST 请求?
【发布时间】:2019-12-06 22:01:11
【问题描述】:

我一直在为我正在处理的项目使用 API 调用,当我尝试将一些 JSON 传递给 POST 请求时遇到问题。该调用在 Postman 中有效,但我无法弄清楚如何在 Ruby 中对其进行格式化。这是我的代码:

require 'httparty'
require 'json'
require 'pp'
#use the HTTParty gem
include HTTParty
#base_uri 'https://app.api.com'
#set some basic things to make the call,
@apiUrl = "https://app.api.com/"
@apiUrlEnd = 'apikey=dontStealMePls'
@apiAll = "#{@apiUrl}#{@apiUrlEnd}"
@apiTest = "https://example.com"

def cc_query
  HTTParty.post(@apiAll.to_s, :body => {
    "header": {"ver": 1,"src_sys_type": 2,"src_sys_name": "Test","api_version": "V999"},
    "command1": {"cmd": "cc_query","ref": "test123","uid": "abc01",  "dsn": "abcdb612","acct_id": 7777}
    })
end

def api_test
  HTTParty.post(@apiTest.to_s)
end

#pp api_test()
pp cc_query()

这段代码给了我这个错误:

{"fault"=>
  {"faultstring"=>"Failed to execute the ExtractVariables: Extract-Variables",
   "detail"=>{"errorcode"=>"steps.extractvariables.ExecutionFailed"}}}

我知道这个错误,因为如果我尝试在呼叫正文中没有任何 JSON 的情况下(通过 Postman)进行呼叫,我会得到它。因此,我假设我上面的代码在进行 API 调用时没有传递任何 JSON。我的 JSON 格式是否不正确?我是否正确格式化了 .post 调用?任何帮助表示赞赏! :)

api_test() 方法只是对 example.com 进行 POST 调用,它就可以工作(节省我的理智)。

【问题讨论】:

    标签: ruby-on-rails ruby api post httparty


    【解决方案1】:

    只需在类中使用 HTTParty 作为 mixin:

    require 'httparty'
    
    class MyApiClient
      include HTTParty
      base_uri 'https://app.api.com'
      format :json
      attr_accessor :api_key
    
      def initalize(api_key:, **options)
        @api_key = api_key
        @options = options
      end
    
      def cc_query
        self.class.post('/', 
          body: {
            header: {
              ver: 1,
              src_sys_type: 2,
              src_sys_name: 'Test',
              api_version: 'V999'
            },
            command1: {
              cmd: 'cc_query',
              ref: 'test123',
              uid: 'abc01',
              dsn: 'abcdb612',
              acct_id: 7777
            }
          }, 
          query: {
            api_key: api_key
          }
        ) 
      end
    end
    

    示例用法:

    MyApiClient.new(api_key: 'xxxxxxxx').cc_query
    

    当您使用format :json时,HTTParty 会自动设置内容类型并处理 JSON 编码和解码。我猜这就是你失败的地方。

    【讨论】:

    • 这无疑为我指明了正确的方向,因为与上面的错误相比,我收到了 Invalid API Key 错误。我只是有点困惑,当我在使用示例用法时输入 API 密钥时,我收到了一个不正确的 API 密钥错误(我正在粘贴我拥有的密钥)。有什么帮助吗?
    • 如果不了解 API,我真的无能为力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多