How to create own custom API in Magento 2

By | November 22, 2021
Spread the love

The REST API documentation published on the Magento 2 Developer Documentation website describes the REST APIs that are available on the latest release of Magento 2.  This documentation is generated from the code base using Swagger and represents the state of the code at the time the documentation was generated. Swagger displays a list of service names. Click on a service name to display the list of APIs defined within that service. Click on an API name to display detailed information about that API.

You can also create a dynamic REST API documentation set on your server with live data. On your server, Swagger displays REST APIs for all installed products and allows you to try out the APIs. For more information, see Generate local REST API reference.

Magento 2.x Apis:  http://devdocs.magento.com/swagger/index.html

Now you can follow following steps to create custom API in magento 2.

Access API with Rest Method:

Step 1  System =>  Integrations => Add Integration

Step 2  System => User Roles => Add New Role

After creating this access for access authorise resource. Now lets create an API. Create Api process similar as Create custom module in magento.

For Ex, we will create a Login API Step By Step.

API Module Structure.

Techgroup
    Mobileapp
     Api
        Customer
          CustomerInterface.php
     etc
         di.xml
         module.xml
         webapi.xml
     Model
         Customer
           Customer.php
     registration.php

File Details

       1. registration.php

“Registration.php” file required in installation process Magento 2.

Here we create a Sample Module for Mobile Api which name “Techgroup_Mobileapp” Auriga is vendor name and Mobileapp is module.

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Techgroup_Mobileapp',
    __DIR__ 
);

2. module.xml

Module.xml which tells magento about our module.Here we declare Module Name and Version control.

Here we explain sample module Techgroup_Mobileapp which Version 1.0.0

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
      <module name="Techgroup_Mobileapp" setup_version="1.0.0"/>
</config>

Webapi.xml

If you wants to create a method which calls through api must be declared in webapi.xml.

Here I create login method for Sample Example.

For Ex.

url=”MAGENTOROOT/V1/api/customer/login”

method=”POST”

ref=”anonymous”

URL which tell the path of access api Method pass the parameters inside api Ref  declaration who can access method (No need to authorization).

As Sample Request

<route url="/V1/api/customer/login" method="POST"> 
    <service class="Techgroup\Mobileapp\Api\Customer\CustomerInterface" method="login"/> 
    <resources> 
        <resource ref="anonymous"/> 
    </resources> 
</route>

di.xml

Basically di.xml using Overriding core module.

Here we declare Login Method in CustomerInterface  And define in Customer model.

<?xml version="1.0"?
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
     <preference for="Techgroup\Mobileapp\Api\Customer\CustomerInterface" type="Techgroup\Mobileapp\Model\Customer\Customer" /> 
</config>

CustomerInterface.php

Declaration of our method Sample Method here we declare our method.

<?php

namespace Techgroup\Mobileapp\Api\Customer;
 
interface CustomerInterface
{
   public function login($email, $password);
}

Customer.php

Definition of our method.

public function login($email, $password) {
     $login = array();
     if($email){
         $login['username'] = $email;
     }
     if($password){
         $login['password'] = $password;
     }
    
     if (!empty($login['username']) && !empty($login['password'])) {
         try {
             $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
             $code = 1;
             $message = array('id'=>$customer->getId(),'email'=>$customer->getEmail(),'name'=>ucwords($customer->getFirstName().' '.$customer->getLastName())); 
         } 
         catch (EmailNotConfirmedException $e) {
             $value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
             $message = __(
                 'This account is not confirmed.' .
                 ' <a href="%1">Click here</a> to resend confirmation email.',
                 $value
             );
             $code = array('status'=>0,'message'=>$message);
         } 
         catch (AuthenticationException $e) {
             $message = __('Invalid login or password.');
             $code = 0;
         } 
         catch (\Exception $e) {
             $message = __('Invalid login or password.');
             $code = 0;
         }
     } else { 
         $message = __('Invalid login or password.');
         $code = 0;
     }
     return array(array('message' => $message,'status'=>$code));
}