In the following article, we talk about the REST API of Magento 2, describing the lifecycle of an order. Below, you will find out how to prepare a store and manage multiple processes via the Magento 2 REST API. Order-related tasks include such processes as the creation of a new customer, quote, order, invoice, and shipment. Besides, wh shed light on checkout preparations and other aspects of an order-related routine common for Magento 2. Before going any further, let’s take a look at what the REST API is.
The Representational State Transfer or REST is an architectural style developed to simplify and organize the life of distributed hypermedia systems. It shares numerous similarities with other architectural styles. However, there are 6 guiding constraints to follow if you want to have a RESTful interface:
Uniform interface. REST should have a simple interface with visible actions regarding the following areas: resource identification, resource manipulation via representations, self-descriptive messages, and hypermedia application state engine.
Client-server. Another vital constraint to follow is the separation of concerns related to user interface and data storage. The former gets improved portability across multiple platforms, while the latter achieves improved scalability due to simplified server components.
Stateless. All requests from a client to a server must contain data necessary to understand them. At the same time, it is impossible to rely on a stored context on the server. It leads to a situation when a client keeps a session state.
Cacheable. It is necessary to label response data as cacheable or non-cacheable. You can do that either implicitly or explicitly. As a result, a client cache can reuse cacheable response data for later.
Layered system. An architecture is composed of hierarchical layers. The component behavior is constrained in the following manner: a component can see only the immediate layer with which it is interacting.
Code on demand. Client functionality is extendable via applets or scripts, reducing the number of pre-implemented features and, consequently, simplifying clients. However, this constraint is optional.
Resources
A resource is a key abstraction of information in REST. Under a resource, we assume any information that can be named. For instance, it can be a document, a temporal service, or a collection of resources, etc. The identification of a particular resource in REST incorporates a resource identifier.
Every resource is characterized by a representation – the resource state at any particular timestamp that contains metadata, which in its turn describes the data and hypermedia links. A client relies upon this information in the transition to the next desired state. A representation has a data format also known as a media type, which identifies a specification of further processing.
You can consider a truly RESTful API a hypertext, where every addressable information unit carries an address either explicitly or implicitly. In the first case, link and ID attributes are a good example that illustrate the tendency. As for carrying data implicitly, think of an address that can be derived from a media type definition and representation structure. As a result, REST is all about simultaneous presentation of information and controls.
Another important aspect of a resource representation is that it should be self-descriptive. Thus, we eliminate the necessity to know whether a resource is an employee or device, from the perspective of a client. That’s where media-types associated with resources enter the game.
In practice, this way of things leads to the necessity to create lots of custom media-types. Usually, you need one media-type associated with a resource. Also, note that every media type should define a default processing model.
Resource Methods
A resource method is another important thing associated with REST that participates in transitions. Think of it as of a uniform interface. However, there are no strict requirements to follow. It means that you can use HTTP POST instead of HTTP PUT for updating a resource. Your API will still be RESTful.
However, everything required for changing the resource state should become a part of the API response for that resource, including the corresponding methods and state where they leave the representation.
And don’t forget that query-based API results should be represented by a list of links with summary information. Avoid using arrays of original resource representations. This constraint is caused by the query nature: it is not a substitute for resource identification.
You need to follow these principles to create simple, lightweight, and fast REST applications. For further information, Check this material: What is REST.
Swagger
Now, when you know the basics, let’s focus on Magento. The platform uses Swagger to display all REST APIs for installed products and allows you to try them out. You can explore the entire list of Magento Commerce REST APIs for B2B v2.2.
If you are not familiar with Swagger, it is an open-source software solution for designing, building, documenting, and consuming RESTful web services. In addition to the popular Swagger UI tool, the Swagger toolset provides solutions that enable automated documentation, code generation, and test-case generation.
Before You Start
You can find the latest version of the REST API documentation on the Magento 2 Developer Documentation here: REST API Overview. Before we begin the exploration of the order lifecycle in Magento 2, make sure that you comply with the following requirements:
You need a Magento 2.1.3+ instance with sample data to be installed. It is recommended to use a functional Luma store with fitness clothing and accessories. Since the test store doesn’t have a sandbox account for credit card payments, the following guide describes order processing via an offline payment method. Follow this link for further information about the store: Getting Started with Magento Open Source 2.1.
Next, you need a REST client. Postman is a good choice, however, it is possible to utilize any REST client that can send calls to Magento.
After that, you can proceed to the following tutorial that explains how to use the Magento 2 REST API to manage an order lifecycle.
Configure Your Demo Store
The zero-step of this tutorial requires changing several settings of the default Luma store. Otherwise, you won’t be able to run the REST calls described below.
Payment methods
As we’ve mentioned above, we cannot use credit card payments in this tutorial. However, you can rely on the following offline payment methods:
Check/Money Order (checkmo);
Bank Transfer Payment (banktransfer);
Cash on Delivery (cashondelivery);
Purchase Order (purchaseorder);
Zero Subtotal Checkout (free).
The corresponding configuration names are listed in brackets. Note that only the first and last payment methods are enabled by default. Since we need to accept bank transfer payments in this guide, go to Stores -> Settings -> Configuration -> Sales -> Payment Methods, turn on the Bank Transfer Payment method and click Save.
Now, you have to refresh the cache. Usually, Magento 2 sends a notification message, informing about that. There is a link in the message that lets you do it within a few clicks.
Cart price rules
Due to the conditions of this guide – it describes shipping calculations, it is necessary to disable a default cart price rule of Luma – free shipping for a $50 purchase. After deactivating the promotion, you enable a flat rate shipping – $5 per item.
You can disable the cart price rule under Marketing -> Promotions -> Cart Price Rules. Disable the rule ID 2: set the Active switch to No and save the change.
Shipping methods
Magento allows you to ship and calculate shipping charges for all products except downloadable items. Therefore, you must specify how to deliver an order with simple, configurable, bundle, or group products.
The purpose of this guide is to explain the Magento 2 REST API, so you can rely on the offline shipping methods. There is no need to enable UPS or Federal Express to complete this tutorial. Note that the offline shipping methods are pre-configured in the system. You can use the following ones:
Flat rate (flatrate);
Table rate (tablerate);
Free shipping (freeshipping).
Note that the last one is not enabled by default. However, you can change this under Stores -> Settings -> Configuration -> Sales -> Shipping Methods. After saving changes, the system will notify you about the necessity to refresh the cache. Follow the provided link to do that as fast as possible.
Get Your Admin Token
In this guide, we work with the following aspects of the Magento 2 REST API:
Endpoint. Here, we describe the HTTP verb and full path to the endpoint:
1
<HTTP verb>http://<host>/rest/<scope>/<endpoint>
HTTP verb is one of the following: GET, POST, PUT, or DELETE;
hostis an IP address (hostname and optionally, port) of your Magento installation;
scope is used to point to a store the call affects;
endpoint is a full Uniform Resource Identifier to the endpoint. It always begins with /V1.
HTTP headers. All calls require one or more HTTP headers, so this section specifies key/value pairs necessary for the HTTP headers.
Payload. Here, you can find data transferred to Magento.
Response. This section lists data that Magento sends back to the REST client.
So, how to get the admin authorization token in Magento 2 and why is it necessary for?
You need an authorization token since most REST calls to Magento require it. The system uses the token to verify that the caller has rights to access resources. Specify the user username and password in the payload to receive your authorization token.
Note that you can use an admin token for 4 hours by default. However, it is possible to change the admin token lifetime. Go to Stores -> Settings -> Configuration and configure the corresponding option under Services -> OAuth -> Access Token Expiration -> Admin Token Lifetime. You can also find more information here: Token-based authentication.
Use the following endpoint to get the access token:
You get the following admin’s access token as a response:
1
5r8cvmpr11j6gmau8990rcj2qk7unh8i
Note that it is necessary to specify this token in the authorization header of every call if admin permissions are required.
Since tokens are not displayed in the Magento admin, you cannot verify this step.
Create a Customer Account
Since this tutorial teaches how to make an order by a logged-in user, we explain how to create a customer account in Magento 2 using the REST API. However, not only logged-in users can make purchases. A guest buyer who logs in or creates an account after the checkout or remains unsigned can also do that. Magento offers additional REST endpoints for such users.
The following example illustrates a simplified way of creating an account. It defines a customer password using plain text. However, the real practice requires specifying the payload, avoiding the password parameter. In the case of a successful call, Magento notifies a customer with a “Welcome” email that includes a request to set a password. To initiate a password reset email in Magento 2, use this call:
1
PUT/V1/customers/password
Use the following endpoint to create a new customer account:
1
POST<host>/rest/<store_code>/V1/customers
Your header is:
1
Content-Type:application/json
Your payload consists of the following rows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
"customer":{
"email":"jdoe@example.com",
"firstname":"Jane",
"lastname":"Doe",
"addresses":[
{
"defaultShipping":true,
"defaultBilling":true,
"firstname":"Jane",
"lastname":"Doe",
"region":{
"regionCode":"NY",
"region":"New York",
"regionId":43
},
"postcode":"10755",
"street":[
"123 Oak Ave"
],
"city":"Purchase",
"telephone":"512-555-1111",
"countryId":"US"
}
]
},
"password":"Password1"
}
Use a real email address in the third row to receive all notifications related to this REST API practice.
You get the following response:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
{
"id":2,
"group_id":1,
"default_billing":"2",
"default_shipping":"2",
"created_at":"2017-01-31 01:18:13",
"updated_at":"2017-01-31 01:18:13",
"created_in":"Default Store View",
"email":"jdoe@example.com",
"firstname":"Jane",
"lastname":"Doe",
"store_id":1,
"website_id":1,
"addresses":[
{
"id":2,
"customer_id":2,
"region":{
"region_code":"NY",
"region":"New York",
"region_id":43
},
"region_id":43,
"country_id":"US",
"street":[
"123 Oak Ave"
],
"telephone":"512-555-1111",
"postcode":"10755",
"city":"Purchase",
"firstname":"Jane",
"lastname":"Doe",
"default_shipping":true,
"default_billing":true
}
],
"disable_auto_group_change":0
}
As you can see, the user’s id value is 2.
Now, log in to the Luma store as a newly created user to verify this step. Use jdoe@example.com as your username and Password1 as yourpassword, if you didn’t specify other values.
Customer access token
Now, you need to get a customer’s access token. To achieve this goal, you should specify the customer’s username and password in the payload. Note that an admin authorization token and a customer access token are not the same.
Magento 2 lets you use a customer token for 1 hour by default. However, you can specify another expiration parameter in Stores -> Settings –> Configuration. The corresponding section is available under Services -> OAuth -> Access Token Expiration.
Use the following endpoint to get a customer access token:
The response is similar to the one you get in the case of an admin authorization token:
1
q0u66k8h42yaevtchv09uyy3y9gaj2ap
Specify this token in the authorization header of every call the customer makes.
Create a Quote
Magento 2 creates a quote when a customer adds an item to a cart. Next, the system can use the quote to perform the following tasks:
Track items the customer wants to buy;
Gather customer information;
Calculate shipping costs, cart subtotal, etc;
Add shipping fees, taxes, and other costs;
Apply coupons and discounts;
Determine the cart grand total;
Choose applicable payment methods;
Place the order for further fulfillment.
Also, note that there are three scenarios when a shopping cart is created. Each one depends on a different user type. First of all, an admin can create a cart – an admin authorization token is required. Secondly, a logged-in customer can do that – a customer authorization token is needed. Thirdly, a guest user can create an anonymous or guest cart.
Below, we describe the second case. If you want to create a cart on behalf of a guest, use the V1/guest-carts endpoint . Note that this situation doesn’t require an authorization token. The system masks the quoteIdfor the guest customer quote.
Now, let’s see how to create a cart for a logged-in customer with the Magento 2 REST API.
Your endpoint looks as follows:
1
POST<host>/rest/<store_code>/V1/carts/mine
These are the headers:
1
2
Content-Type:application/json
Authorization:Bearer<customer token>
The payload is none.
The response is the following:
1
quoteId:4
Note that there are calls that may refer to this parameter as to the cartId.
Add To Cart
Below, we describe how to add different products to the cart. This tutorial describes steps necessary to place simple, downloadable, and bundle products to the cart using the Magento 2 REST API. Since all the calls are performed on behalf of a customer, you need to specify the customer’s token in the authorization header.
In the case of a guest customer, you should use the V1/guest-carts/<cartId>/items endpoint. No authorization token is needed. However, the payload and response are the same as in the situation with the logged-in customer for all product types. The only exception is a quote ID in the payload.
Simple products
Adding a simple product to a cart with the help of the Magento 2 REST API requires the following parameters: a product SKU and quantity as well as a quote ID generated during the previous step when we created a cart.
Your endpoint for adding a simple product to the cart via the Magento 2 REST API looks as follows:
1
POST<host>/rest/<store_code>/V1/carts/mine/items
These are the headers:
1
2
Content-Type:application/json
Authorization:Bearer<customer token>
The payload contains the following rows:
1
2
3
4
5
6
7
{
"cartItem":{
"sku":"WS12-M-Orange",
"qty":1,
"quote_id":"4"
}
}
And the response looks like that:
1
2
3
4
5
6
7
8
9
{
"item_id":7,
"sku":"WS12-M-Orange",
"qty":1,
"name":"Radiant Tee-M-Orange",
"price":19.99,
"product_type":"simple",
"quote_id":"4"
}
You’ve just added an orange medium-sized women’s t-shirt named Radiant Tee-M-Orange to the cart.
Downloadable products
The situation with downloadable products is the same. The Magento 2 REST API requires specifying SKU, quantity, and quote ID to add them to the cart.
Use this endpoint:
1
POST<host>/rest/<store_code>/V1/carts/mine/items
With the following headers:
1
2
Content-Type:application/json
Authorization:Bearer<customer token>
The payload looks as follows:
1
2
3
4
5
6
7
{
"cartItem":{
"sku":"240-LV08",
"qty":1,
"quote_id":"4"
}
}
As a result, you get this response:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"item_id":8,
"sku":"240-LV08",
"qty":1,
"name":"Advanced Pilates & Yoga (Strength)",
"price":18,
"product_type":"downloadable",
"quote_id":"4",
"product_option":{
"extension_attributes":{
"downloadable_option":{
"downloadable_links":[
5
]
}
}
}
}
You’ve just added the downloadable product called Advanced Pilates & Yoga to the cart with the help of the Magento 2 REST API.
Configurable products
The situation differs a little bit when it comes to configurable products. In addition to the product’s SKU, you also need to specify the set of option_id/option_value pairs. Below, we shed light on how to add a configurable product that comes in three colors and five sized to the cart. The colors are black, gray, and orange; the sizes – XS, S, M, L, and XL.
The sample data of the Luma store uses the following option_idvalues for Size and Color – 141 and 93. You can use the following call to determine the option_id values for the given SKU:
1
GET/V1/configurable-products/:sku/options/all
To see information about each combination of color and size, use this call:
1
GET/V1/configurable-products/:sku/children
Below, you can see the returned values for the size – 168 – and color – 52 – options of a small gray Chaz Kangeroo Hoodie.
1
2
3
4
5
6
7
8
9
10
11
12
{
"custom_attributes":[
{
"attribute_code":"size",
"value":"168"
},
{
"attribute_code":"color",
"value":"52"
}
]
}
This information is necessary to add the product to the cart via the Magento 2 REST API. Your endpoint is the following:
1
POST<host>/rest/<store_code>/V1/carts/mine/items
The headers include the following information:
1
2
Content-Type:application/json
Authorization:Bearer<customer token>
Your payload looks as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
"cartItem":{
"sku":"MH01",
"qty":1,
"quote_id":"4",
"product_option":{
"extension_attributes":{
"configurable_item_options":[
{
"option_id":"93",
"option_value":52
},
{
"option_id":"141",
"option_value":168
}
]
}
},
"extension_attributes":{}
}
}
As a result, you get this response:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"item_id":13,
"sku":"MH01-S-Gray",
"qty":1,
"name":"Chaz Kangeroo Hoodie",
"price":52,
"product_type":"configurable",
"quote_id":"4",
"product_option":{
"extension_attributes":{
"configurable_item_options":[
{
"option_id":"93",
"option_value":52
},
{
"option_id":"141",
"option_value":168
}
]
}
}
}
Bundle products
The more product options and conditions you have, the bigger your code should be. When it comes to bundle products, your payload is much bigger than in the case of the previous examples.
Let’s take a look at a bundled product available in Luma. It is the Sprite Yoga Companion Kit. Its SKU is 24-WG080. The kit consists of the four items, two of which are available in three variations.
The first product of the bundle is Sprite Statis Ball. It is available in three sizes:
55 cm – SKU: 24-WG081-blue
65 cm – SKU: 24-WG082-blue
75 cm – SKU: 24-WG083-blue
Next, there is a Sprite Foam Yoga brick in the kit. Its SKU is24-WG084.
Sprite Yoga Strap is the third item. It provides three length options:
6 ft – SKU: 24-WG085
8 ft – SKU: 24-WG086
10 ft – SKU: 24-WG087
Sprite Foam Roller is the last item. Its SKU is 24-WG088.
You can simply add a bundle product to the cart by specifying its SKU. However, it is also necessary to place its individual components separately. It is possible by specifying the idof the item’s product_linksobject.
Magento 2 uses the product_linksobject for ordering and placement of options on the customization page. However, the platform also incorporates it to link the item’s skuand idto the skuof the bundle product.
The response in its simplified form looks as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
[
{
"option_id":1,
"title":"Sprite Stasis Ball",
"required":true,
"type":"radio",
"position":1,
"sku":"24-WG080",
"product_links":[
{
"id":"1",
"sku":"24-WG081-blue",
"option_id":1,
"qty":1
},
{
"id":"2",
"sku":"24-WG082-blue",
"option_id":1,
"qty":1
},
{
"id":"3",
"sku":"24-WG083-blue",
"option_id":1,
"qty":1
}
]
},
{
"option_id":2,
"title":"Sprite Foam Yoga Brick",
"required":true,
"type":"radio",
"position":2,
"sku":"24-WG080",
"product_links":[
{
"id":"4",
"sku":"24-WG084",
"option_id":2,
"qty":1
}
]
},
{
"option_id":3,
"title":"Sprite Yoga Strap",
"required":true,
"type":"radio",
"position":3,
"sku":"24-WG080",
"product_links":[
{
"id":"5",
"sku":"24-WG085",
"option_id":3,
"qty":1
},
{
"id":"6",
"sku":"24-WG086",
"option_id":3,
"qty":1
},
{
"id":"7",
"sku":"24-WG087",
"option_id":3,
"qty":1
}
]
},
{
"option_id":4,
"title":"Sprite Foam Roller",
"required":true,
"type":"radio",
"position":4,
"sku":"24-WG080",
"product_links":[
{
"id":"8",
"sku":"24-WG088",
"option_id":4,
"qty":1
}
]
}
]
In our example below, we use a 65 cm Sprite Stasis Ball (id: 2), Sprite Foam Yoga Brick (id: 4), 8 ft Sprite Yoga strap (id: 6), and Sprite Foam Roller (id: 8) to add the Sprite Yoga Companion Kit bundle product to the cart via Magento 2 REST API.
Your endpoint looks as follows:
1
POST<host>/rest/<store_code>/V1/carts/mine/items
The headers are:
1
2
Content-Type:application/json
Authorization:Bearer<customer token>
You have to deal with the following payload:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
"cartItem":{
"sku":"24-WG080",
"qty":1,
"quote_id":"4",
"product_option":{
"extension_attributes":{
"bundle_options":[
{
"option_id":1,
"option_qty":1,
"option_selections":[2]
},
{
"option_id":2,
"option_qty":1,
"option_selections":[4]
},
{
"option_id":3,
"option_qty":1,
"option_selections":[6]
},
{
"option_id":4,
"option_qty":1,
"option_selections":[8]
}
]
}
}
}
}
As a result, the system provides the following response:
To verify this step, it is only necessary to sign in as the customer we’ve created above and to take a look at your shopping cart. All the items should be available there.
Checkout Preparations
Now, let’s see how to prepare the order for the checkout procedure. This process includes the following steps. Below, you will find how to use the Magento 2 REST API to estimate shipping costs as well as specify shipping/billing information.
Shipping costs
By default, Magento calculates shipping costs for all shipping methods available for the order. As we’ve mentioned above, in our case, we will apply the flatrateand tablerateshipping methods.
If you have to deal with the guest checkout, it is necessary to use the following endpoint:
1
V1/guest-carts/<cartId>/estimate-shipping-methods
There is no need to include an authorization token.
As for a logged-in user, the endpoint looks as follows:
The payload should include the shipping address as in the following example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"address":{
"region":"New York",
"region_id":43,
"region_code":"NY",
"country_id":"US",
"street":[
"123 Oak Ave"
],
"postcode":"10577",
"city":"Purchase",
"firstname":"Jane",
"lastname":"Doe",
"customer_id":4,
"email":"jdoe@example.com",
"telephone":"(512) 555-1111",
"same_as_billing":1
}
}
The response looks as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[
{
"carrier_code":"flatrate",
"method_code":"flatrate",
"carrier_title":"Flat Rate",
"method_title":"Fixed",
"amount":15,
"base_amount":15,
"available":true,
"error_message":"",
"price_excl_tax":15,
"price_incl_tax":15
},
{
"carrier_code":"tablerate",
"method_code":"bestway",
"carrier_title":"Best Way",
"method_title":"Table Rate",
"amount":5,
"base_amount":5,
"available":true,
"error_message":"",
"price_excl_tax":5,
"price_incl_tax":5
}
]
As you can see the Table Rate shipping method is less expensive than the Flat Rate one: $5 and $15 correspondingly. Also, note that every bundle counts as one item, and downloadable products don’t have a shipping charge.
Shipping/billing information
Below, we show how to specify the shipping and billing addresses using the Magento 2 REST API. Besides, we set the selected carrier_codeand method_code. Let’s assume that the customer selects the less expensive shipping method – Table Rate.
Next, Magento has to return a list of payment options. At the same time, the platform calculates the order totals.
If you work with a guest cart, use this endpoint, excluding the authorization token:
1
V1/guest-carts/<cartId>/shipping-information
Your endpoint to set shipping and billing information:
"title":"Shipping & Handling (Best Way - Table Rate)",
"value":5
},
{
"code":"tax",
"title":"Tax",
"value":0,
"extension_attributes":{
"tax_grandtotal_details":[]
}
},
{
"code":"grand_total",
"title":"Grand Total",
"value":165,
"area":"footer"
}
]
}
}
The order subtotal is $160. Together with shipping charges of $5, it results in the grand total of $165.
As for the payment methods available in our tutorial, they include banktransferand checkmo. This checkout step is described below.
Note that if your shipping_amount parameter is 0, it is necessary to disable the cart price rule that enables free shipping when a customer purchases products for more than $50. We described this step above.
To verify this step, you need to visit the checkout page as the customer. Address fields should be complete and shipping charges – calculated.
Place an Order
Below, we describe how to send payment information and review the order as an administrator with the help of the Magento 2 REST API.
Payment information
You need to submit payment information as a customer to let Magento 2 create a new order and send an order confirmation back. Due to the use of the offline payment method in this guide, there is no need to provide detailed payment information. We use the endpoint that requires only data regarding the payment method and billing address.
When it comes to guests, there is no need to include an authorization token. The corresponding endpoint looks as follows:
1
V1/guest-carts/<cartId>/payment-information
Your endpoint for a registered customer looks as follows:
To request an order object, use this endpoint, where3is the orderid:
1
GET<host>/rest/<store_code>/V1/orders/3
Your headers are:
1
2
Content-Type:application/json
Authorization:Bearer<administrator token>
The payload is not applicable.
The response contains all order data:
customer information,
payment details,
totals and subtotals per order,
totals and subtotals per item.
To verify this step as a customer, you should log in to your customer account. The order should be displayed in the dashboard. Next, log in to the Magento 2 backend. The order should be available under Sales -> Orders with the Pending status.
Invoice Creation
It is possible to create an invoice only after you receive payment for an order. Since we are exploring a situation when the order is paid offline, you need to inform Magento that the payment has been captured to create an invoice via the REST API.
Let’s see how to create a full invoice. If you need a partial invoice, add an array of items to the payload. Your endpoint looks as follows:
1
POST<host>/rest/<store_code>/V1/order/3/invoice
Don’t forget that 3 is the orderid.
The corresponding headers are:
1
2
Content-Type:application/json
Authorization:Bearer<administrator token>
The payload is quite simple:
1
2
3
4
{
"capture":true,
"notify":true
}
As a response, you get an invoice id. Let it be3.
Now, when the invoice is created, you can view it with the help of this endpoint:
We will use the order_item_id values in the next step, but before going any further, let’s verify the current action in the Magento 2 admin. The invoice should be available under Sales -> Invoices with the Paid status. The order (Sales -> Orders) should get a new status – Processing.
Shipment Creation
You can create a shipment with the help of the Magento 2 REST API, using the order_item_id of each product to be shipped. However, a partial shipment is possible. In this situation, you need to specify order_item_ids of items you want to ship.
Use the following endpoint (3 is the order id) to create a shipment:
1
POST<host>/rest/<store_code>/V1/order/3/ship
The corresponding headers are:
1
2
Content-Type:application/json
Authorization:Bearer<administrator token>
The payload looks as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"items":[
{
"order_item_id":3,
"qty":1
},
{
"order_item_id":5,
"qty":1
},
{
"order_item_id":11,
"qty":1
}
],
"tracks":[
{
"track_number":"1Y-9876543210",
"title":"United Parcel Service",
"carrier_code":"ups"
}
]
}
Note that it is possible to include one or more tracking numbers in the tracks array.
In response, you get a shipment ID (3).
If everything is ok, you will see the new shipment under Sales -> Shipments. The status of the corresponding order will be Complete.
Partial Refund
Magento provides two endpoints for issuing a refund. You can create a credit memo and update the order/invoice using only one call. Use the following endpoint to issues an offline refund:
1
POST/V1/order/<order_ID>/refund
To issue a refund with an online payment system, utilize this one:
1
POST/V1/invoice/<invoice_ID>/refund
Below, we explain how to create a refund for the Radiant T-M-Orange shirt.
Due to the use of a bank transfer, we have to use the following call:
1
POST/V1/order/<order ID>/refund
The order_item_idfor the product is 3.
Use the argumentsobject to adjust the amount of the credit you are going to refund. However, there is a constraint caused by the tablerateshipping method used for the order. Since a refund can’t be applied to the shipping costs, the shipping_amount is 0. However, it is possible to set the value of shipping_amountto 5, which is its actual amount – $5 per item, for the flatrateshipping method.
Before we proceed to the endpoint, note that Magento 2 uses the return_to_stock_itemsarray to specify order_item_ids to be restocked.
As for the endpoint, it looks as follows:
1
POST<host>/rest/<store_code>/V1/order/5/refund
The corresponding headers are:
1
2
Content-Type:application/json
Authorization:Bearer<administrator token>
Your payload is the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"items":[
{
"order_item_id":3,
"qty":1
}
],
"notify":true,
"arguments":{
"shipping_amount":0,
"adjustment_positive":0,
"adjustment_negative":0,
"extension_attributes":{
"return_to_stock_items":[
3
]
}
}
}
In response, you get a credit memo ID. You can check it under Sales -> Credit Memos. If the corresponding record is available in the grid, you’ve finished successfully. For further information, Check this official documentation: How to Create & Manage Orders in Magento 2 via REST API.
Final Words
As you can see, the Magento 2 REST API is quite developer-friendly. With the detailed documentation, you can effortlessly use it to connect Magento 2 to any external system. However, you can also rely on already existing solutions, such as our Improved Import & Export. The extension provides the ability to use REST API integrations with any third-party platforms and e-commerce solutions, automating data transfers to/from Magento 2.