从Rails使用HTTParty POST到VoilaNorbert API

huangapple go评论75阅读模式
英文:

POST to VoilaNorbert API from Rails with HTTParty

问题

我正在尝试使用HTTParty Rails gem将数据POST到标准的VoilaNorbert搜索API端点

response = HTTParty.post(
  'https://api.voilanorbert.com/2018-01-08/search/name',
  query: {
    'name': 'Elon Musk',
    'domain': 'https://www.tesla.com/'
  },
  headers: {
    'Content-Type': 'application/json',
    'Authorization': VOILANORBERT_API_TOKEN
  }
)

然而,当我尝试这个简单的请求时,我得到以下响应:

=> {"name"=>["This field is required."]}

我理解的是上面的查询块应该传递name字段,而在这种情况下name是"Elon Musk"。

我在这里漏掉了什么?

英文:

I am trying to POST data to the standard VoilaNorbert search API endpoint using the HTTParty Rails gem:

response = HTTParty.post(
  'https://api.voilanorbert.com/2018-01-08/search/name',
  query: {
    'name': 'Elon Musk', 
    'domain': 'https://www.tesla.com/'
  },
  headers: {
    'Content-Type': 'application/json',
    'Authorization': VOILANORBERT_API_TOKEN
  }
)

However, when I try this simple request, I get the response:

 => {"name"=>["This field is required."]} 

My understanding is that the query block above is supposed to pass along the name field, which in this case is "Elon Musk".

What am I missing here?

答案1

得分: 1

经过一些试验和错误,我成功地意识到需要将负载更改为将表单数据发送到请求的主体中,而不是作为查询参数发送。这需要使用body块来编码表单字段,以及请求中的多部分方法,指示正在上传数据。

response = HTTParty.post(
  'https://api.voilanorbert.com/2018-01-08/search/name',
   body: {
     name: 'Elon',
     domain: 'https://www.tesla.com/'  
   },
   multipart: true,
   headers: {
     'Content-Type': 'application/json',
     'Authorization': VOILANORBERT_API_TOKEN
   }
)
英文:

After some trial and error, I succeeded by realizing I needed to change the payload to send form-data in the body of the request rather than as query params. This requires using the body block to encode form fields, as well as the multipart method on the request indicating that data is being uploaded.

response = HTTParty.post(
  'https://api.voilanorbert.com/2018-01-08/search/name',
   body: {
     name: 'Elon',
     domain: 'https://www.tesla.com/'  
   },
   multipart: true,
   headers: {
     'Content-Type': 'application/json',
     'Authorization': VOILANORBERT_API_TOKEN
   }
)

huangapple
  • 本文由 发表于 2020年1月4日 11:55:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/59587746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定