Sha256: bdd04f7d31d639219f4842d66a792bff12aed5f3b831fd760de609ac57b67e2c

Contents?: true

Size: 1.48 KB

Versions: 1

Compression:

Stored size: 1.48 KB

Contents

require 'httparty'
require 'json'

module DataForSEO
  class Client
    include HTTParty

    attr_accessor :base_uri, :auth, :api_version 

    def initialize(username, password, sandbox=false, api_version='v3')
        if sandbox
            @base_uri = 'https://sandbox.dataforseo.com'
        else
            @base_uri = 'https://api.dataforseo.com'
        end

        @auth = {username: username, password: password}
        @api_version = api_version 
    end

    def merge_request_options(options)
        options.merge!({ basic_auth: @auth })
        options.merge!({headers: { 'Content-Type' => 'application/json' }})
        options 
    end

    def parse_response(request)
        begin 
            json = JSON.parse(request.response.body)
        rescue => e 
            warn ['Parse response JSON error', e.class, e.message].join(' ')
            json = {}
        end
        json
    end

    def get(path, options={})
        target_url = [@base_uri, @api_version, path].join('/')
        options = merge_request_options(options)
        request = self.class.get(target_url, options)
        json = parse_response(request)
        return json, request
    end

    def post(path, body={}, options = {})
        target_url = [@base_uri, @api_version, path].join('/')
        options[:body] = body.to_json
        options = merge_request_options(options)
        request = self.class.post(target_url, options)
        json = parse_response(request)
        return json, request
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
data_for_seo-0.1.0 lib/data_for_seo/client.rb