Rails - 如何通过 API 向 SendGrid 营销活动添加联系人

use*_*461 1 ruby rest ruby-on-rails rest-client sendgrid

我需要使用 SendGrid 发出 HTTP get 和 post 请求以将联系人添加到我们的帐户,但是他们的电子邮件营销功能似乎没有什么亮点。

归结为提出一些请求,但是我无法通过他们的身份验证步骤。

他们说要这样做

curl -X "GET" "https://api.sendgrid.com/v3/templates" -H "Authorization: Bearer Your.API.Key-HERE" -H "Content-Type: application/json"
Run Code Online (Sandbox Code Playgroud)

并使用 Rest-Client gem 我试图像这样发出身份验证请求......

username = 'username'
api_key = 'SG.MY_API_KEY'
key = Base64.encode64(username + ":" + api_key)
headers = {"Authorization" => "Bearer #{key}", "Content-Type" => "application/json"}
response = RestClient.get 'https://api.sendgrid.com/v3/templates', headers
Run Code Online (Sandbox Code Playgroud)

返回...

RestClient::Unauthorized: 401 Unauthorized: {"errors":[{"field":null,"message":"authorization required"}]}
Run Code Online (Sandbox Code Playgroud)

使用他们的 API的最终目标是添加联系人

我如何错误地提出这个获取请求?

use*_*461 5

我终于弄清楚了。为了将来参考,这是有效的代码......

require 'rest_client'
api_key = 'YOUR_API_KEY'
headers = {'Authorization' => "Bearer #{api_key}"}
data = {:email => 'email@website.com'}
response = RestClient.post 'https://api.sendgrid.com/v3/contactdb/recipients', [data].to_json, headers
Run Code Online (Sandbox Code Playgroud)