如何格式化HTTParty POST请求?

问题描述 投票:0回答:1

我一直在为我正在处理的项目使用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进行调用而没有JSON,都会得到此错误。因此,我假设上面的代码在进行API调用时未传递任何JSON。我的JSON格式不正确吗?我甚至可以正确格式化.post调用吗?任何帮助表示赞赏! :)

api_test()方法只对example.com进行POSt调用即可,并且有效(节省了理智)。

ruby-on-rails ruby api post httparty
1个回答
0
投票

只需在类中使用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: 'dontStealMePls').cc_query

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

© www.soinside.com 2019 - 2024. All rights reserved.