簡體   English   中英

如何格式化 HTTParty POST 請求?

[英]How to format HTTParty POST request?

我一直在為我正在處理的項目處理 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 調用並且它可以工作(保存我的理智)。

只需使用 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 編碼和解碼。 我猜這就是你失敗的地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM