英文:
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
}
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论