Magento 2 REST API - Benefits & Implementation Guidelines

Are you ready to take your online store to the next level? Supercharge your e-commerce experience with Magento 2 REST API. Unleash its power to elevate your store’s functionality and drive unprecedented growth. How can seamless integration and expanded functionality transform your business? Join us on this exciting journey as we delve into the world of Magento 2 REST API and unlock its full potential.

Discover Magento 2 API: Benefits, implementation guidelines, and a closer look at the REST API. Elevate e-commerce integration with this comprehensive solution.

REST API

Magento API Integration Service by Mageplaza

Connect your store with any 3rd-party software and boost customer experience quickly and efficiently.

Learn more
Magento API Integration service

What is REST API

The Magento 2 REST API identifies various functions which can be used to perform requests and receive responses. A developer can perform these interactions by using the HTTP protocol.

The caller leads to an HTTP request which includes the below elements:

  • An HTTP header which provides not only authentication but also other instructions
  • A verb which is the action against the endpoint, it can be GET, POST, PUT, and DELETE.
  • An endpoint is a Uniform Resource Indicator (URI). This endpoint identifies the server, the web service, and also the resource which is acted on.
  • The call payload includes set of input parameters and attributes which you supply with the request.

A response payload and an HTTP status code will be returned

To help you understand easier, below are the details information about these four elements:

HTTP headers

Below is the table which describes three HTTP headers in your web API calls:

HTTP header Description Syntax  
Authorization This HTTP header is required. It specifies the authentication token which proves that you are the owner of a Magento account. The token is specified in the Authorization request header with the HTTP authorization scheme Bearer. Authorization: Bearer <TOKEN>. <TOKEN> is the authentication token which is returned by the Magento token service.  
Accept This HTTP header is optional. It specifies the response body’s format. JSON is the default. Accept: application/<FORMAT>. <FORMAT> is JSON or XML.  
Content-Type This HTTP header is required for operations with a request body. It specifies the request body’s format. Content-Type:application/<FORMAT>. <FORMAT> is JSON or XML.  

HTTP verb

  • GET: This verb requests a current representation transfer of the target resource. If the verb is omitted, the default is GET.
  • PUT: This verb requests the target resource’s state be created or replaced with the state which is defined by the representation enclosed in the request message payload.
  • POST: This verb requests the representation enclosed which is in the request to be accepted as data for the target resource to process.
  • DELETE: This verb requests the target resource to be deleted by the origin server.

Endpoint

This is a combination of the server, web service, store code, resource against and template parameters.

For instance, in the endpoint http://magento.ll/index.php/rest/default/V1/customerGroups/:id, magento.ll/index.php/ is the server, rest is the web service, /V1/customerGroups is the resource, and id is the template parameter.

A store code can include one of the values which are mentioned below:

  • The assigned store code of the store.
  • default which is the default value when there are no store code provided.
  • all only applies to endpoints which are defined in the CMS and Product modules. The API call will affect all of the merchant’s stores if this value is specified.

Call payload

This element is a set of input parameters and attributes which are supplied with the request. Both required and optional inputs are included in API operations.

Input parameters are specified in the URI. For instance, in the URI GET/V1/customers/:customerId, the customerId template parameter must be specified.

Input attributes are specified in a JSON- or XML-formatted request body. For example, in the POST /V1/customers call, a request body must be specified like this:

{
    "customer": {
        "email": "[email protected]",
        "firstname": "John",
        "lastname": "Doe"
    },
    "addresses": [
        {
            "defaultShipping": true,
            "defaultBilling": true,
            "firstname": "John",
            "lastname": "Doe",
            "region": {
                "regionCode": "CA",
                "region": "California",
                "regionId": 12
            },
            "postcode": "90001",
            "street": ["Zoe Ave"],
            "city": "Los Angeles",
            "telephone": "555-000-00-00",
            "countryId": "US"
        }
    ]
}

This includes a customer object which has customer email, first name, last name, and address information. This information is used to populate the new customer account.

Way to Use Magento 2 REST API

The Magento 2 REST API offers a set of predefined functions that developers use to execute requests and receive responses over the HTTP protocol. To effectively use these functions, it’s essential to comprehend the flow to call APIs.

In initiating an HTTP request through the REST API structure, the following elements are involved:

HTTP Header: Authenticate the API request. It often contains the Authorization field with a bearer token or other credentials.

HTTP Verb: Determines the operation that the endpoint will execute, including actions like GET, POST, PUT, and DELETE.

GET: Retrieve data from the server.

POST: Send data to the server to create a new resource.

PUT: Update a resource on the server.

DELETE: Remove a resource from the server.

Endpoint (URI): A Uniform Resource Identifier (URI) serves to identify the server, web services, and resource details.

Call Payload: A JSON or XML formatted string that includes the data you want to send with your request. For POST and PUT requests, this typically includes the attributes of the resource you’re creating or updating.

Currently, Magento 2 uses three authentication techniques as outlined in its REST API documentation.

Token-Based Authentication: Used primarily for mobile applications. You obtain a token by sending admin or customer credentials to a token-generating endpoint.

Admin and Customer Authentication: Directly uses login credentials to authenticate each API call.

OAuth Authentication: A more secure method for third-party applications, involving a consumer key, consumer secret, access token, and access token secret.

These authentication methods are limited to accessing only resources assigned. To begin utilizing the Magento 2 REST API, it’s necessary to verify the user’s identity and their authorization to use the API. The permissions to access specific resources are established in the webapi.xml file. Customers are allocated identical permissions for their response. The Magento 2 API establishes various user categories, each encompassing a specific range of permissions.

User Type, including:

Admin or Integration: Typically has the broadest access to resources and can perform almost any action.

Customer: Has limited access, usually to their own order history, profile information, and other personal data.

Guest User: The most restricted access, often limited to browsing products and other public-facing information.

How to call a request

Below I will provide you an example on how to construct a REST web API call to create an account.

<route url="/V1/customers" method="POST">
   <service class="Magento\Customer\Api\AccountManagementInterface" method="createAccount"/>
   <resources>
      <resource ref="anonymous"/>
   </resources>
</route>
  • Step 3: To construct the URI, the method and url values are used on the route element. Here, POST /V1/customers is the URI.

  • Step 4: The class attribute is used on the service element to identify the service interface. The service interface in this example is the AccountManagementInterface PHP file.

In the AccountManagementInterface.php file, the createAccount method can be found like this:

public function createAccount(
     \Magento\Customer\Api\Data\CustomerInterface $customer,
     $password = null,
     $redirectUrl = ''
 )

A customer data object is required while the password and redirectUrl values are optional. Null is the default password value, the default redirectUrl value is blank.

  • Step 5: Specify JSON or XML request body on the call to pass the customer data object in the POST call payload.

Example of Customers Search API request

This is an example of generating a Customers Search request according to search criteria. This request will return a customers’ list which matches the given search criteria.

  • Step 1: Authorization, Accept and Content-Type headers need to be passed to a request object. The Authorization token which is returned by the Magento token service is used.
$token = 'token';
$httpHeaders = new \Zend\Http\Headers();
$httpHeaders->addHeaders([
   'Authorization' => 'Bearer ' . $token,
   'Accept' => 'application/json',
   'Content-Type' => 'application/json'
]);
  • Step 2: Open the Magento/Customer/etc/webapi.xml configuration file. Then find the interface CustomerRepositoryInterface with the method getList.

  • Step 3: The headers, URI and method need are set to a request object. URI /V1/customers/search and method GET values are used. The searchCriteria parameter is used to complete the Customer Search query.

Below is the example which finding the customers who have the first name contains Ver and the last name contains Costello.

 $request = new \Zend\Http\Request();
 $request->setHeaders($httpHeaders);
 $request->setUri('http://magento.ll/rest/V1/customers/search');
 $request->setMethod(\Zend\Http\Request::METHOD_GET);

 $params = new \Zend\Stdlib\Parameters([
     'searchCriteria' => [
         'filterGroups' => [
             0 => [
                 'filters' => [
                     0 => [
                         'field' => 'firstname',
                         'value' => '%ver%',
                         'condition_type' => 'like'
                     ],
                     1 => [
                         'field' => 'lastname',
                         'value' => '%Costello%',
                         'condition_type' => 'like'
                     ]
                 ]
             ]
         ]
     ],
     'current_page' => 1,
     'page_size' => 10
 ]);
    
 $request->setQuery($params);
  • Step 4: A HTTP Curl client object is prepared and the request object is pass to Client::send() method.
$client = new \Zend\Http\Client();
$options = [
   'adapter'   => 'Zend\Http\Client\Adapter\Curl',
   'curloptions' => [CURLOPT_FOLLOWLOCATION => true],
   'maxredirects' => 0,
   'timeout' => 30
 ];
 $client->setOptions($options);

 $response = $client->send($request);

A list of customers in JSON format will be returned:

{
    "items": [
        {
            "id": 1,
            "group_id": 1,
            "default_billing": "1",
            "default_shipping": "1",
            "created_at": "2017-12-05 09:50:11",
            "updated_at": "2018-09-22 06:32:50",
            "created_in": "Default Store View",
            "dob": "1973-12-15",
            "email": "[email protected]",
            "firstname": "Veronica",
            "lastname": "Costello",
            "gender": 2,
            "store_id": 1,
            "website_id": 1,
            "addresses": [
                {
                    "id": 1,
                    "customer_id": 1,
                    "region": {
                        "region_code": "MI",
                        "region": "Michigan",
                        "region_id": 33
                    },
                    "region_id": 33,
                    "country_id": "US",
                    "street": [
                        "6146 Honey Bluff Parkway"
                    ],
                    "telephone": "(555) 229-3326",
                    "postcode": "49628-7978",
                    "city": "Calder",
                    "firstname": "Veronica",
                    "lastname": "Costello",
                    "default_shipping": true,
                    "default_billing": true
                },
                {
                    "id": 19,
                    "customer_id": 1,
                    "region": {
                        "region_code": "London ",
                        "region": "London ",
                        "region_id": 0
                    },
                    "region_id": 0,
                    "country_id": "GB",
                    "street": [
                        "1 Studio 103 The Business Centre 61"
                    ],
                    "telephone": "1234567890",
                    "postcode": "CF24 3DG",
                    "city": "Tottenham ",
                    "firstname": "Veronica",
                    "lastname": "Costello"
                }
            ],
            "disable_auto_group_change": 0
        }
    ],
    "search_criteria": {
        "filter_groups": [
            {
                "filters": [
                    {
                        "field": "firstname",
                        "value": "%ver%",
                        "condition_type": "like"
                    }
                ]
            }
        ]
    },
    "total_count": 1
}

An XML format can also be specified by changing the Accept header of the request.

Conclusion

Above I have just provided you all the information about what is REST API and how a request can be called. I hope this post is useful for you. If you have further questions or new ideas, feel free to leave a comment below.

If you find it too complicated to understand, our experts are always willing to help you! We know that API integration is essential to growing your business, as it enables you to discover new opportunities and boost customer experience. But we also know that it’s a complicated process and requires quite a lot of knowledge to implement.

Mageplaza offers a number of Magento API/GraphQL integration services for you, such as CRM, ERP, marketing automation, payment platforms, etc. Our experts will lead your project from start to finish to ensure that you’re entirely satisfied with the result. We also follow the best practices in implementing the API integration to help you leverage your business’s full capabilities.

Give our API integration services a nice try! Contact our experts for free consultations now!

Image Description
Hello, I'm the Chief Technology Officer of Mageplaza, and I am thrilled to share my story with you. My deep love and passion for technology have fueled my journey as a professional coder and an ultra-marathon runner. Over the past decade, I have accumulated extensive experience and honed my expertise in PHP development.
x