Skip to content

Client Tutorial Overview

Adam Korn edited this page Jun 16, 2022 · 4 revisions

Configure the Magento Account

The Magento account you use must be assigned a User Role that has the appropriate API resources include 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 all other desired resources are included


Initialize and Authenticate a Client

Authentication is very straightforward

  1. Initialize a Client using your Magento Admin login credentials
  2. Request a token either by specifying login=True (or nothing) at the time of Client instantiation , or by calling authenticate() at any point afterwards
from magento import Client

api = Client('website.com','username', 'password', login=False)
api.authenticate()

Alternatively, use Client.new() to login with input prompts

api = Client.new()
print('\nAccess Token: ', api.ACCESS_TOKEN)

Output:

Domain: >? website.com
Username: >? username
Password: >? password
User Agent: >? 
2022-06-14 00:55:42 INFO   |[ MyMagento | website_username ]|:  Authenticating username on website.com...
2022-06-14 00:55:43 INFO   |[ MyMagento | website_username ]|:  Logged in to username

Access Token:  eyJraWQiIxIiwiYWxnIjoiSFMyNTYifQ.eyJ1aWQiOjI3LCJ1dHlwaWQiOjIsImlhdCI6MTY1NTE4MjU0MywiZXhwIjoxNjU1MTg2MTQzfQ.AbtkboAG_5R6CTsHmZwu_DiINJ7BKQ0_5sqHGJqcJVk

View/Validate the Access Token

The access token currently in use by a Client object can be accessed via its

  • ACCESS_TOKEN - instance attribute that stores the token
  • token - property that calls authenticate() if no ACCESS_TOKEN has been set

You can call the validate() method to verify that the access token isn't expired


Saving/Loading Client Configurations

A Client instance can be saved to/loaded from various formats

import json
from magento import Client

# Save to/Load from JSON string, pickle string, or dict
json_str = api.to_json()
json_api = Client.from_json(json_str)

pickle_bytes = api.to_pickle() 
pickle_api = Client.load(pickle_bytes)

json_dict = json.loads(api.to_json())
dict_api = Client(**json_dict, login=False)

Create a Client Without Credentials and Avoid Authentication

Initialize a Client with login=False to prevent calling authenticate()

test_client = Client('','','',login=False)

Avoid calling token before setting the ACCESS_TOKEN attribute

@property
def token(self) -> str:
    """Returns or generates access token"""
    if not self.ACCESS_TOKEN:
        self.authenticate()
    return self.ACCESS_TOKEN

It will raise an AuthenticationError if valid credentials aren't set


Create or Load a Client Then Manually Set the Access Token

If your site uses a different authentication provider (ie. 2FA) and doesn't use the standard token authentication endpoint/workflow, you can simply generate the token as you normally would, then set the Client access token manually.

This can be done multiple ways:

1. Directly set the ACCESS_TOKEN on an already initialized Client. Verify it by calling validate()

token = "fsdkjgnewofgnQ$r@FDN8FJ38NDJKIINvblbahgfjgjgjgjfjfASJHNAHKSJDNKJASFDhoeodiqwahhahahahr02389jfd3nm981"
api.ACCESS_TOKEN = token
api.validate()
>>> True

2. Initialize the Client and specify the token parameter. Ensure to use login=False so no attempt is made to generate a token

api = magento.Client(
  domain="website.com",
  username="username",
  password="password",
  token=token,
  login=False   
)

3. Load the configuration from a Client previously saved as pickle file (that had login=False at the time it was saved)

with open('myClient.pickle', 'rb') as f:
    api = Client.load(f.read())

api.logger.info("HELLO")
>>> 2022-06-16 04:48:45 INFO   |[ MyMagento | website_username ]|:  HELLO

4. Load a Client from a JSON string/dictionary with all necessary parameters. login=False is mandatory

config = {
    'domain': 'website.com', 
    'username': 'username', 
    'password': 'password', 
    'token': token,
    'login': False
}
api = Client(**config)
print(api.ACCESS_TOKEN)
>>> fsdkjgnewofgnQ$r@FDN8FJ38NDJKIINvblbahgfjgjgjgjfjfASJHNAHKSJDNKJASFDhoeodiqwahhahahahr02389jfd3nm981

Regardless of how it's done, the key is to avoid calling authenticate(), as it would request a new token