Magento 2 Guide To Create Custom Api

As we have already seen how to create a basic module in Magento 2, now lets learn how to create you own custom api. So start creation of your new module by creating module.xml and registration.php. I have created my module ‘CustomApi’ under ‘W3solver’ namespace so below is the code of my module.xml and registration.php

Module.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * w3solver.com
 *
 * @category       W3solver
 * @package        W3solver_CustomApi
 * @Description    module
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
   <module name="W3solver_CustomApi" setup_version="2.0.1"></module>
</config>

Registration.php

<?php

/**
 * I95Dev.com
 *
 *
 * @category    W3solver
 * @package     W3solver_CustomApi
 * @Description Module registration file
 * @author      W3solver
 */
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'W3solver_CustomApi',
    __DIR__
);

Now to create any custom API we need to add ‘webapi.xml’ file under ‘etc’ folder. In below code you can see we have a rest api with method as GET and url as /V1/customapi/shipping/:name, the class to which it refers is W3solver\CustomApi\Api\ShippingInterface

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/customapi/shipping/:name" method="GET">
        <service class="W3solver\CustomApi\Api\ShippingInterface" method="exist"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Now we will create the interface(ShippingInterface) file under ‘Api’ folder

<?php
namespace W3solver\CustomApi\Api;
 
interface ShippingInterface
{
    /**
     * check if shipping method exists
     *
     * @api
     * @param string $name shipping method name
     * @return bool
     */
    public function exist($name);
}

The interface is implemented in its respective model, in our case we are implementing it in Shipping.php file placed directly under ‘Model’ Folder.

<?php

namespace W3solver\CustomApi\Model;

use W3solver\CustomApi\Api\ShippingInterface;

class Shipping implements ShippingInterface
{

    public $shipconfig;
    public $scopeConfig;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Shipping\Model\Config $shipconfig
    ) {
        $this->shipconfig = $shipconfig;
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * checks if shipping method is active
     *
     * @api
     * @param string $name shipping method name
     * @return string Greeting message with users name.
     */
    public function exist($name)
    {

        $activeCarriers = $this->shipconfig->getActiveCarriers();
        $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
        foreach ($activeCarriers as $carrierCode => $carrierModel) {
            if ($carrierMethods = $carrierModel->getAllowedMethods()) {
                foreach ($carrierMethods as $methodCode => $method) {
                    $code = $carrierCode . '_' . $methodCode;
                    if ($code == $name) {
                        return true;
                    }
                }
            }
        }

        return false;
    }
}

We are all set for your API to test, above API checks the availability of method.

Integrate Amazon Rekongition service With PHP.

Ahh! If you have never heard AWS Rekognition service that no need to worry. Rekognition is a service provided by Amazon in the year 2016. Your program can recognize faces, you can compare face, find a specific face, find content from the image and videos.You can moderate the uploaded images/video according to your need. It doesn’t sound excited now but it is a very important and useful in many use case.
Suppose you have an e-commerce site, where seller uploads their product. The seller is free to upload any product seller can upload an image of Weapon, Drug and some content that you really don’t want to allow on your application. To remove them you have to moderate the products manually. Here AWS Rekognition comes in the picture, by using this service you can write your logic in code and moderate images and video. It helps you to understand the image and you can write your algorithm accordingly.

Listed things, that you will be required to integrate AWS Recognition.

1. AWS account. If you don’t have an account you can create.
2. It will be better if you will create an IAM user and provide the sufficient access permission to him.(Obtain key and secret )
3. You can get the key, login to aws console -> search IAM -> Users(from left panel)-> security Credential-> Create access key
4. AWS PHP SDK.

There are 33 methods exposed by AWS underrecognition service. You can use according to your need. Visit this link to get all methods.

How to implement this: This service support almost all language. For PHP, AWS has SDK. You need to download this SDK. Follow Command to get AWS PHP SDK.

Go to your project folder and run command.

curl -sS https://getcomposer.org/installer | php

Run composer command and install PHP SDK

php composer.phar require aws/aws-sdk-php

That’s it. Now you have PHP SDK with you. You can Use this SDK to integrate all service provided By Amazon.

You can use aws recognition service with S3 as well as local storage. so let’s start your IDE and Write first code:

require 'vendor/autoload.php';

use Aws\Rekognition\RekognitionClient;
$options = [
    'region' => 'us-west-2',
    'version' => '2016-06-27',
    'credentials' => array(
        'key' => 'Your key',
        'secret'  => 'Your Secret',
      )
    
    ];
$rekognition = new RekognitionClient($options);
$fp_image = fopen('test.jpg', 'r');
$image = fread($fp_image, filesize('test.jpg'));
fclose($fp_image);

Custom Api Module to check if shipment and payment methods are active

There are lots of api provided by magento but here is the module that provide you a custom api to check if shipment and payment method are active or not. Below you can find out the module zip attached. I have tested my code via postman so below are some screenshot of the same:-

1. Check for payment method

Api End Point:- V1/customapi/payment/:paymentmethodname

 

2. Check for shipment method

Api End Point:- V1/customapi/payment/:paymentmethodname

Versions: I’ve tested the module with the version 2.2.2

click link to download the extension

Let me know if you found any issue or have any query.
Updated on :- 01-02-2018