How To Create API Request In Magento 2?

how to create api request in magento 2

To create an API request in Magento 2, there are two actions that we have to take: creating API requests and forcing request parameters.

A. Create API Request

There are four simple steps to create:

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 that 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 a 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;
}

That’s it! Hope you’ve found this blog post helpful.

Leave a Reply

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