Skip to content

TDKorn/my-magento

Repository files navigation

Logo for MyMagento: Python Magento 2 REST API Wrapper

MyMagentoπŸ›’

A Python package that wraps and extends the Magento 2 REST API

Explore the docs Β»_

PyPI Version

GitHub Repository

image

Documentation Status

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 endpoint
  • Intuitive 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 SearchQuery_ Subclass Model_ Subclass
orders Client.orders_ OrderSearch_ Order_
orders/items Client.order_items_ OrderItemSearch_ OrderItem_
invoices Client.invoices_ InvoiceSearch_ Invoice_
products Client.products_ ProductSearch_ Product_
products/attributes Client.product_attributes_ ProductAttributeSearch_ ProductAttribute_
categories Client.categories_ CategorySearch_ Category_
customers Client.customers_ CustomerSearch_ Customer_
endpoint Client.search('endpoint') SearchQuery_ APIResponse_

...

βš™ Installing MyMagento

To install using pip:

pip install my-magento

Please note that MyMagento requires Python >= 3.10

...

πŸ“š Documentation

Full documentation can be found on ReadTheDocs

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, or password 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

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

...

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 store views_
  • Passing the scope keyword argument to Client.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()_, and execute()_ the search
  • The since()_ and until()_ 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>