The Ultimate Magento 2 REST API Guide

Magento 2 REST API tutorial

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. 

REST API Explained

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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:

  1. 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.
  2. 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.
  3. If you are not familiar with how to construct a REST call in Magento, follow this link: Construct a request in Magento 2.
  4. It is also necessary to be familiar with the Magento REST API documentation: static REST API or local API reference.

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:

  1. Check/Money Order (checkmo);
  2. Bank Transfer Payment (banktransfer);
  3. Cash on Delivery (cashondelivery);
  4. Purchase Order (purchaseorder);
  5. 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:

    • HTTP verb is one of the following: GET, POST, PUT, or DELETE;
    • host is 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:

Your header is:

Your payload consists of the following rows:

You get the following admin’s access token as a response:

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:

Use the following endpoint to create a new customer account:

Your header is:

Your payload consists of the following rows:

Use a real email address in the third row to receive all notifications related to this REST API practice.

You get the following response:

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 your password, 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:

Your header looks as follows:

The payload consists of the following rows:

The response is similar to the one you get in the case of an admin authorization token:

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 quoteId for 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:

These are the headers:

The payload is none.

The response is the following:

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:

These are the headers:

The payload contains the following rows:

And the response looks like that:

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:

With the following headers:

The payload looks as follows:

As a result, you get this response:

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_id values for Size and Color – 141 and 93. You can use the following call to determine the option_id values for the given SKU:

To see information about each combination of color and size, use this call:

Below, you can see the returned values for the size – 168 – and color – 52 – options of a small gray Chaz Kangeroo Hoodie.

This information is necessary to add the product to the cart via the Magento 2 REST API. Your endpoint is the following:

The headers include the following information:

Your payload looks as follows:

As a result, you get this response:

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 is 24-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 id of the item’s product_links object. 

Magento 2 uses the product_links object for ordering and placement of options on the customization page. However, the platform also incorporates it to link the item’s sku and id to the sku of the bundle product.

Use this call to get id values in the response: 

The response in its simplified form looks as follows:

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:

The headers are:

You have to deal with the following payload:

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 flatrate and tablerate shipping methods.

If you have to deal with the guest checkout, it is necessary to use the following endpoint:

There is no need to include an authorization token.

As for a logged-in user, the endpoint looks as follows:

The headers contain the following information:

The payload should include the shipping address as in the following example:

The response looks as follows:

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_code and 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:

Your endpoint to set shipping and billing information:

The appropriate headers:

The payload is the following one

And this is the response:

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 banktransfer and 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:

Your endpoint for a registered customer looks as follows: 

Its headers are:

And this is the payload:

In response, you get an orderID.

Order review

To request an order object, use this endpoint, where 3 is the orderid:

Your headers are:

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:

Don’t forget that 3 is the orderid.

The corresponding headers are:

The payload is quite simple:

As a response, you get an invoice id. Let it be 3.

Now, when the invoice is created, you can view it with the help of this endpoint:

Your headers look as follows:

The payload is not applicable.

The response looks as follows:

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:

The corresponding headers are:

The payload looks as follows:

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: 

To issue a refund with an online payment system, utilize this one:

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:

The order_item_id for the product is 3.

Use the arguments object to adjust the amount of the credit you are going to refund. However, there is a constraint caused by the tablerate shipping 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_amount to 5, which is its actual amount – $5 per item, for the flatrate shipping method.

Before we proceed to the endpoint, note that Magento 2 uses the return_to_stock_items array to specify order_item_ids to be restocked.

As for the endpoint, it looks as follows:

The corresponding headers are:

Your payload is the following:


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.