Module: PrestaShop

Defined in:
lib/presta_shop.rb,
lib/presta_shop/api.rb,
lib/presta_shop/version.rb,
lib/presta_shop/resource.rb,
lib/presta_shop/requestor.rb,
lib/presta_shop/uri_handler.rb,
lib/presta_shop/requestor/image.rb

Defined Under Namespace

Classes: API, Requestor, Resource, UriHandler

Constant Summary collapse

VERSION =
'0.1.2'

Class Method Summary collapse

Class Method Details

.api_enabled?(url) ⇒ boolean

Check if there is an enabled API in a Prestashop instance.

Parameters:

Returns:

  • (boolean)

    true if the API is enabled, false if it is disabled

Raises:

  • (RestClient::Exception)

    if there is an error during HTTP GET

  • (StandardError)

    if a response different from 401 or 503 is received (not counting redirect responses, which will be followed)



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/presta_shop.rb', line 23

def self.api_enabled?(url)
  api_uri = UriHandler.api_uri url
  res = RestClient::Resource.new api_uri, user: '', password: ''
  begin
    response = res.get
    # We don't send an API key, so an HTTP error code should be returned. Execution shouldn't reach here normally.
    raise StandardError.new "Expected 401 or 503 response from Prestashop API #{api_uri} without key, instead received <#{response.code}> #{response.body}"
  rescue RestClient::Exception => e
    if e.response.code == 401
      return true # "Unauthorized" response means API is enabled
    elsif e.response.code == 503
      return false # "Service Unavailable" response means API is disabled
    else
      raise e # Any other HTTP error code means something is wrong
    end
  end
end

.valid_key?(url, key) ⇒ boolean

Check if an API key is valid.

Parameters:

  • url (String)

    base URL of the Prestashop installation. Do not append “/api” to it, the gem does it internally. E.g. use “my.prestashop.com”, not “my.prestashop.com/api

  • key (String)

    the key to check

Returns:

  • (boolean)

    true if key is valid, false otherwise

Raises:

  • (RestClient::Exception)

    if there is an error during HTTP GET

  • (StandardError)

    if a response different from 200 or 401 is received (not counting redirect responses, which will be followed)



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/presta_shop.rb', line 49

def self.valid_key?(url, key)
  api_uri = UriHandler.api_uri url
  res = RestClient::Resource.new api_uri, user: key, password: ''
  begin
    response = res.get
    if response.code == 200 # OK response means API key is valid
      return true
    else
      raise StandardError.new "Expected 200 or 401 response from Prestashop API #{api_uri} with key #{key}, instead received <#{response.code}> #{response.body}"
    end
  rescue RestClient::Exception => e
    if e.response.code == 401
      return false # "Unauthorized" response means API key is invalid
    else
      raise e # Any other HTTP error code means something is wrong
    end
  end
end