1

This is the curl request I'd like to perform:

curl --request GET --url 'https://us8.api.mailchimp.com/3.0/' --user 'anystring:<apikey>'

Running this curl command from the command line, I get a bunch of JSON, which is what I want.

I'm trying to perform this same request using Faraday. This is what I've tried:

conn = Faraday.new "https://us8.api.mailchimp.com/3.0/" do |faraday|
  faraday.adapter Faraday.default_adapter
end
conn.basic_auth('apikey', <apikey>)

response = conn.get

puts response.body # => "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>301 Moved Permanently</title>\n</head>...

How do I get JSON instead of the html I'm seeing in response.body?

FellyTone84
  • 665
  • 8
  • 18

3 Answers3

4

This ended up working for me:

conn = Faraday.new('https://us8.api.mailchimp.com/3.0/') do |c|
  c.use FaradayMiddleware::ParseJson, content_type: "application/json"
  c.use Faraday::Adapter::NetHttp
end

conn.basic_auth('apikey', <api_key>)

response = conn.get('campaigns')

puts response # => json blob
FellyTone84
  • 665
  • 8
  • 18
1

A much more concise option is to manually encode your credentials into Base64 and set the Authorization header manually. This saves a few lines of code and keeps it in a similar format to regular Faraday requests (i.e. Faraday.post <URL>, <BODY>, <HEADERS>).

i.e.

encoded_credentials = Base64.encode64('apikey:api_secret').chomp
Faraday.post 'http://myhost.local/my_url', {}, authorization: "Basic #{encoded_credentials}"
XtraSimplicity
  • 5,704
  • 1
  • 28
  • 28
0

This is the farday code for curl operations using ruby gem.

    def contacts
     response = JSON.parse(params)

     @conn = Faraday.new('https://domain.example.com/api/v2/') do |farday|
      farday.use FaradayMiddleware::ParseJson, content_type: "application/json"
      farday.use Faraday::Adapter::NetHttp
     end
     @conn.basic_auth('apikey', <your_api_key>)
     response = @conn.get('contacts')
     puts response 
     render :json => {"success" => true}

    end
Elayaraja Dev
  • 208
  • 3
  • 6