Table Of Contents
MyMagento - Python Magento 2 REST API Wrapper
About MyMagento
What’s MyMagento?
MyMagento
is a highly interconnected package that wraps and extends the Magento 2 REST API,
providing a more intuitive and user-friendly interface to access and update your store.
MyMagento simplifies interaction with the Magento 2 REST API
If you’ve worked with the Magento 2 API, you’ll know that not all endpoints are created equally.
MyMagento
aims to streamline your workflow by simplifying a
variety of commonly needed API operations.
Main Components
The Client
Handles all API interactions
Supports multiple store views
Provides access to all other package components
The SearchQuery
and Subclasses
execute()
a search query on any endpointIntuitive interface for Building Custom Search Queries
All predefined methods retrieve data using only 1-2 API requests
The Model
Subclasses
Wrap all API responses in the package
Provide additional endpoint-specific methods to retrieve and update data
Available Endpoints
MyMagento
is compatible with every API endpoint
Endpoints are wrapped with a Model
and SearchQuery
subclass as follows:
Endpoint |
Client Shortcut |
|
|
---|---|---|---|
|
|||
|
|||
|
|||
|
|||
|
|||
|
|||
|
|
…
⚙ Installing MyMagento
To install using pip
:
pip install my-magento
Please note that MyMagento
requires Python >= 3.10
…
QuickStart: Login with MyMagento
MyMagento
uses the Client
class to handle all interactions with the API.
Tip
See Get a Magento 2 REST API Token With MyMagento for full details on generating an access token
Setting the Login Credentials
To generate an ACCESS_TOKEN
you’ll need to authenticate()
your USER_CREDENTIALS
.
Creating a Client
requires a domain
, username
, and password
at minimum.
>>> domain = 'website.com'
>>> username ='username'
>>> password = 'password'
If you’re using a local installation of Magento you’ll need to set local=True
. Your domain should look like this:
>>> domain = '127.0.0.1/path/to/magento'
…
Getting a Client
Option 1: Initialize a Client
Directly
from magento import Client
>>> api = Client(domain, username, password, **kwargs)
Option 2: Call get_api()
import magento
>>> api = magento.get_api(**kwargs)
get_api()
takes the same keyword arguments as the Client
If the
domain
,username
, orpassword
are missing, it will attempt to use the following environment variables:
import os
os.environ['MAGENTO_DOMAIN'] = domain
os.environ['MAGENTO_USERNAME']= username
os.environ['MAGENTO_PASSWORD']= password
…
Getting an ACCESS_TOKEN
Unless you specify login=False
, the Client
will automatically call authenticate()
once initialized:
>> api.authenticate()
|[ MyMagento | website_username ]|: Authenticating username on website.com...
|[ MyMagento | website_username ]|: Logged in to username
Interacting with the API
Did you Get a Magento 2 REST API Token With MyMagento? Then let’s start using the API!
Performing a search()
The Client.search()
method lets you execute()
a query on
any API endpoint
It creates a SearchQuery
for the endpoint,
allowing you to retrieve data about
An individual item (ex.
by_id()
)A list of items (ex.
by_list()
)Any search criteria you desire (see Building Custom Search Queries)
From the Docs…
- Client.search(endpoint)[source]View on GitHub
Initializes and returns a
SearchQuery
corresponding to the specified endpointNote
Several endpoints have predefined
SearchQuery
andModel
subclassesIf a subclass hasn’t been defined for the
endpoint
yet, a generalSearchQuery
will be returned, which wraps theresult
withAPIResponse
- Parameters
endpoint (str) – a valid Magento API search endpoint
- Return type
Example: search()
an endpoint by_id()
# Query the "invoices" endpoint (also: api.invoices)
>>> api.search("invoices").by_id(1)
<Magento Invoice: "#000000001"> for <Magento Order: "#000000001" placed on 2022-11-01 03:27:33>
Example: search()
an endpoint by_list()
# Retrieve invoices from a list of invoice ids
>>> ids = list(range(1,101))
>>> api.invoices.by_list("entity_id", ids)
[<Magento Invoice: "#000000001"> for <Magento Order: "#000000001" placed on 2022-11-01 03:27:33>, ...]
…
Search Results: The Model
Classes
The result
of any SearchQuery
will be parsed and wrapped by a
Model
class in the magento.models
subpackage.
These classes make the API response data easier to work with.
They also provide endpoint-specific methods to update store data and search for related items.
Example: Retrieving every Order
containing a Product
Let’s retrieve a Product
using by_sku()
>>> product = api.products.by_sku("24-MB01")
We can search for orders containing this product in multiple ways:
# Using the Product itself
>>> product.get_orders()
[<Magento Order: "#000000003" placed on 2022-12-21 08:09:33>, ... ]
# Using an OrderSearch
>>> api.orders.by_product(product)
>>> api.orders.by_product_id(product.id)
>>> api.orders.by_sku(product.sku)
[<Magento Order: "#000000003" placed on 2022-12-21 08:09:33>, ... ]
Example: Retrieving all Product
s and Invoice
s for a Category
>>> category = api.categories.by_name("Watches")
>>> category.get_products()
>>> category.get_invoices()
[<Magento Product: 24-MG04>, <Magento Product: 24-MG01>, <Magento Product: 24-MG03>, ... ]
[<Magento Invoice: "#000000004"> for <Magento Order: "#000000004" placed on 2022-11-14 03:27:33>, ... ]
Example: Updating the Thumbnail MediaEntry
of a Product
# Update product thumbnail label on specific store view
>>> product.thumbnail.set_alt_text("bonjour", scope="FR")
>>> print(product.thumbnail)
<MediaEntry 3417 for <Magento Product: 24-MB01>: bonjour>
…
Tip: Set the Store Scope
If you have multiple store views, a store_code
can be specified when
retrieving/updating data
The
Client.scope
is used by default - simply change it to switch storeviews
Passing the
scope
keyword argument toClient.url_for()
,Model.refresh()
, and some Model update methods will temporarily override the Client scope
…
Building Custom Search Queries
In addition to the predefined methods, you can also build your own queries
Simply
add_criteria()
,restrict_fields()
, andexecute()
the searchThe
since()
anduntil()
methods allow you to further filter your query by date
Example: Retrieve Orders Over $50 Placed Since the Start of 2023
>>> api.orders.add_criteria(
... field="grand_total",
... value="50",
... condition="gt"
... ).since("2023-01-01").execute()
[<Magento Order: "#000000012" placed on 2023-01-02 05:19:55>, ...]
…
Making Authorized Requests
The Client
can be used to generate the url_for()
any API endpoint,
including a store scope
.
You can use this URL to make an authorized
get()
, post()
, put()
, or delete()
request.
Example: Making a get()
Request
# Request the data for credit memo with id 7
>>> url = api.url_for('creditmemo/7')
>>> response = api.get(url)
>>> print(response.json())
{'adjustment': 1.5, 'adjustment_negative': 0, 'adjustment_positive': 1.5, 'base_adjustment': 1.5, ... }
Note
A search()
is simpler than making get()
requests, as the result will
be wrapped by APIResponse
or other Model
# Retrieve credit memo with id 7 using a search
>>> memo = api.search("creditmemo").by_id(7)
>>> print(memo.data)
>>> print(memo)
{'adjustment': 1.5, 'adjustment_negative': 0, 'adjustment_positive': 1.5, 'base_adjustment': 1.5, ... }
<magento.models.model.APIResponse object at 0x000001BA42FD0FD1>
Example: Making a post()
Request
# Add a comment to credit memo with id 7
>>> url = api.url_for("creditmemo/7/comments")
>>> payload = {
"entity": {
"comment": "this is a comment",
"is_customer_notified": 0,
"is_visible_on_front": 0,
"parent_id": 20
}
}
>>> response = api.post(url, payload)
Tip
The Model.data_endpoint()
will usually be
close to the url to post()
to
# The same as above, but using a search
>>> memo = api.search("creditmemo").by_id(7)
>>> url = memo.data_endpoint() + '/comments'
>>> response = api.post(url, payload)
The magento
Package
The magento
package provides various tools to help simplify interaction with the Magento 2 API.
Functions
- magento.get_api(**kwargs)[source]View on GitHub
Initialize a
Client
using credentials stored in environment variablesAny valid
Client
kwargs can be used in addition to and/or instead of environment variablesUsage:
import magento api = magento.get_api()
- Parameters
kwargs – any valid kwargs for
Client
- Raises
ValueError – if login credentials are missing
- Return type
…
The clients
module
- class magento.clients.Client(domain, username, password, scope='', local=False, 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='', local=False, 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
or127.0.0.1/magento24
)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 onlocal (bool) – whether the Magento store is hosted locally
user_agent (Optional[str]) – the user agent to use in requests
log_level (str) – the logging level for logging to stdout
login (bool) – if
True
, callsauthenticate()
upon initializationkwargs – see below
…
- logger: MagentoLogger
The
MagentoLogger
for the domain/username combination
- classmethod new()[source]View on GitHub
Prompts for input to log in to the Magento API
- Return type
- classmethod load(pickle_bytes)[source]View on GitHub
Initialize a
Client
using a pickle bytestring fromto_pickle()
- Return type
- classmethod from_json(json_str)[source]View on GitHub
Initialize a
Client
from a JSON string of settings- Return type
- classmethod from_dict(d)[source]View on GitHub
Initialize a
Client
from a dictionary of settings- Return type
- 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
- search(endpoint)[source]View on GitHub
Initializes and returns a
SearchQuery
corresponding to the specified endpointNote
Several endpoints have predefined
SearchQuery
andModel
subclassesIf a subclass hasn’t been defined for the
endpoint
yet, a generalSearchQuery
will be returned, which wraps theresult
withAPIResponse
- Parameters
endpoint (str) – a valid Magento API search endpoint
- Return type
- 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
- post(url, payload)[source]View on GitHub
Sends an authorized
POST
request
- put(url, payload)[source]View on GitHub
Sends an authorized
PUT
request
- delete(url)[source]View on GitHub
Sends an authorized
DELETE
request
- authenticate()[source]View on GitHub
Authenticates the
USER_CREDENTIALS
and retrieves an access token- Return type
- validate()[source]View on GitHub
Validates the
token
by sending an authorized request to a standard API endpoint- Raises
AuthenticationError
if the token is invalid- Return type
- request(method, url, payload=None)[source]View on GitHub
Sends an authorized API request. Used for all internal requests
- 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
- Return type
- property headers: dict
Authorization headers for API requests
Automatically generates a
token
if needed
- to_pickle(validate=False)[source]View on GitHub
Serializes the Client to a pickle bytestring
- Parameters
validate (bool) – if
True
, validates thetoken
/USER_CREDENTIALS
before serializing- Return type
- to_json(validate=False)[source]View on GitHub
Serializes the Client to a JSON string
- Parameters
validate (bool) – if
True
, validates thetoken
/USER_CREDENTIALS
before serializing- Return type
- to_dict(validate=False)[source]View on GitHub
Serializes the Client to a dictionary
- 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
- 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 theClient
- 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
scopeThis method is called by
update_attributes()
andupdate_custom_attributes()
to see if the second request is needed
Example
The
price
attribute isWebsite
scope and themeta_title
attribute isStore View
scope>> attribute_data = {'price': 12, 'meta_title': 'My Product'} >> store.filter_website_attrs(attribute_data) {'price': 12}
- refresh()[source]View on GitHub
Clears all cached properties
- Return type
The search
module
Available Endpoints
The following endpoints are currently wrapped with a Model
and SearchQuery
subclass
Endpoint |
Client Shortcut |
|
|
---|---|---|---|
|
|||
|
|||
|
|||
|
|||
|
|||
|
|||
|
|
- class magento.search.SearchQuery(endpoint, client, model=<class 'magento.models.model.APIResponse'>)[source]View on GitHub
Bases:
object
Queries any endpoint that invokes the searchCriteria interface. Parent of all endpoint-specific search classes
Tip
See https://developer.adobe.com/commerce/webapi/rest/use-rest/performing-searches/ for official docs
- __init__(endpoint, client, model=<class 'magento.models.model.APIResponse'>)[source]View on GitHub
Initialize a SearchQuery object
- endpoint
The endpoint being queried
- Model
The magento.models subpackage class to wrap the response with
- query
The current url for the search request
- fields
Restricted fields, from
restrict_fields()
- add_criteria(field, value, condition='eq', **kwargs)[source]View on GitHub
Add criteria to the search query
- Parameters
field – the API response field to search by
value – the value of the field to compare
condition – the comparison condition
kwargs – additional search option arguments (
group
andfilter
)
- Returns
the calling SearchQuery object
- Return type
Self
Keyword Argument Options:
Condition
The
condition
argument specifies the condition used to evaluate the attribute value"eq"
(default): matches items for whichfield=value
"gt"
: matches items for whichfield>value
"lt"
: matches items for whichfield<value
"gteq"
: matches items for whichfield>=value
"lteq"
: matches items for whichfield<=value
"in"
: matches items for whichfield in value.split(",")
Tip: for
in
, useby_list()
if not building a complex query
Example
# Search for Orders created in 2023 >>> orders = api.orders.add_criteria( ... field="created_at", ... value="2023-01-01", ... condition='gteq' ... ).execute()
Keyword Argument Options: Using Filter Groups
group
- filter group numberfilter
- filter number (within the specified filter group)Using Filter Groups
Filter groups are filter criteria in the form of { field: value }
Group 0 Filter 0 -> Filter 0 Group 0 Filter 0 + Group 0 Filter 1 -> Filter 0 OR Filter 1 Group 0 Filter 0 + Group 1 Filter 0 -> Filter 0 AND Filter 0
- restrict_fields(fields)[source]View on GitHub
Constrain the API response data to only contain the specified fields
- Parameters
fields (Iterable[str]) – an iterable or comma separated string of fields to include in the response
- Returns
the calling SearchQuery object
- Return type
Self
- execute()[source]View on GitHub
Sends the search request using the current
scope
of theclient
Tip
Change the
Client.scope
to retrieveresult
data from different storeviews
- by_id(item_id)[source]View on GitHub
Retrieve data for an individual item by its id
Note
The
id
field used is different depending on the endpoint being queriedMost endpoints use an
entity_id
orid
The
orders/items
endpoint usesitem_id
The
products
endpoint usesproduct_id
, but can also be queriedby_sku()
The
IDENTIFIER
attribute of eachModel
contains the appropriate field
- by_list(field, values)[source]View on GitHub
Search for multiple items using an iterable or comma-separated string of field values
Examples
Retrieve
Product
with ids from 1 to 10:# Values can be a list/tuple/iterable >> api.products.by_list('entity_id', range(1,11))
Search for
Order
that are processing, pending, or completed:# Values can be a comma-separated string >> api.orders.by_list('status', 'processing,pending,completed')
- since(sinceDate=None)[source]View on GitHub
Retrieve items for which
created_at >= sinceDate
Example:
# Retrieve products created in 2023 >> api.products.since('2023-01-01').execute()
Tip
Calling with no arguments retrieves all items
# Retrieve all products >> api.products.since().execute()
- Parameters
sinceDate (str) – the date for response data to start from
- Returns
the calling
SearchQuery
- Return type
Self
- until(toDate)[source]View on GitHub
Retrieve items for which
created_at <= toDate
- Parameters
toDate (str) – the date for response data to end at (inclusive)
- Returns
the calling
SearchQuery
- Return type
Self
- property result: Optional[Union[Model, List[Model]]]
The result of the search query, wrapped by the
Model
corresponding to the endpoint- Returns
the API response as either an individual or list of
Model
objects
- validate_result()[source]View on GitHub
Parses the response and returns the actual result data, regardless of search approach
- parse(data)[source]View on GitHub
Parses the API response with the corresponding
Model
object
- reset()[source]View on GitHub
Resets the query and result, allowing the object to be reused
- class magento.search.OrderSearch(client)[source]View on GitHub
Bases:
SearchQuery
SearchQuery
subclass for theorders
endpoint- __init__(client)[source]View on GitHub
Initialize an
OrderSearch
- by_number(order_number)[source]View on GitHub
Retrieve an
Order
by number
- by_product(product)[source]View on GitHub
- by_sku(sku)[source]View on GitHub
Search for
Order
by product skuNote
Like
OrderItemSearch.by_sku()
, the sku will need to be an exact match to the sku of a simple product, including a custom option if applicableUse
by_product()
orby_product_id()
to find orders containing any of theoption_skus
and/or allchildren
of a configurable product
- by_product_id(product_id)[source]View on GitHub
Search for
Order
s byproduct_id
- by_category_id(category_id, search_subcategories=False)[source]View on GitHub
Search for
Order
s bycategory_id
- by_category(category, search_subcategories=False)[source]View on GitHub
Search for
Order
s that contain any of the category’sproducts
- by_skulist(skulist)[source]View on GitHub
Search for
Order
s using a list or comma separated string of product SKUs
- class magento.search.OrderItemSearch(client)[source]View on GitHub
Bases:
SearchQuery
SearchQuery
subclass for theorders/items
endpoint- __init__(client)[source]View on GitHub
Initialize an
OrderItemSearch
- property result: Optional[Union[OrderItem, List[OrderItem]]]
The result of the search query, wrapped by the
Model
corresponding to the endpoint- Returns
the API response as either an individual or list of
Model
objects
- parse(data)[source]View on GitHub
Overrides
SearchQuery.parse()
to fully hydrateOrderItem
objectsExtra validation is required for OrderItems, as duplicated and/or incomplete data is returned when the child of a configurable product is searched
by_sku()
orby_product()
- by_product(product)[source]View on GitHub
Search for
OrderItem
entries byProduct
Note
This will match OrderItems that contain
Any of the child products of a configurable product
Any of the
option_skus
of a product with custom options
- by_sku(sku)[source]View on GitHub
Search for
OrderItem
entries by product sku.The SKU must be an exact match to the OrderItem SKU
OrderItems always use the SKU of a simple product, including any custom options. This means that:
Searching the SKU of a configurable product returns nothing
If a product has custom options, the search will only find OrderItems that contain the specific option sku (or base sku) that’s provided
To search for OrderItems containing all
children
of a configurable product and/or all possibleoption_skus
, useby_product()
orby_product_id()
- by_product_id(product_id)[source]View on GitHub
Search for
OrderItem
entries by product id.
- by_category_id(category_id, search_subcategories=False)[source]View on GitHub
Search for
OrderItem
entries bycategory_id
- by_category(category, search_subcategories=False)[source]View on GitHub
Search for
OrderItem
entries that contain any of the category’sproducts
- class magento.search.InvoiceSearch(client)[source]View on GitHub
Bases:
SearchQuery
SearchQuery
subclass for theinvoices
endpoint- __init__(client)[source]View on GitHub
Initialize an
InvoiceSearch
- by_number(invoice_number)[source]View on GitHub
Retrieve an
Invoice
by number
- by_order_number(order_number)[source]View on GitHub
Retrieve an
Invoice
by order number
- by_order(order)[source]View on GitHub
- by_order_id(order_id)[source]View on GitHub
Retrieve an
Invoice
byorder_id
- by_product(product)[source]View on GitHub
- by_sku(sku)[source]View on GitHub
Search for
Invoice
s by product skuNote
Like
OrderItemSearch.by_sku()
, the sku will need to be an exact match to the sku of a simple product, including a custom option if applicableUse
by_product()
orby_product_id()
to find orders containing any of theoption_skus
and/or allchildren
of a configurable product
- by_product_id(product_id)[source]View on GitHub
Search for
Invoice
s byproduct_id
- by_category_id(category_id, search_subcategories=False)[source]View on GitHub
Search for
Invoice
s bycategory_id
- by_category(category, search_subcategories=False)[source]View on GitHub
Search for
Invoice
s that contain any of the category’sproducts
- by_skulist(skulist)[source]View on GitHub
Search for
Invoice
s using a list or comma separated string of product SKUs
- from_order_items(items)[source]View on GitHub
Retrieve unique
Invoice
objects fromOrderItem
entries using a single requestTip
Since there is no
invoices/items
endpoint, to search for invoices we must first do anOrderItemSearch
, then retrieve theorder_ids
and searchby_order_id()
- class magento.search.ProductSearch(client)[source]View on GitHub
Bases:
SearchQuery
SearchQuery
subclass for theproducts
endpoint- __init__(client)[source]View on GitHub
Initialize a
ProductSearch
- property attributes: ProductAttributeSearch
Alternate way to access the SearchQuery for
ProductAttribute
data
- by_id(item_id)[source]View on GitHub
Retrieve a
Product
byproduct_id
Note
Response data from the
products
endpoint only has anid
field, but all other endpoints that return data about products will useproduct_id
- by_sku(sku)[source]View on GitHub
Retrieve a
Product
bysku
- by_skulist(skulist)[source]View on GitHub
Search for :class:`~.Product`s using a list or comma separated string of SKUs
- by_category(category, search_subcategories=False)[source]View on GitHub
- by_category_id(category_id, search_subcategories=False)[source]View on GitHub
Search for
Product
s bycategory_id
- class magento.search.ProductAttributeSearch(client)[source]View on GitHub
Bases:
SearchQuery
SearchQuery
subclass for theproducts/attributes
endpoint- __init__(client)[source]View on GitHub
Initialize a
ProductAttributeSearch
- get_all()[source]View on GitHub
Retrieve a list of all :class:`~.ProductAttribute`s
- Return type
- by_code(attribute_code)[source]View on GitHub
Retrieve a
ProductAttribute
by its attribute code- Parameters
attribute_code (str) – the code of the
ProductAttribute
- Return type
- get_types()[source]View on GitHub
Retrieve a list of all available
ProductAttribute
types- Return type
- class magento.search.CategorySearch(client)[source]View on GitHub
Bases:
SearchQuery
SearchQuery
subclass for thecategories
endpoint- __init__(client)[source]View on GitHub
Initialize a
CategorySearch
- get_root()[source]View on GitHub
Retrieve the top level/default
Category
(every other category is a subcategory)- Return type
- get_all()[source]View on GitHub
Retrieve a list of all categories
The exceptions
module
- exception magento.exceptions.MagentoError(client, msg=None, response=None)[source]View on GitHub
Bases:
Exception
Base exception class for error responses returned by the Magento API
- Variables
DEFAULT_MSG – default exception message to use if a message isn’t provided
- DEFAULT_MSG = 'An error occurred while processing the request.'
- __init__(client, msg=None, response=None)[source]View on GitHub
Log and raise a MagentoError
- exception magento.exceptions.AuthenticationError(client, msg=None, response=None)[source]View on GitHub
Bases:
MagentoError
Exception class for errors when trying to
authenticate()
aClient
- DEFAULT_MSG = 'Failed to authenticate credentials.'
- __init__(client, msg=None, response=None)[source]View on GitHub
Log and raise a MagentoError
The utils
module
- magento.utils.parse_domain(domain)[source]View on GitHub
Returns the root domain of the provided domain
Example:
>>> parse_domain('https://www.mymagento.com/') 'mymagento.com'
- magento.utils.get_agents()[source]View on GitHub
Scrapes a list of user agents. Returns a default list if the scrape fails.
- Return type
- magento.utils.get_agent(index=0)[source]View on GitHub
Returns a single user agent string from the specified index of the AGENTS list
- Return type
- class magento.utils.LoggerUtils[source]View on GitHub
Bases:
object
Utility class that simplifies access to logger handler info
- static get_handler_names(logger)[source]View on GitHub
Get all handler names
- static get_stream_handlers(logger)[source]View on GitHub
Get all the StreamHandlers of the current logger (NOTE: StreamHandler subclasses excluded)
- static get_file_handlers(logger)[source]View on GitHub
Get all the FileHandlers of the current logger
- Return type
- static get_log_files(logger)[source]View on GitHub
Get the log file paths from all FileHandlers of a logger
- static get_handler_by_log_file(logger, log_file)[source]View on GitHub
Returns the FileHandler logging to the specified file, given it exists
- Return type
- static clear_handlers(logger)[source]View on GitHub
- Return type
- static clear_stream_handlers(logger)[source]View on GitHub
Removes all StreamHandlers from a logger
- Return type
- static clear_file_handlers(logger)[source]View on GitHub
Removes all FileHandlers from a logger
- Return type
- static map_handlers_by_name(logger)[source]View on GitHub
Map the handlers of a logger first by type, and then by their name
FileHandlers are mapped to both their handlers and log file, while StreamHandlers are just mapped to the handler Handlers without a name will be skipped, because look at the method name (:
- class magento.utils.MagentoLogger(name, log_file=None, stdout_level='INFO', log_requests=True)[source]View on GitHub
Bases:
object
Logging class used within the package
- Variables
PREFIX – hardcoded prefix to use in log messages
PACKAGE_LOG_NAME – the default name for the package logger
CLIENT_LOG_NAME – the default format for the client logger name
LOG_MESSAGE – the default format for the message component of log messages. (Use magento.logger.LOG_MESSAGE for easy access)
FORMATTER – the default logging format
HANDLER_NAME – the default format for the names of handlers created by this package
- PREFIX = 'MyMagento'
- PACKAGE_LOG_NAME = 'my-magento'
- CLIENT_LOG_NAME = '{domain}_{username}'
- HANDLER_NAME = 'MyMagento__{name}__{stdout_level}'
- LOG_MESSAGE = '|[ MyMagento | {name} ]|: {message}'
- FORMATTER = <logging.Formatter object>
- __init__(name, log_file=None, stdout_level='INFO', log_requests=True)[source]View on GitHub
Initialize the logger
Each Client object corresponds to a unique username/domain combination, which is used to attach it to its associated MagentoLogger and log file, allowing all activity across all endpoints to be tracked. A package logger exists as well, which logs all activity from the package. All log files have their log level set to DEBUG
- Parameters
- setup_logger(stdout_level='INFO', log_requests=True)[source]View on GitHub
Configures a logger and assigns it to the logger attribute.
- format_msg(msg)[source]View on GitHub
Formats the
LOG_MESSAGE
using the specified message- Return type
- debug(msg)[source]View on GitHub
Formats the
LOG_MESSAGE
with the specified message, then logs it with Logger.debug()
- info(msg)[source]View on GitHub
Formats the
LOG_MESSAGE
with the specified message, then logs it with Logger.info()
- error(msg)[source]View on GitHub
Formats the
LOG_MESSAGE
with the specified message, then logs it with Logger.error()
- warning(msg)[source]View on GitHub
Formats the
LOG_MESSAGE
with the specified message, then logs it with Logger.warning()
- critical(msg)[source]View on GitHub
Formats the
LOG_MESSAGE
with the specified message, then logs it with Logger.critical()
- property handlers
- property handler_names
- property handler_map
- property file_handlers
- property stream_handlers
- property log_files
- property log_path
- static get_magento_handlers(logger)[source]View on GitHub
- static clear_magento_handlers(logger, handler_type, clear_pkg=False)[source]View on GitHub
Clear all handlers from a logger that were created by MagentoLogger
- Parameters
logger (Logger) – any logger
handler_type (Union[Type[FileHandler], Type[StreamHandler]]) – the logging handler type to check for and remove
clear_pkg (bool) – if True, will delete the package handler for writing to my-magento.log (Default is False)
- static clear_magento_file_handlers(logger, clear_pkg=False)[source]View on GitHub
- static clear_magento_stdout_handlers(logger, clear_pkg=False)[source]View on GitHub
- static owns_handler(handler)[source]View on GitHub
Checks if a handler is a Stream/FileHandler from this package or not
- static get_package_handler()[source]View on GitHub
Returns the FileHandler object that writes to the magento.log file
- Return type
- static add_request_logging(handler)[source]View on GitHub
Adds the specified handler to the requests package logger, allowing for easier debugging of API calls
- magento.utils.get_package_file_handler()[source]View on GitHub
…
Subpackages
The magento.models
subpackage
The magento.models
subpackage contains all of the Model
API response wrapper classes.
The model
module
- class magento.models.model.Model(data, client, endpoint, private_keys=True)[source]View on GitHub
Bases:
ABC
The abstract base class of all API response wrapper classes
Overview
A
Model
wraps the responsedata
from an APIendpoint
Several endpoints have subclasses with additional methods to retrieve/update data
All other endpoints are wrapped using a general
APIResponse
The endpoint’s corresponding
SearchQuery
can be accessed viaquery_endpoint()
- DOCUMENTATION: str = None
Link to the Official Magento 2 API documentation for the endpoint wrapped by the Model
- __init__(data, client, endpoint, private_keys=True)[source]View on GitHub
Initialize a
Model
object from an API response and theendpoint
that it came from…
Tip
The
endpoint
is used to:Generate the
url_for()
any requests made by subclass-specific methodsMatch the
Model
to its correspondingSearchQuery
objectDetermine how to
parse()
newModel
objects from API responses
…
- Parameters
- set_attrs(data, private_keys=True)[source]View on GitHub
Initializes object attributes using the JSON from an API response as the data source
Called at the time of object initialization, but can also be used to update the source data and reinitialize the attributes without creating a new object
- Parameters
data (dict) – the API response JSON to use as the object source data
private_keys (bool) – if set to True, will set the
excluded_keys
as private attributes (prefixed with__
) instead of fully excluding them
Private Keys Clarification
Let’s say that
"status"
is in theexcluded_keys
No matter what, the
status
attribute will not be set on theModel
If
private_keys==True
, the__status
attribute will be set (using thestatus
data)If
private_keys==False
, the data fromstatus
is completely excluded
- abstract property excluded_keys: List[str]
API response keys that shouldn’t be set as object attributes by
set_attrs()
- Returns
list of API response keys that shouldn’t be set as attributes
- property uid: Union[str, int]
Unique item identifier; used in the url of the
data_endpoint()
- data_endpoint(scope=None)[source]View on GitHub
Endpoint to use when requesting/updating the item’s data
- query_endpoint()[source]View on GitHub
Initializes and returns the
SearchQuery
object corresponding to the Model’sendpoint
- Returns
a
SearchQuery
or subclass, depending on theendpoint
- Return type
- parse(response)[source]View on GitHub
Uses the instance’s corresponding
SearchQuery
to parse an API response
- refresh(scope=None)[source]View on GitHub
Updates object attributes in place using current data from the
data_endpoint()
Hint
refresh()
can be used to switch the scope of the source data without creating a new object or changing theClient.scope
Example
# Get product data on 'default' scope >>> product = client.products.by_sku('sku42') # Get fresh product data from different scope >>> product.refresh('all') Refreshed <Magento Product: sku42> on scope all
- Parameters
scope (Optional[str]) – the scope to send the request on; uses the
Client.scope
if not provided- Return type
- static unpack_attributes(attributes, key='attribute_code')[source]View on GitHub
Unpacks a list of attribute dictionaries into a single dictionary
Example
>> custom_attrs = [{'attribute_code': 'attr', 'value': 'val'},{'attribute_code': 'will_to_live', 'value': '0'}] >> print(Model.unpack_attributes(custom_attrs)) {'attr': 'val', 'will_to_live': '0'}
- static pack_attributes(attribute_data, key='attribute_code')[source]View on GitHub
Packs a dictionary containing attributes into a list of attribute dictionaries
Example
>> attribute_data = {'special_price': 12, 'meta_title': 'My Product'} >> print(Model.pack_attributes(attribute_data)) >> print(Model.pack_attributes(attribute_data, key='label')) [{'attribute_code': 'special_price', 'value': 12}, {'attribute_code': 'meta_title', 'value': 'My Product'}] [{'label': 'special_price', 'value': 12}, {'label': 'meta_title', 'value': 'My Product'}]
- static encode(string)[source]View on GitHub
URL-encode with
urllib.parse
; used for requests that could contain special characters
- property cached: List[str]
Names of properties that are wrapped with
functools.cached_property()
- clear(*keys)[source]View on GitHub
Deletes the provided keys from the object’s
__dict__
To clear all cached properties:
>> self.clear(*self.cached)
- Parameters
keys (str) – name of the object attribute(s) to delete
- get_scope_name(scope)[source]View on GitHub
Returns the appropriate scope name to use for logging messages
- Return type
…
- class magento.models.model.APIResponse(data, client, endpoint)[source]View on GitHub
Bases:
Model
- __init__(data, client, endpoint)[source]View on GitHub
A generic
Model
subclassWraps API responses when there isn’t a
Model
subclass defined for theendpoint
- property excluded_keys: List[str]
API response keys that shouldn’t be set as object attributes by
set_attrs()
- Returns
list of API response keys that shouldn’t be set as attributes
- property uid: Optional[int]
Unique item identifier
Note
Since the
APIResponse
can wrap any endpoint, the response is checked for commonly used id fields (entity_id
andid
)If the endpoint doesn’t use those fields,
None
will be returned
The product
module
- class magento.models.product.Product(data, client)[source]View on GitHub
Bases:
Model
Wrapper for the
products
endpoint- STATUS_ENABLED = 1
- STATUS_DISABLED = 2
- VISIBILITY_NOT_VISIBLE = 1
- VISIBILITY_CATALOG = 2
- VISIBILITY_SEARCH = 3
- VISIBILITY_BOTH = 4
- DOCUMENTATION: str = 'https://adobe-commerce.redoc.ly/2.3.7-admin/tag/products/'
Link to the Official Magento 2 API documentation for the endpoint wrapped by the Model
- __init__(data, client)[source]View on GitHub
Initialize a Product object using an API response from the
products
endpoint
- property excluded_keys
API response keys that shouldn’t be set as object attributes by
set_attrs()
- Returns
list of API response keys that shouldn’t be set as attributes
- update_stock(qty)[source]View on GitHub
Updates the stock quantity
- update_status(status)[source]View on GitHub
Update the product status
- Parameters
status (int) – either 1 (for
STATUS_ENABLED
) or 2 (forSTATUS_DISABLED
)- Return type
- update_price(price)[source]View on GitHub
Update the product price
- update_special_price(price)[source]View on GitHub
Update the product special price
- update_name(name, scope=None)[source]View on GitHub
Update the product name
- Parameters
name (str) – the new name to use
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided
- Return type
- update_description(description, scope=None)[source]View on GitHub
Update the product description
- Parameters
description (str) – the new HTML description to use
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided
- Return type
- update_metadata(metadata, scope=None)[source]View on GitHub
Update the product metadata
- Parameters
metadata (dict) – the new
meta_title
,meta_keyword
and/ormeta_description
to usescope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided
- Return type
- update_attributes(attribute_data, scope=None)[source]View on GitHub
Update top level product attributes with scoping taken into account
Note
Product attributes can have a
Global
,Store View
orWebsite
scope- Global Attributes
Values are updated on all store views and the admin
- Website Attributes
Values are updated on all store views
- Store View Attributes
Values are updated on the store view specified in the request
scope
A second request will be made to update
Store View
andWebsite
attributes on the admin, depending on how manyStore
views
you have:1 View: admin values are updated for all attributes, regardless of scope
2+ Views: admin values are updated only for
website_product_attributes
- Parameters
attribute_data (dict) – a dictionary of product attributes to update
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided
- Return type
- update_custom_attributes(attribute_data, scope=None)[source]View on GitHub
Update custom attributes with scoping taken into account
See
update_attributes()
for detailsImportant
This method only supports updating custom attributes
- Parameters
attribute_data (dict) – a dictionary of custom attributes to update
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided
- Return type
- get_orders()[source]View on GitHub
Searches for orders that contain the product
If the product is configurable, returns orders containing any of its child products
- get_order_items()[source]View on GitHub
Searches for order items that contain the product
If the product is configurable, returns order items containing any of its child products
- get_invoices()[source]View on GitHub
Searches for invoices that contain the product
If the product is configurable, returns invoices containing any of its child products
- delete()[source]View on GitHub
Deletes the product
Hint
If you delete a product by accident, the
Product
object’sdata
attribute will still contain the raw data, which can be used to recover it.Alternatively, don’t delete it by accident.
- Return type
- get_children(refresh=False, scope=None)[source]View on GitHub
Retrieve the child simple products of a configurable product
- property children: List[Product]
If the Product is a configurable product, returns a list of its child products
- property categories: Optional[Category | List[Category]]
Categories the product is in, returned as a list of
Category
objects
- property media_gallery_entries: List[MediaEntry]
The product’s media gallery entries, returned as a list of
MediaEntry
objects
- property thumbnail: MediaEntry
The
MediaEntry
corresponding to the product’s thumbnail
- get_media_by_id(entry_id)[source]View on GitHub
Access a
MediaEntry
of the product by id- Parameters
entry_id (int) – the id of the media gallery entry
- Return type
- property option_skus: List[str]
The full SKUs for the product’s customizable options, if they exist
- property stock_item_id: int
Item id of the StockItem, used to
update_stock()
- class magento.models.product.MediaEntry(product, entry)[source]View on GitHub
Bases:
Model
Wraps a media gallery entry of a
Product
- MEDIA_TYPES = ['base', 'small', 'thumbnail', 'swatch']
- DOCUMENTATION: str = 'https://adobe-commerce.redoc.ly/2.3.7-admin/tag/productsskumediaentryId'
Link to the Official Magento 2 API documentation for the endpoint wrapped by the Model
- __init__(product, entry)[source]View on GitHub
Initialize a MediaEntry object for a
Product
- query_endpoint()[source]View on GitHub
No search endpoint exists for media gallery entries
- property excluded_keys: List[str]
API response keys that shouldn’t be set as object attributes by
set_attrs()
- Returns
list of API response keys that shouldn’t be set as attributes
- property is_enabled
- property is_thumbnail
- property link
Permalink to the image
- disable(scope=None)[source]View on GitHub
Disables the MediaEntry on the given scope
- Parameters
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided- Return type
- enable(scope=None)[source]View on GitHub
Enables the MediaEntry on the given scope
- Parameters
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided- Return type
- add_media_type(media_type, scope=None)[source]View on GitHub
Add a media type to the MediaEntry on the given scope
Caution
If the media type is already assigned to a different entry, it will be removed
- Parameters
media_type (str) – one of the
MEDIA_TYPES
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided
- Return type
- remove_media_type(media_type, scope=None)[source]View on GitHub
Remove a media type from the MediaEntry on the given scope
- Parameters
media_type (str) – one of the
MEDIA_TYPES
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided
- Return type
- set_media_types(types, scope=None)[source]View on GitHub
Set media types for the MediaEntry on the given scope
- Parameters
types (list) – a list containing all
MEDIA_TYPES
to assignscope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided
- Return type
- set_position(position, scope=None)[source]View on GitHub
Set the position of the MediaEntry on the given scope
- Parameters
position (int) – the position to change to
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided
- Return type
- set_alt_text(text, scope=None)[source]View on GitHub
Set the alt text (
label
) of the MediaEntry on the given scope- Parameters
text (str) – the alt text to use
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided
- Return type
- update(scope=None)[source]View on GitHub
Uses the
data
dict to update the media entryNote
Some updates alter the data of other entries; if the update is successful, the associated
Product
will be refreshed on the same scope to keep the data consistentTip
If there’s only 1 store view, the admin will also be updated
- Parameters
scope (Optional[str]) – the scope to send the request on; will use the
Client.scope
if not provided- Return type
- class magento.models.product.ProductAttribute(data, client)[source]View on GitHub
Bases:
Model
Wrapper for the
products/attributes
endpoint- DOCUMENTATION: str = 'https://adobe-commerce.redoc.ly/2.3.7-admin/tag/productsattributes/'
Link to the Official Magento 2 API documentation for the endpoint wrapped by the Model
- __init__(data, client)[source]View on GitHub
Initialize a ProductAttribute object using an API response from the
products/attributes
endpoint
- property excluded_keys: List[str]
API response keys that shouldn’t be set as object attributes by
set_attrs()
- Returns
list of API response keys that shouldn’t be set as attributes
- property options
The category
module
- class magento.models.category.Category(data, client)[source]View on GitHub
Bases:
Model
Wrapper for the
categories
endpoint- DOCUMENTATION: str = 'https://adobe-commerce.redoc.ly/2.3.7-admin/tag/categories'
Link to the Official Magento 2 API documentation for the endpoint wrapped by the Model
- __init__(data, client)[source]View on GitHub
Initialize a Category object using an API response from the
categories
endpoint- Parameters
data (dict) – raw API response
- property excluded_keys
API response keys that shouldn’t be set as object attributes by
set_attrs()
- Returns
list of API response keys that shouldn’t be set as attributes
- property subcategories: List[Category]
The child categories, returned as a list of
Category
objectsNote
Only the direct child categories are returned. For a list of all descendants, use
all_subcategories
- property subcategory_ids: List[int]
The
category_ids
of thesubcategories
- property subcategory_names: List[str]
The names of the category’s
subcategories
- property all_subcategories: Optional[List[Category]]
Recursively retrieves all descendants of the category
- property all_subcategory_ids: List[int]
The
category_ids
ofall_subcategories
- property products: List[Product]
The
Product
s in the categoryAlias for
get_products()
- property all_products: List[Product]
The
Product
s in the category and inall_subcategories
Alias for
get_products()
withsearch_subcategories=True
- property all_product_ids: Set[int]
The
product_ids
of the products in the category and inall_subcategories
- property all_skus: Set[str]
The skus of the products in the category and in
all_subcategories
- get_products(search_subcategories=False)[source]View on GitHub
Retrieves the category’s products
- Parameters
search_subcategories (bool) – if
True
, also retrieves products fromall_subcategories
- Return type
- get_orders(search_subcategories=False)[source]View on GitHub
Retrieve any
Order
that contains one of the category’sproducts
- Parameters
search_subcategories (bool) – if
True
, also searches for orders fromall_subcategories
- Return type
- get_order_items(search_subcategories=False)[source]View on GitHub
Retrieve any
OrderItem
that contains one of the category’sproducts
- Parameters
search_subcategories (bool) – if
True
, also searches for order items fromall_subcategories
- Return type
- get_invoices(search_subcategories=False)[source]View on GitHub
Retrieve any
Invoice
that contains one of the category’sproducts
- Parameters
search_subcategories (bool) – if
True
, also searches for invoices fromall_subcategories
- Return type
The order
module
- class magento.models.order.Order(data, client)[source]View on GitHub
Bases:
Model
Wrapper for the
orders
endpoint- DOCUMENTATION: str = 'https://adobe-commerce.redoc.ly/2.3.7-admin/tag/orders'
Link to the Official Magento 2 API documentation for the endpoint wrapped by the Model
- __init__(data, client)[source]View on GitHub
Initialize an Order object using an API response from the
orders
endpoint
- property excluded_keys: List[str]
API response keys that shouldn’t be set as object attributes by
set_attrs()
- Returns
list of API response keys that shouldn’t be set as attributes
- property items: List[OrderItem]
The ordered items, returned as a list of
OrderItem
objectsNote
When a configurable
Product
is ordered, the API returns data for both the configurable and simple productThe
OrderItem
is initialized using the configurable product data, since the simple product data is incompleteThe
product
andproduct_id
will still match the simple product though
If both entries are needed, the unparsed response is in the
data
dict
- property products: List[Product]
The ordered
items
, returned as their correspondingProduct
objects
- get_invoice()[source]View on GitHub
Retrieve the
Invoice
of the Order- Return type
- property ship_to: dict
Condensed version of the
shipping_address
dict
- class magento.models.order.OrderItem(item, client=None, order=None)[source]View on GitHub
Bases:
Model
Wrapper for the
order/items
endpoint- DOCUMENTATION: str = 'https://adobe-commerce.redoc.ly/2.3.7-admin/tag/ordersitems'
Link to the Official Magento 2 API documentation for the endpoint wrapped by the Model
- __init__(item, client=None, order=None)[source]View on GitHub
Initialize an OrderItem using an API response from the
orders/items
endpoint
- property excluded_keys: List[str]
API response keys that shouldn’t be set as object attributes by
set_attrs()
- Returns
list of API response keys that shouldn’t be set as attributes
- property product: Product
The item’s corresponding
Product
Note
If the ordered item:
Is a configurable product - the child simple product is returned
Has custom options - the base product is returned
The invoice
module
- class magento.models.invoice.Invoice(data, client)[source]View on GitHub
Bases:
Model
Wrapper for the
invoices
endpoint- DOCUMENTATION: str = 'https://adobe-commerce.redoc.ly/2.3.7-admin/tag/invoices'
Link to the Official Magento 2 API documentation for the endpoint wrapped by the Model
- __init__(data, client)[source]View on GitHub
Initialize an Invoice object using an API response from the
invoices
endpoint
- property excluded_keys: List[str]
API response keys that shouldn’t be set as object attributes by
set_attrs()
- Returns
list of API response keys that shouldn’t be set as attributes
- property items: List[InvoiceItem]
The invoiced items, returned as a list of
InvoiceItem
objects
- class magento.models.invoice.InvoiceItem(item, invoice)[source]View on GitHub
Bases:
Model
Wraps an item entry of an
Invoice
- DOCUMENTATION: str = 'https://adobe-commerce.redoc.ly/2.3.7-admin/tag/invoicesid'
Link to the Official Magento 2 API documentation for the endpoint wrapped by the Model
- __init__(item, invoice)[source]View on GitHub
Initialize an InvoiceItem of an
Invoice
- data_endpoint(scope=None)[source]View on GitHub
No data endpoint exists for invoice items
- query_endpoint()[source]View on GitHub
No search endpoint exists for invoice items
- property excluded_keys: List[str]
API response keys that shouldn’t be set as object attributes by
set_attrs()
- Returns
list of API response keys that shouldn’t be set as attributes
Get a Magento 2 REST API Token With MyMagento
Let’s generate a Magento 2 REST API token using the MyMagento REST API wrapper package.
Setting the Login Credentials
Use your Magento 2 login credentials to generate an ACCESS_TOKEN
domain = 'domain.com'
username ='username'
password = 'password'
If you’re using a local installation of Magento, your domain should look like this:
domain = '127.0.0.1/path/to/magento'
Getting a Client
Now that that’s set that up, let’s start using the API.
MyMagento uses the Client
class to handle all interactions with the API
import magento
api = magento.get_api(domain=domain, username=username, password=password, local=True)
2023-02-15 01:09:05 INFO |[ MyMagento | 127_adam ]|: Authenticating adam on 127.0.0.1/magento24...
2023-02-15 01:09:06 INFO |[ MyMagento | 127_adam ]|: Logged in to adam
Setting Environment Variables
To log in faster in the future, you can set the following environment variables:
import os
os.environ['MAGENTO_DOMAIN'] = domain
os.environ['MAGENTO_USERNAME']= username
os.environ['MAGENTO_PASSWORD']= password
The Client
can now be initialized as follows
import magento
api = magento.get_api(local=True)
2023-02-15 01:09:28 INFO |[ MyMagento | 127_adam ]|: Authenticating adam on 127.0.0.1/magento24...
2023-02-15 01:09:30 INFO |[ MyMagento | 127_adam ]|: Logged in to adam
Add discount on each product based on product price
I saw this question on Magento StackExchange:
Question
I have 100 products in my store and each product has different price. I want to add discount on each product based on specific price. For example, If a product is added into the cart and it has 100usd price then i want to apply 10% discount on it and if a product is added into the cart and it has 110usd price then i want to apply 11% discount on it and so on. I hope you understand what I want to achieve. in simple words, discount on each product based on product price. Thanks
Solution Using MyMagento
First, you’ll want to Get a Magento 2 REST API Token With MyMagento
import magento
>>> api = magento.get_api()
Let’s say we have the skus of the 100 products in an array.
We can use a ProductSearch
retrieve these products as Product
objects using by_skulist()
>>> skus = [f"test_sku{n}" for n in range(1, 101)]
>>> products = api.products.by_skulist(skus)
To retrieve the Product
objects using a field other than sku
, like product_id
, we can use by_list()
:
>>> product_ids = list(range(1,101))
>>> products = api.products.by_list(
... field="entity_id", # To search by product_id
... values=product_ids
... )
Once we have our list of Product
objects, we can calculate the discount based on their price, then update the special_price
(discount price) using the Product.update_special_price()
method
>>> for product in products:
... if product.price < 100:
... continue
...
... discount = product.price / 1000
... price = product.price * (1 - discount)
... product.update_special_price(round(price, 2))
We loop through our list of products and
Skip the products if the
price
is not $100 or moreCalculate the discount percentage by dividing the
price
by 1000Calculate the new, discounted product price by multiplying the current
price
by1 - discount
Use the new price we calculated to update the
special_price
of the product
Changelog
v2.1.0
Added
get_api()
to login using credentials stored in environment variablesThe environment variables
MAGENTO_USERNAME
,MAGENTO_PASSWORD
,MAGENTO_DOMAIN
will be used if thedomain
,username
orpassword
kwargs are missing
import magento
>>> magento.get_api()
2023-02-08 03:34:20 INFO |[ MyMagento | 127_user ]|: Authenticating user on 127.0.0.1/path/to/magento
2023-02-08 03:34:23 INFO |[ MyMagento | 127_user ]|: Logged in to user
<magento.clients.Client object at 0x000001CA83E1A200>
…
Added
local
kwarg toClient
to support locally hosted Magento stores and test environmentsBy default,
local=False
from magento import Client
>>> api = Client("127.0.0.1/path/to/magento", "username", "password", local=True)
…
Add
since()
anduntil()
method toSearchQuery
classes, which search thecreated_at
fieldThey can be chained together and also with
add_criteria()
Example
# Retrieve orders from the first 7 days of 2023
>>> api.orders.since("2023-01-01").until("2023-01-07").execute()
[<Magento Order: #000000012 placed on 2023-01-02 05:19:55>, ]
Example
# Retrieve orders over $50 placed since 2022
>>> api.orders.add_criteria(
... field="grand_total",
... value="50",
... condition="gteq"
... ).since("2022-01-01").execute()
[<Magento Order: #000000003 placed on 2022-12-21 08:09:33>, ...]
…
Changed
add_criteria()
to auto-increment the filter group by default if no group is specified (ie.AND
condition)
# Retrieving products that are over $10 AND in the category with id 15
#
# Before v2.1.0
>>> api.products.add_criteria('category_id','15').add_criteria('price','10','gteq', group=1)
# v2.1.0+
>>> api.products.add_criteria('category_id','15').add_criteria('price','10','gteq')
…
Changed the
Client.BASE_URL
to not include"www."
at the start (see #8)Added unit tests for
url_for()
Added Jupyter notebook examples