Skip to content

OneSila/OneSilaMagento2Api

Β 
Β 

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 https://static.pepy.tech/personalized-badge/my-magento?period=total&units=none&left_color=grey&right_color=blue&left_text=Downloads 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 |.~.Manager|_ Subclasses

  • Manages interaction with API endpoints
  • Allows executing searches, creating, and updating resources
  • Provides an intuitive interface for Managing Resources
  • Supports advanced operations like get_or_create, simplifying workflows

🧠 The Model Subclasses

  • Wrap all API responses in the package
  • Provide additional endpoint-specific methods to retrieve and update data
  • FetchedOnlyModel subclass can only be retrieved from the API, not created directly
  • ImmutableModel subclass cannot be modified after initialization and throws an error if save() is called

...

Available Endpoints

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|_

...

βš™ Installing MyMagento

To install using pip:

pip install onesila-magneto

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

Managing Resources with Managers

The |.~.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}")

Building Custom Queries with Managers

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)

Managing Immutable Models

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}")

Managing Fetched-Only Models

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}")

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.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>

About

Python Magento 2 REST API Wrapper

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python 100.0%