Class: DataForSEO::Client

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/data_for_seo/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(username, password, sandbox = false, api_version = 'v3') ⇒ Client

Returns a new instance of Client.



10
11
12
13
14
15
16
17
18
19
# File 'lib/data_for_seo/client.rb', line 10

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

Instance Attribute Details

#api_versionObject

Returns the value of attribute api_version.



8
9
10
# File 'lib/data_for_seo/client.rb', line 8

def api_version
  @api_version
end

#authObject

Returns the value of attribute auth.



8
9
10
# File 'lib/data_for_seo/client.rb', line 8

def auth
  @auth
end

#base_uriObject

Returns the value of attribute base_uri.



8
9
10
# File 'lib/data_for_seo/client.rb', line 8

def base_uri
  @base_uri
end

Instance Method Details

#get(path, options = {}) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/data_for_seo/client.rb', line 37

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

#merge_request_options(options) ⇒ Object



21
22
23
24
25
# File 'lib/data_for_seo/client.rb', line 21

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

#parse_response(request) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/data_for_seo/client.rb', line 27

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

#post(path, body = {}, options = {}) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/data_for_seo/client.rb', line 45

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