Custom API for Magento 2

Custom API for Magento 2

We have already went through on how to configure integration and utilize Magento apis. But let’s see how to make our own module with custom API calls.

Module Essentials

For a simpler start you should read the following article: “How to create a basic module in Magento 2” by Hrvoje Ivancic and make basic Magento 2 module. You would need only two things, module.xml and register.php for this example module. I would create module under Inchoo name space and call it Hello.

Module Configuration – etc/module.xml

<?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="Inchoo_Hello" setup_version="1.0.0" />
</config>

Registration – registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Inchoo_Hello',
    __DIR__
);

API configuration

There are two more additional configurations we need to add API capability to module, webapi.xml and di.xml. In webapi.xml we are configuring access rights and API Interface that specified method will use.

Web API configuration – 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">
    <route url="/V1/hello/name/:name" method="GET">
        <service class="Inchoo\Hello\Api\HelloInterface" method="name"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Resource tag defines what resources user needs to have to be able to access this api call. Possible options are self, anonymous or Magento resource like Magento_Catalog::products or Magento_Customer::group. We will for now use anonymous so we can access it as a guest.

Define Interface – 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="Inchoo\Hello\Api\HelloInterface"
                type="Inchoo\Hello\Model\Hello" />
</config>

In di.xml we define what model will interface call to. We also need to add Interface and Model, please note that you need to take care about comments also.

Interface – Api/HelloInterface.php

<?php
namespace Inchoo\Hello\Api;
 
interface HelloInterface
{
    /**
     * Returns greeting message to user
     *
     * @api
     * @param string $name Users name.
     * @return string Greeting message with users name.
     */
    public function name($name);
}

 

Model – Model/Hello.php

<?php
namespace Inchoo\Hello\Model;
use Inchoo\Hello\Api\HelloInterface;
 
class Hello implements HelloInterface
{
    /**
     * Returns greeting message to user
     *
     * @api
     * @param string $name Users name.
     * @return string Greeting message with users name.
     */
    public function name($name) {
        return "Hello, " . $name;
    }
}

Within model we add our functionality that will be executed by call to API method. In this case it will append Hello to name provided by call and return as string.

With all this your module should look like this:

file_tree

 

Communicating with new API call

Testing as guest

To test REST you can go to http://{domain_name}/rest/V1/{method}/{attribute}/{value}.

Example: http://magento2.loc/rest/V1/hello/name/Jim

This is how response should look like for this example:

<response>Hello, Jim</response>

Here is small code that will test same API call but with SOAP:

<?php
$proxy = new SoapClient('http://magento2.vm/index.php/soap/default?wsdl&services=inchooHelloV1');
$result = $proxy->inchooHelloV1Name(array("name"=>"Jim"));
var_dump($result);

Response for SOAP

object(stdClass)#2 (1) {
  ["result"]=>
  string(10) "Hello, Jim"
}

Adding ACL

If we don’t set anonymous in resource of webapi.xml, we need to set existing Magento resource or create our own. We can do that by adding acl.xml to etc.

ACL – etc/acl.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Inchoo_Hello::hello" title="Hello" translate="title" sortOrder="110" />
            </resource>
        </resources>
    </acl>
</config>

 

In this case we need to add “Inchoo_Hello::hello” to webapi.xml resource instead anonymous.

In article Magento 2 API usage with examples by Tomas Novoselic is covered how we can connect to Magento with REST or SOAP API and we can use the same example to create new integration and test new implementation of API call.

Since Magento 2 is still fresh this may change in time, but we will try to keep this up to date with latest version. This is tested with Magento v2.1.0.

 

You made it all the way down here so you must have enjoyed this post! You may also like:

MageOS and How Open Source Shapes eCommerce Tomislav Marijanovic

MageOS and How Open Source Shapes eCommerce

Back to the Future with Hyvä: Developers’ Perspective Tomislav Marijanovic

Back to the Future with Hyvä: Developers’ Perspective

Magento 2 API usage with examples Tomas Novoselic

Magento 2 API usage with examples

Tell us about your project

Drop us a line. We'd love to know more about your project.