Recently i had to fetch order information using the Magento 2 API, and to be more specific: The latest orders with a specific status. This turned out to be a bit harder than i initially expected. Magento has some pretty good documentation on this subject, but i still needed a little bit tinkering to get the right result.
Authentication
First: You can't access orders directly, you need to authenticate yourself before you can retrieve them. There are different kinds of authentication methods available, depending on your needs. To retrieve the orders you need the integration
or the admin
token type. For development the admin
type is the easiest. You can retrieve a token by executing this request:
POST https://<URL>/rest/all/V1/integration/admin/token { username=*USERNAME* password=*PASSWORD* }
This will return a token in json format, which means it's encapsulated in "
. This token needs to be sent with every next request as an Bearer Token
:
Authorization: Bearer hzefhgfmus0sj5djivajqac8ocdm8rq4
Hey, I'm running a developer focussed newsletter called MageDispatch.com, which is for the community and by the community. Here you can share links that you think that the community should know about. If you like this kind of technical content you will like this newsletter too.
Retrieving orders
Next is retrieving the latest orders:
GET https://<URL>/rest/all/V1/orders?searchCriteria[sortOrders][0][field]=created_at
This will give you an array with something like this:
{ "entity_id": 133, "base_grand_total": 107.43, "state": "processing", "items": [ { "base_price": 45, "name": "Erika Running Short-32-Red", // ... } ], "billing_address": { "email": "[email protected]", "firstname": "Veronica", "lastname": "Costello", // ... }, "payment": { // ... }, "status_histories": [ { "status": "pending", // ... } ], "extension_attributes": { // ... } }
Need to filter on the status of the order? Add this variable:
searchCriteria[filter_groups][0][filters][0][value]
If you combine that with the sort order you'll get something like this:
GET https://<URL>/rest/all/V1/orders?searchCriteria[sortOrders][0][field]=created_at&searchCriteria[filter_groups][0][filters][0][value]
Want to respond?