简体   繁体   English

如何在Httparty中构建json参数

[英]How to build json params in Httparty

I have to send a post request in httparty and get response my json params are 我必须在httparty中发送发布请求并获得响应,我的json参数是

    {
  "webhook": {
    "topic": "shop/update",
    "address": "http://2350d6c0.ngrok.io/shopify_stores/update_shop_info",
    "format": "json"
  }
}

And i am using httparty params as 我正在使用httparty params作为

begin
          response = HTTParty.post("#{url}",
          { 
            :body => [
                {
                    "webhook" => {
                        "topic" => "shop\/update",
                        "address" => "http:\/\/15ec3a12.ngrok.io\/shopify_stores\/update_shop_info", #place your url here
                        "format" => "json" 
                   }
                }
                        ].to_json,
            :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'}
          })
          byebug
        rescue HTTParty::Error

    end

but it repsonse is 但它是

Required parameter missing or invalid 必填参数缺失或无效

The smoothest way to work with HTTParty is by creating clients instead of using it in a procedural fashion. 使用HTTParty的最流畅的方法是创建客户端,而不是以过程方式使用它。

class MyApiClient
  include HTTParty
  base_uri 'example.com'

  format :json

  # this is just an example of how it is commonly done
  def initalize(api_key = nil)
    @api_key = api_key
  end

  def post_something(data)
    self.class.post("/some_path", data)
  end
end

This will let you do: 这将使您能够:

client = MyApiClient.new()
puts client.post_something({ foo: "bar" })

You don't need handle setting headers or encoding the body - HTTParty will handle that for you. 您不需要处理设置标头或对正文进行编码-HTTParty会为您处理。 Thats kind of the whole point of the library - if you want to grunt it out procedurally just use Net::HTTP which is part of the stdlib. 多数民众赞成在整个库的要点-如果您要按程序使用它,只需使用Net :: HTTP ,它是stdlib的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM