π What's MyMagento? |
|---|
|
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.
...
π» The |
|---|
|
π The |.~.Manager|_ Subclasses |
|---|
|
π§ The |
|---|
|
...
MyMagento is compatible with every API endpoint
Endpoints are wrapped with a Model and |.~.Manager|_ subclass as follows:
| Endpoint | Client Shortcut | |.~.Manager|_ Subclass | Model Subclass |
|---|---|---|---|
orders |
Client.orders |
|.~.OrderManager|_ | Order |
orders/items |
Client.order_items |
|.~.OrderItemManager|_ | OrderItem |
invoices |
Client.invoices |
|.~.InvoiceManager|_ | Invoice |
products |
Client.products |
|.~.ProductManager|_ | Product |
products/attributes |
Client.product_attributes |
|.~.ProductAttributeManager|_ | ProductAttribute |
products/attributes/{attribute_code}/options |
|..Client.product_attribute_options|_ | |.~.ProductAttributeOptionManager|_ | |.~.AttributeOption|_ |
categories |
Client.categories |
|.~.CategoryManager|_ | Category |
customers |
Client.customers |
|.~.CustomerManager|_ | Customer |
shipments |
|..Client.shipments|_ | |.~.ShipmentManager|_ | |.~.Shipment|_ |
attribute_sets |
|..Client.attribute_sets|_ | |.~.AttributeSetManager|_ | |.~.AttributeSet|_ |
...
To install using pip:
pip install onesila-magneto
Please note that MyMagento requires Python >= 3.10
...
Full documentation can be found on ReadTheDocs
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 |
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, orpasswordare 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 usernameThe |.~.Manager|_ subclasses now handle all interactions with API endpoints, including searching, creating, and updating resources.
Basic Example: Searching for an order by ID
order = api.orders.by_id(12345)
print(order)Creating a New Product:
product_data = {
"sku": "new-sku",
"name": "New Product",
"attribute_set_id": 4,
"price": 199.99,
}
product = api.products.create(data=product_data)
print(product)Using `get_or_create`:
product, created = api.products.get_or_create(
data={
"sku": "existing-sku",
"name": "Existing Product",
"attribute_set_id": 4,
"price": 199.99,
},
identifier="sku"
)
if created:
print("New product created:", product)
else:
print("Product already exists:", product)Saving Changes to a Model:
attribute = api.product_attributes.by_code('test')
option = AttributeOption(data={}, attribute=attribute, client=api)
option.label = 'New Label'
option.sort_order = 3
option.save()
print(f"Attribute option saved with label: {option.label}")While predefined methods cover most use cases, you can still build custom queries using Managers.
Example: Retrieve Orders Over $50 Placed Since 2023:
orders = api.orders.add_criteria(
field="grand_total",
value="50",
condition="gt"
).since("2023-01-01").execute_search()
for order in orders:
print(order)Example: Get or Create an Attribute Option:
attribute = api.product_attributes.by_code('color')
option, created = api.product_attribute_options.get_or_create(
data={"label": "Red", "sort_order": 1},
identifier="label"
)
if created:
print("New option created:", option)
else:
print("Option already exists:", option)The ImmutableModel subclass is designed for resources that cannot be modified after creation. Calling save() on an instance of this subclass will raise an OperationNotAllowedError.
Example:
immutable_instance = ImmutableModel(data={}, client=api)
try:
immutable_instance.save()
except OperationNotAllowedError as e:
print(f"Error: {e}")The FetchedOnlyModel subclass can only be retrieved via API calls and cannot be created directly. Attempting to initialize this model for creation will raise an OperationNotAllowedError.
Example:
try:
fetched_instance = FetchedOnlyModel(data={}, client=api, endpoint='endpoint', fetched=False)
except OperationNotAllowedError as e:
print(f"Error: {e}")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 # Retrieve credit memo with id 7 using a search
>>> memo = api.manager("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> |
