The clients module

class magento.clients.Client(domain, username, password, scope='', user_agent=None, token=None, log_level='INFO', login=True, **kwargs)[source]View on GitHub

Bases: object

The class that handles all interaction with the API

__init__(domain, username, password, scope='', user_agent=None, token=None, log_level='INFO', login=True, **kwargs)[source]View on GitHub

Initialize a Client

Important!

The Magento account you use to log in must be assigned a User Role that has the appropriate API resources included in its Resource Access settings

This can be verified in Magento Admin by going to:

System -> Permissions -> User Roles -> {Role} -> Role Resources -> Resource Access

and ensuring that Sales, Catalog, Customers, and any other desired resources are included

Parameters
  • domain (str) – domain name of the Magento store (ex. domain.com)

  • username (str) – username of the Magento Admin account

  • password (str) – password of the Magento Admin account

  • scope (Optional[str]) – the store view scope to search() and make requests on

  • user_agent (Optional[str]) – the user agent to use in requests

  • token (Optional[str]) – an existing access token

  • log_level (str) – the logging level for logging to stdout

  • login (bool) – if True, calls authenticate() upon initialization

  • kwargs – see below

…

Optional Keyword Arguments
  • log_file (str) – log file to use for the client’s logger

  • log_requests (bool) - if True, the logs from requests will be added to the client’s log_file

BASE_URL: str

The base API URL

USER_CREDENTIALS: Dict[str, str]

The user credentials

ACCESS_TOKEN: str

The API access token

domain: str

The Magento store domain

scope: str

The store view code to request/update data on

user_agent: str

The user agent to use in requests

logger: MagentoLogger

The MagentoLogger for the domain/username combination

store: Store

An initialized Store object

classmethod new()[source]View on GitHub

Prompts for input to log in to the Magento API

Return type

Client

classmethod load(pickle_bytes)[source]View on GitHub

Initialize a Client using a pickle bytestring from to_pickle()

Return type

Client

classmethod from_json(json_str)[source]View on GitHub

Initialize a Client from a JSON string of settings

Return type

Client

classmethod from_dict(d)[source]View on GitHub

Initialize a Client from a dictionary of settings

Return type

Client

url_for(endpoint, scope=None)[source]View on GitHub

Returns the appropriate request url for the given API endpoint and store scope

Example

# Generate the url for credit memo with id 7
>> api=Client("domain.com", "user", "password")
>> api.url_for('creditmemo/7')
"https://domain.com/rest/V1/creditmemo/7"

# Generate the same url on the "en" store view
>> api.url_for('creditmemo/7', scope='en')
"https://domain.com/rest/en/V1/creditmemo/7"
Parameters
  • endpoint (str) – the API endpoint

  • scope (Optional[str]) – the scope to generate the url for; uses the Client.scope if not provided

Return type

str

search(endpoint)[source]View on GitHub

Initializes and returns a SearchQuery corresponding to the specified endpoint

Note

Several endpoints have predefined SearchQuery and Model subclasses

If a subclass hasn’t been defined for the endpoint yet, a general SearchQuery will be returned, which wraps the result with APIResponse

Parameters

endpoint (str) – a valid Magento API search endpoint

Return type

SearchQuery

property orders: OrderSearch

Initializes an OrderSearch

property order_items: OrderItemSearch

Initializes an OrderItemSearch

property invoices: InvoiceSearch

Initializes an InvoiceSearch

property categories: CategorySearch

Initializes a CategorySearch

property products: ProductSearch

Initializes a ProductSearch

property product_attributes: ProductAttributeSearch

Initializes a ProductAttributeSearch

get(url)[source]View on GitHub

Sends an authorized GET request

Parameters

url (str) – the URL to make the request on

Return type

Response

post(url, payload)[source]View on GitHub

Sends an authorized POST request

Parameters
  • url (str) – the URL to make the request on

  • payload (dict) – the JSON payload for the request

Return type

Response

put(url, payload)[source]View on GitHub

Sends an authorized PUT request

Parameters
  • url (str) – the URL to make the request on

  • payload (dict) – the JSON payload for the request

Return type

Response

delete(url)[source]View on GitHub

Sends an authorized DELETE request

Parameters

url (str) – the URL to make the request on

Return type

Response

authenticate()[source]View on GitHub

Authenticates the USER_CREDENTIALS and retrieves an access token

Return type

bool

validate()[source]View on GitHub

Validates the token by sending an authorized request to a standard API endpoint

Return type

bool

request(method, url, payload=None)[source]View on GitHub

Sends an authorized API request. Used for all internal requests

Tip

Use get(), post(), put() or delete() instead

Parameters
  • method (str) – the request method

  • url (str) – the url to send the request to

  • payload (Optional[dict]) – the JSON payload for the request (if the method is POST or PUT)

Return type

Response

get_logger(log_file=None, stdout_level='INFO', log_requests=True)[source]View on GitHub

Retrieve a MagentoLogger for the current username/domain combination. Log files are DEBUG.

Parameters
  • log_file (Optional[str]) – the file to log to

  • stdout_level (str) – the logging level for stdout logging

  • log_requests (bool) – if True, adds the FileHandler to the connectionpool logger

Return type

MagentoLogger

property headers: dict

Authorization headers for API requests

Automatically generates a token if needed

property token: str

Returns or generates an ACCES_TOKEN

to_pickle(validate=False)[source]View on GitHub

Serializes the Client to a pickle bytestring

Parameters

validate (bool) – if True, validates the token/USER_CREDENTIALS before serializing

Return type

bytes

to_json(validate=False)[source]View on GitHub

Serializes the Client to a JSON string

Parameters

validate (bool) – if True, validates the token/USER_CREDENTIALS before serializing

Return type

str

to_dict(validate=False)[source]View on GitHub

Serializes the Client to a dictionary

Parameters

validate (bool) – if True, validates the token/USER_CREDENTIALS before serializing

Return type

Dict[str, str]

view_config()[source]View on GitHub

Prints the Client configuration settings

class magento.clients.Store(client)[source]View on GitHub

Bases: object

Class containing store configurations and cached attribute lists

__init__(client)[source]View on GitHub

Initialize a Store object

Parameters

client (Client) – an initialized Client object

property is_single_store: bool

Whether the store has a single store view (default) or multiple store views

property active: APIResponse

Returns the store config corresponding to the current scope of the Client

property configs: Optional[Union[APIResponse, List[APIResponse]]]

Returns a list of all store configurations

property views: Optional[Union[APIResponse, List[APIResponse]]]

Returns a list of all store views

property all_product_attributes: List[ProductAttribute]

A cached list of all product attributes

property store_view_product_attributes: List[ProductAttribute]

A cached list of all product attributes with the Store View scope

property website_product_attributes: List[ProductAttribute]

A cached list of all product attributes with the Web Site scope

property global_product_attributes: List[ProductAttribute]

A cached list of all product attributes with the Global scope

property website_attribute_codes: List[str]

The attribute codes of the website_product_attributes

filter_website_attrs(attribute_data)[source]View on GitHub

Filters a product attribute dict and returns a new one that contains only the website scope attributes

Website scoped attributes must be updated on the admin by making a second request on the all scope

Example

The price attribute is Website scope and the meta_title attribute is Store View scope

>> attribute_data = {'price': 12, 'meta_title': 'My Product'}
>> store.filter_website_attrs(attribute_data)
{'price': 12}
Parameters

attribute_data (dict) – a dict of product attributes

Return type

dict

refresh()[source]View on GitHub

Clears all cached properties

Return type

bool