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

我需要使用SendGrid进行HTTP get和post请求以向我们的帐户添加联系人,但是他们的电子邮件营销function似乎没有gem。

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

他们说这样做

curl -X "GET" "https://api.sendgrid.com/v3/templates" -H "Authorization: Bearer Your.API.Key-HERE" -H "Content-Type: application/json" 

并使用Rest-Client gem我正在尝试进行身份validation请求……

 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 

返回……

 RestClient::Unauthorized: 401 Unauthorized: {"errors":[{"field":null,"message":"authorization required"}]} 

使用其API的最终目标是添加联系人 。

我怎么错误地提出这个请求?

我最终搞清楚了。 为了将来参考,这里的代码有效…

 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 

要通过API向您的SendGrid帐户添加营销联系人,请参阅https://sendgrid.api-docs.io/v3.0/contacts-api-recipients/add-recipients上的文档。

您可以在页面的“代码生成”部分中看到示例代码。

 require 'uri' require 'net/http' url = URI("https://api.sendgrid.com/v3/contactdb/recipients") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer <>' request["content-type"] = 'application/json' request.body = "[{\"email\":\"example@example.com\",\"first_name\":\"\",\"last_name\":\"User\",\"age\":25},{\"email\":\"example2@example.com\",\"first_name\":\"Example\",\"last_name\":\"User\",\"age\":25}]" response = http.request(request) puts response.read_body