Search code examples
ruby-on-railsrubyapiposthttparty

How to format HTTParty POST request?


I've been playing around with API calls for a project I'm working on and I'm getting a problem when I try to pass some JSON to a POST request. The call works in Postman, but I just can't figure out how to format it in Ruby. Here's my code:

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()

This code gives me this error:

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

I know that error because I would get it if I tried to make a call without any JSON in the body of the call (through Postman). So from that I assume that my code above is not passing any JSON when making an API call. Am I formatting my JSON incorrectly? Am I even formatting the .post call correctly? Any help is appreciated! :)

the api_test() method just makes a POSt call to example.com and it works (saving my sanity).


Solution

  • Just use HTTParty as a mixin instead in a class instead:

    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
    

    Example usage:

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

    When you use format :json HTTParty will automatically set the content type and handle JSON encoding and decoding. I'm guessing thats where you failed.