Latest news

How To Create API Request In Magento 2?

No comments

A. Create API Request

There are 4 simple steps to create an API request:

Step 1: Declare API

Create webapi.xml under the etc root module folder:
/magento/module-customer/etc/webapi.xml

<route url="/V1/customers" method="POST">
   <service class="Magento\Customer\Api\AccountManagementInterface" method="createAccount"/>
   <resources>
       <resource ref="anonymous"/>
   </resources>
</route>

Let us walk you through the above code to make sure you understand what’s happening:

  • Route – This is the URL which will be used to call our API https://{{MagentoBaseURL}}/index.php/rest/V1/customers.
  • Service class – This is the interface class of our API and the main method “createAccount” will be called.
  • Resources – This defines who has permission to call this API. It could be anonymous (everyone) or self (customer) or specific admin user with specific permission, for example, Magento_Customer:: customer which can be added in acl.xml.

Step 2: Create the main interface file as specified in webapi.xml

Magento\Customer\Api\CustomerRepositoryInterface

/**
* Create customer account. Perform necessary business operations like sending email.
*
* @param \Magento\Customer\Api\Data\CustomerInterface $customer
* @param string $password
* @param string $redirectUrl
* @return \Magento\Customer\Api\Data\CustomerInterface
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function createAccount(
   \Magento\Customer\Api\Data\CustomerInterface $customer,
   $password = null,
   $redirectUrl = ''
);

Step 3: Create model classes where you can put the actual business logic

You must specify this in our di.xml file under the etc folder
/module-customer/etc/di.xml

<preference for="Magento\Customer\Api\AccountManagementInterface"
           type="Magento\Customer\Model\AccountManagement" />

 

Step 4: Create the first model class AccountManagement.php to define the createAccount function

/**
* @inheritdoc
*/
public function createAccount(CustomerInterface $customer, $password = null, $redirectUrl = '')
{
   if ($password !== null) {
       $this->checkPasswordStrength($password);
       $customerEmail = $customer->getEmail();
       try {
           $this->credentialsValidator->checkPasswordDifferentFromEmail($customerEmail, $password);
       } catch (InputException $e) {
           throw new LocalizedException(
               __("The password can't be the same as the email address. Create a new password and try again.")
           );
       
       $hash = $this->createPasswordHash($password);
   } else {
       $hash = null;
   
   return $this->createAccountWithPasswordHash($customer, $hash, $redirectUrl);
}

 

B. Forcing Request Parameters

We can force parameters in the webapi.xml to guarantee that a specific value is utilized on specific routes.
Let see an example with endpoint /V1/carts/mine

Step 1: Declare parameters in webapi.xml

vendor/magento/module-quote/etc/webapi.xml

<route url="/V1/carts/mine" method="POST">
   <service class="Magento\Quote\Api\CartManagementInterface" method="createEmptyCartForCustomer"/>
   <resources>
       <resource ref="self" />
   </resources>
   <data>
       <parameter name="customerId" force="true">%customer_id%</parameter>
   </data>
</route>

 

Step 2: Make an override in di.xml

vendor/magento/module-webapi/etc/di.xml

<type name="Magento\Webapi\Controller\Rest\ParamsOverrider">
   <arguments>
       <argument name="paramOverriders" xsi:type="array">
           <item name="%customer_id%" xsi:type="object">Magento\Webapi\Controller\Rest\ParamOverriderCustomerId</item>
       </argument>
   </arguments>
</type>

 

Step 3: Get the value of params

vendor/magento/module-webapi/Controller/Rest/ParamOverriderCustomerId.php

/**
* {@inheritDoc}
*/
public function getOverriddenValue()
{
   if ($this->userContext->getUserType() === UserContextInterface::USER_TYPE_CUSTOMER) {
       return $this->userContext->getUserId();
   
   return null;
}

 

We have shown you the basic guide to creating the API request for Magento 2. If you have any issues when following the steps, please leave a comment below.

1 Star2 Stars3 Stars4 Stars5 Stars (16 votes, average: 5.00 out of 5)
Loading...

 

Related Posts:

Download Free Magento 2 API for Mobile App

How To Use Stripe Connect With Custom Account (Vendor Account) In Magento 2?

How To Configure REDIS In Magento 2 & Magento 1? (5 Minutes)

How To Use Custom Local Storage & Cookie Storage In Magento 2?

How To Migrate Magento 1.9.x to 2.3.x Without Any Problem?

April LeeHow To Create API Request In Magento 2?

Leave a Reply

Your email address will not be published. Required fields are marked *