• As we all know that API is a must in every web application nowadays.

    Because, everybody needs to access those features and data of our web application through different ways. This is where API’s comes into picture, In simple words API’s are a kind of interface which has a set of functions that allows programmers to access specific features or data of our application. As the name suggests Web Api is an API over the web which can be accessed through HTTP protocol.

    So we will be creating a custom API in Magento. To create this we will be requiring few files.

    Here is the folder structure for the same :

    Beginning with registering our module for creating an API.

    So we will create our registration file for our custom api which will be registration.php

    <?php
    /**
     * Toshal Software
     *
     * @category Toshal_ApiUser
     *
     * @author Abhishek
     */
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        "Toshal_ApiUser",
        __DIR__
    );

    Also we will create a module.xml file for our module which will configure our module in our magento installation :

    <?xml version="1.0"?>
    
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="Toshal_ApiUser" setup_version="2.0.0" active="true"></module>
    </config>

    Now we will be creating a interface file named ApiUserManagementInterface.php which will be called when we call api :

    The location for this file will be : app/code/Toshal/ApiUser/Api/ApiUserManagementInterface.php

    <?php
    
    namespace Toshal\ApiUser\Api;
    
    interface ApiUserManagementInterface
    {
        /**
         * get ApiUser data
         *
         * @api
         *
         * @param int $id
         *
         * @return \Toshal\ApiUser\Api\Data\ApiUserInterface
         */
    
        public function  getUserData($id);
    }

    In the above file, we can see that the @api, @param and @return that are written in the comment section because all documents like these should have these things defined in them else the program won’t work.

    Now we implement the above interface in the following model file which will be located in Toshal/ApiUser/Model/Api/ApiUserManagement.php

    <?php
    
    namespace Toshal\ApiUser\Model\Api;
    
    class ApiUserManagement implements \Toshal\ApiUser\Api\ApiUserManagementInterface
    {
        const SEVERE_ERROR = 0;
        const SUCCESS = 1;
        const LOCAL_ERROR = 2;
    
        protected $_apiUserFactory;
    
        public function __construct(
            \Toshal\ApiUser\Model\ApiUserFactory $apiUserFactory
        ) {
            $this->_apiUserFactory = $apiUserFactory;
        }
    
        /**
         * get test Api data.
         *
         * @api
         *
         * @param int $id
         *
         * @return \Toshal\ApiUser\Api\Data\ApiUserInterface
         */
        public function getUserData($id)
        {
            try {
                $model = $this->_apiUserFactory->create();
                if(!$model->getId()){
                    throw new \Magento\Framework\Exception\LocalizedException(__('no data found'));
                }
                return $model;
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $returnArray['error'] = $e->getMessage();
                $returnArray['status'] = 0;
                $this->getJsonResponse(
                    $returnArray
                );
            } catch (\Exception $e) {
                $this->createLog($e);
                $returnArray['error'] = __('unable to process request');
                $returnArray['status'] = 2;
                $this->getJsonResponse($returnArray);
            }        
        }
    }

    The above class is the implementation of the interface, as you can see we have implemented the interface method that we had created in our interface file in Toshal/ApiUser/Api/ApiUserManagementInterface.php file.

    Now we will create a model file that will take a custom value and send that value in the Api :

    This file will be created in : app/code/Toshal/ApiUser/Model/ApiUser.php

    <?php
    
    namespace Toshal\ApiUser\Model;
    
    /**
     * @method \Toshal\ApiUser\Model\ResourceModel\Product_getResource()
     *
     * @method \Toshal\ApiUser\Model\ResourceModel\ProductgetResource()
     */
    
    class ApiUser implements \Toshal\ApiUser\Api\Data\ApiUserInterface
    {
        /**
         * Get ID.
         *
         * @return int
         */
    
        public function getId()
        {
            return 1;
        }
    
        /**
         * Set ID.
         *
         * @param int $id
         *
         * @return \Toshal\ApiUser\Api\Data\ProductInterface
         */
    
        public function setId($id)
        {
        }
    
        /**
         * Get Title
         *
         * @return string|null
         */
        public function getTitle()
        {
            return 'this is test title';
        }
    
        /**
         * Set title.
         *
         * @param string $title
         *
         * @return \Toshal\ApiUser\Api\Data\ProductInterface
         */
    
        public function setTitle($title)
        {
    
        }
    
        /**
         * Get Description
         *
         * @return string|null
         */
    
        public function getDescription()
        {
            return 'this is test api description';
        }
    
        /**
         * Set Description
         *
         * @param string $desc
         *
         * @return \Toshal\ApiUser\Api\Data\ProductInterface
         */
        public function setDescription($desc)
        {
            
        }
    }

    The next file that we will create is the interface for the above file which will be as follows :

    The location for this file will be : app/code/Toshal/ApiUser/Api/Data/ApiUserInterface.php

    <?php
    
    /**
     * Toshal Software
     *
     * @category Toshal
     *
     * @author Toshal
     */
    
    namespace Toshal\ApiUser\Api\Data;
    
    /**
     * ApiUser product Inteface file
     *
     * @api
     */
    interface ApiUserInterface
    {
        /**#@+
         * Constants for keys of data array. Identical to the name of the getter in snake case
         */
    
        const ENTITY_ID = 'entity_id';
    
        const TITLE = 'title';
    
        const DESC = 'description';
    
        /**#@-*/
    
        /**
         * Get Id.
         *
         * @return int|null
         *
         */
        public function getId();
    
        /**
         * Set Id.
         *
         * @param int $id
         *
         * @return \Toshal\ApiUser\Api\Data\ProductInterface
         */
        public function setId($id);
    
        /**
         * Get title
         *
         * @return string|null
         */
        public function getTitle();
    
        /**
         * Set Title.
         *
         * @param string $title
         *
         * @return \Toshal\ApiUser\Api\Data\ProductInterface
         */
        public function setTitle($title);
    
        /**
         * Get desc.
         *
         * @return string|null
         */
        public function getDescription();
    
        /**
         * Set Desc.
         *
         * @param string $desc
         *
         * @return \Toshal\ApiUser\Api\Data\ProductInterface
         */
        public function setDescription($desc);
    }

    Now let's create our di.xml file which will consist the information about which model file should be used for corresponding interface

    The location for this file would be : app/code/Toshal/ApiUser/etc/di.xml

    <?xml version="1.0"?>
    
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <preference
            for="Toshal\ApiUser\Api\ApiUserManagementInterface"
            type="Toshal\ApiUser\Model\Api\ApiUserManagement" />
        <preference
            for="Toshal\ApiUser\Api\Data\ApiUserInterface"
            type="Toshal\ApiUser\Model\ApiUser" />
    </config>

    Now we will be creating the webapi.xml file which will the configure our api in magento and it will contain the URL which can be called by the user to run the API :

    This file will be located in app/code/Toshal/ApiUser/etc/webapi.xml :

    <?xml version="1.0"?>
    
    <routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
        <!-- ApiUser group -->
        <route url="/V1/apiuser/custom/me" method="GET">
            <service
                class="Toshal\ApiUser\Api\ApiUserManagementInterface"
                method="getUserData" />
                <resources>
                    <resource ref="self" />
                </resources>
                <data>
                    <parameter name="id" force="true">%customer_id%</parameter>
                </data>
        </route>
    </routes>

    The Result for this api would be like this :

     

    References :

    https://webkul.com/blog/magento2-custom-rest-api/

0 Years in
Operation
0 Loyal
Clients
0 Successful
Projects

Words from our clients

 

Tell Us About Your Project

We’ve done lot’s of work, Let’s Check some from here