Search code examples
ruby-on-railsrubyrestsendgridrest-client

Rails - How to add contacts to SendGrid marketing campaigns via API


I need to make HTTP get and post requests with SendGrid to add contacts to our account, however there doesn't seem to be a gem for their email marketing functionality.

It boils down to making a few requests however I can't get past their authentication step.

They say to do this

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

And using the Rest-Client gem I'm trying to make the authentication request like so...

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

which returns...

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

The ultimate objective of using their API is to add contacts.

How am I incorrectly making this get request?


Solution

  • I ended up figuring it out. For future reference, here's the code that worked...

    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