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)View on GitHub
View Source Code
def search(self, endpoint: str) -> SearchQuery: """Initializes and returns a :class:`~.SearchQuery` corresponding to the specified endpoint .. note:: Several endpoints have predefined :class:`~.SearchQuery` and :class:`~.Model` subclasses If a subclass hasn't been defined for the ``endpoint`` yet, a general :class:`~.SearchQuery` will be returned, which wraps the :attr:`~.SearchQuery.result` with :class:`~.APIResponse` :param endpoint: a valid Magento API search endpoint """ if endpoint.lower() == 'orders': return self.orders if endpoint.lower() == 'orders/items': return self.order_items if endpoint.lower() == 'invoices': return self.invoices if endpoint.lower() == 'categories': return self.categories if endpoint.lower() == 'products': return self.products if endpoint.lower() == 'products/attributes': return self.product_attributes if endpoint.lower() in ('customers', 'customers/search'): return self.customers # Any other endpoint is queried with a general SearchQuery object return SearchQuery(endpoint=endpoint, client=self) 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)