1

How to create Rest API in magento 2 custom module. Is there any way to create API without writing di.xml?

  • Yes you can create api without it, do you want to create it for mobile app? – John Aug 31 '18 at 11:07
  • Yes. Please guide. – Apurba Bhowmik Sep 3 '18 at 3:22
2

For Mobile API, create an custom module with files like registration.php, etc->module.xml, etc->routes.xml(in this file define your route)

Helper->Data.php

class Data extends AbstractHelper
{

    /**
     * Data constructor.
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     */
    public function __construct(
        Context $context,
        ObjectManagerInterface $objectManager,
        StoreManagerInterface $storeManager
    )
    {
        parent::__construct($context, $objectManager, $storeManager);
    }

    public function createAutherizeSession($authentication_key, $device_id){

        if($authentication_key !='' && $device_id !=''){
            $authentication_key = '$9384598$-'.rand(1,999999999).'-'.$device_id;
            $session_authentication_key = $authentication_key;
        } else {
            $session_authentication_key = 0;
        }
        return $session_authentication_key;
    }

    public function authenticate($authentication_key = null, $device_id = null){
        $key = $device_id;
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $resource = $objectManager->create('\Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

        $query = $connection->query("select session_id from tbl_authorization where device_id='".$device_id."'");
        $result = $query->fetch();
        $session_authentication_key = $result['session_id'];

        $session_data = $session_authentication_key;
        $ex = explode(':', $session_data);
        if(count($ex) == 2){
            $new_authentication_key = $authentication_key . ':' . end($ex);
        } else {
            $new_authentication_key = $authentication_key;
        }

        if($new_authentication_key == $session_authentication_key){
            $mes =  'true';
        } else {
            $mes = 'false';
        }
        return $mes;
    }

    public function convertJson($code=null, $data=null){
        $message = $this->messageList($code);
        if($data == ''){
            $data = array();
        }
        if($code[0] == 2){
            $code = 200;
        }
        header('Content-Type: application/json');
        return json_encode(array("status"=>$code,"message"=>$message,"data"=>$data));

    }

    /* Message list function */

    public function messageList($messId = null){
        $message = array(
            '4000' => 'Authorize to Access',
            '4001' => 'Not authorize to Access',
            '2000' => 'Success',
            '0000' => 'Error',
            '0001' => 'Invalid Parameter',
            '0002' => 'No record found',
            '0007' => 'Please try again',

            '2001' => 'Password changed Successfully',
            '0003' => 'New and confirm password not match',
            '0004' => 'Old password incorrect',
            '0006' => 'Password length must be greater or equal than 6.',

            '2002' => 'User registered Successfully',
            '0005' => 'Email id already exists. Try a different email id.',
            '2019' => 'Updated Successfully',

            '2005' => 'Login successfully',
            '0008' => 'Invalid credentials. please try again!',
            '2011' => 'Logout successfully',
            '2056' => 'Review Saved Successfully',
            '2017' => 'Products Detail',
            '2018' => 'Package List',
            '2028' => 'List',
            '2029' => 'Details',
            '2032' => 'Category List',
            '2030' => 'Comment was successfully saved',
            '2031' => 'Post Comments Details',  
            '3001' => 'Forum Topic',    
            '3002' => 'Forum Details',

            '8001' => 'All City(State) List',
            '8002' => 'All Country(State) List',        
            '2007' => 'Product has been added Successfully in a cart',
            '2008' => 'Product has been deleted Successfully from cart',
            '2012' => 'Product has been update Successfully in a cart.',
            '2024' => 'Coupon Code Applied Successfully',

            '2040' => 'List of Results',
            '2009' => 'Newsletter subscription Successfully',
            '2010' => 'Newsletter has been Successfully un-subscribed.',

            '0009' => 'Address can not be more than 50 character.',
            '2013' => 'Customer address saved Successfully',
            '2014' => 'Address Deleted Successfully.',
            '2015' => 'Order Canceled Successfully',
            '2016' => 'Forgot password link send Successfully. Please check mail.',
            '2017' => 'Thank you for your query. We will get back to you soon.',
            '0010' => 'Email id not exists.Try again.',

            );
        return $message[$messId];
    }


}

You can define more response code and their messages in this file.

Controller - Authorization - Index.php

<?php

namespace Vendor\Modulename\Controller\Authorization;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\ForwardFactory;
use Magento\Framework\View\Result\PageFactory;

class Index extends Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    public $resultPageFactory;

    /**
     * @type \Magento\Framework\Controller\Result\ForwardFactory
     */
    protected $resultForwardFactory;



    /**
     * View constructor.
     * @param Context $context
     * @param PageFactory $resultPageFactory
     * @param ForwardFactory $resultForwardFactory

     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        ForwardFactory $resultForwardFactory
    )
    {
        parent::__construct($context);

        $this->resultPageFactory = $resultPageFactory;
        $this->resultForwardFactory = $resultForwardFactory;

    }

    /**
     * @return $this|\Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Origin,Authorization, Content-Type, X-Auth-Token');

        $helper = $this->_objectManager->create(
            'Vendor\Module\Helper\Data'
        );
        $data = array();
        $zendRequest = new \Zend_Controller_Request_Http();
        $authentication_key = $zendRequest->getHeader('Authorization');
        $device_id = $this->getRequest()->getParam('device_id');
        // die;
        if($authentication_key == '34F435436345685345345F23'){
            /* create authorization table */
            $resource = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection');
            $connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

            $query = $connection->query("create table if not exists tbl_authorization(id INT NOT NULL AUTO_INCREMENT primary key,device_id varchar(200) not null default '' ,session_id text not null)");

            $status = $helper->createAutherizeSession($authentication_key,$device_id);
            if($status == ''){
                echo $message =  $helper->convertJson('0001');
                die;
            } else if($status !=''){
                $data[]['Authorization_key'] = $status;

                $connection->query("delete from tbl_authorization where device_id='".$device_id."'");

                $connection->query("insert into tbl_authorization(device_id,session_id) values('".$device_id."','".$status."')");

                echo $message =  $helper->convertJson('2000',$data);
            }
        } else {
            echo $message =  $helper->convertJson('4001');
        }

    }
}

Controller -> Authorization -> Globals.php

<?php
namespace VendorName\ModuleName\Controller\Authorization;

use Magento\Framework\App\Action\Action;

class Globals extends Action
{

    public $auth;
    public $uid;

    public function execute()
    {

        $zendRequest = new \Zend_Controller_Request_Http();
        $authentication_key = $zendRequest->getHeader('Authorization');
        $device_id = $this->getRequest()->getParam('device_id');

        $helper = $this->_objectManager->create(
            'VendorName\ModuleName\Helper\Data'
        );    
        $status = $helper->authenticate($authentication_key,$device_id);
        if($status == 'false'){
            echo $message =  $helper->convertJson('4001');
            die;
        } else if($status == 'true'){
            $message =  $helper->convertJson('4000');
        }


    }
}

Now create Api folder inside controller and here you go, you can define behavior of every api here, for example product list api should be like this.

Productlist.php

<?php

namespace VendorName\ModuleName\Controller\Api;

use Magento\Framework\App\Action\Action;

class Productlist extends Action
{

    public function execute()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Origin,Authorization, Content-Type, X-Auth-Token');

        $result = array();
        $final = array();
        /* get list of category banner */
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        $helper = $objectManager->create(
            'VendorName\ModuleName\Helper\Data'
        );
        if($this->getRequest()->getParam('category_id')){
            if($this->getRequest()->getParam('sort')){
                $sortdata = explode('|', $this->getRequest()->getParam('sort'));
            }
            $cateinstance = $this->_objectManager->create('Magento\Catalog\Model\CategoryFactory');
            $category_id = $this->getRequest()->getParam('category_id');
            $collection = $cateinstance->create()->load($category_id)->getProductCollection()->addAttributeToSelect('*');
            $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
            $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
            $collection->setOrder('name','DESC');
            $list = array();
            $store = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore();
            $priceHelper = $objectManager->create('Magento\Framework\Pricing\Helper\Data');
            foreach ($collection as $product) {
                $each = array();
                $each['id'] = $product->getId();
                $each['name'] = $product->getName();
                $each['price'] = $priceHelper->currency($product->getFinalPrice(), true, false);
                $each['image'] = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $product->getImage();
                $list[] = $each;
            }
            $result['product'] = $list;
            $final[] = $result;
            $message = $helper->convertJson('2000',$final);
        }else{
            $message = $helper->convertJson('0001');
        }
        echo $message;
    }
}

Here in this API, parameter required is "category_id". Use postman and with post method, under headers define Authorization as key and pass the authorization key we define in authorization file and next is "content-type" under Body of postman define key as "category_id" and its value should be a category id value. send and you will get the response. See screenshots for more reference.

1. enter image description here

2. enter image description here

Finally, you need to send Url's like for e.g. http://yourwebsite.com/mobileapi/api/productlist

to your mobile team, then its their ball to play. Hope it helps, Cheers.

  • Before it catch someone else attention, i'm also not in favour of using object manager. But in case of quick deployment then it doesn't matter how you are doing it. If anyone can want to improve this then it will there call. Also this module is a custom one for some specific requirement it might be changes for different purposes as well. – John Sep 3 '18 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.