HTTP with ruby

In my job we recently decided to use an email management tool called getResponse which I started to build the adapter to user with its API.

One of the first things I did was to test the creation of an email with curl:

curl -X POST https://api3.getresponse360.pl/v3/contacts
  -d '{"email": "adnilson@frontline.cv",
       "campaign": {
         "campaignId": "G"
      } }'
  -H 'Cache-Control: no-cache'
  -H 'Content-Type: application/json'
  -H 'X-Auth-Token: api-key 23902okjwefiKJPJjknowiejoijoij'
  -H 'X-DOMAIN: info.hustle.de'

With Ruby’s Net::HTTP library would be like this:

require 'net/http'
require 'json'

uri = URI.parse('https://api3.getresponse360.pl/v3/contacts')

header = {
  'Content-Type': 'application/json',
  'X-Auth-Token': 'api-key 23902okjwefiKJPJjknowiejoijoij',
  'X-DOMAIN': 'info.hustle.de',
  'Cache-Control': 'no-cache',
}
user = {
  "email": "adnilson@frontline.cv",
  "campaign": {"campaignId": "G"}
}

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = user.to_json
http.use_ssl = true

response = http.request(request)

I had some problems with the post request which was not sending the correct data, maybe something was changed or lost meanwhile.
A colleague of mine suggested the Faraday gem.
I was with a little resistance since the least gems we use the better but we were in a hurry and it is very light I took a shot.

require 'faraday'
require 'json'

conn = Faraday.new(url: 'https://api3.getresponse360.pl/v3/contacts')

user = {
  "email": "adnilson@frontline.cv",
  "campaign": {"campaignId": "G"}
}
conn.post do |req|
  req.headers['Content-Type'] = 'application/json'
  req.headers['X-Auth-Token'] = 'api-key 23902okjwefiKJPJjknowiejoijoij'
  req.headers['X-DOMAIN'] = 'info.hustle.de'
  req.headers['Cache-Control'] = 'no-cache'

  req.body = user.to_json
end

That’s it. See you next week.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s