1

Magento 2 version 2.1.10.

Admin base url : /admin

Site base url : /

How can I create a rest api and make it available only under the admin base url, like /admin/testapi ?

Furthermore, some day I may want use a separate domain name like admin.store.com for the backend site, how can I avoid CORS issue, like calling admin.store.com/testapi from store.com ?

Thanks a lot for any ideas ~~

1

To access any Rest API endpoint for admin only you need to defined its route like below in webapi.xml.

<route url="/V1/test/api" method="GET">
    <service class="Vendor\Module\Api\TestInterface" method="get"/>
    <resources>
        <resource ref="Magento_Cart::manage" />
    </resources>
</route>

In above code, this api endpoint can only be accessed for those admin users who have access of Magento_Cart::manage resource. To access this api you need to pass admin token in header. Let me know if you need further assistance.

  • Thanks for the help. But this does not address my question at all. My question is how to setup the rest api endpoint under admin site, and how to get around or deal with the CORS issue when I need to put admin site to a different domain. – jeffrey Nov 18 '18 at 8:30
0

You can access this by allow step below:

http://yoursite.loc/index.php/rest/V1/view

Api

<?php
namespace Iota\Security\Api;

interface SecurityManagementInterface
{

    const STORE_STATUS_OPEN = 1;
    const STORE_STATUS_CLOSE = 2;

    /**
     * @api
     * @return array.
     */
    public function view();
}

Model

<?php
namespace Iota\Security\Model;

/**
 * 
 */
class SecurityManagement implements \Iota\Security\Api\SecurityManagementInterface {

    public function view(){
        // Something
    }
}

etc/di.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Ihor Vansach (ihor@magefan.com). All rights reserved.
 * See LICENSE.txt for license details (http://opensource.org/licenses/osl-3.0.php).
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Iota\Security\Model\SecurityManagementInterface" type="Iota\Security\Model\SecurityManagement"/>
</config>

etc/webapi.xml

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">

    <route url="/V1/view" method="GET">
        <service class="Iota\Security\Api\SecurityManagementInterface"
            method="view" />
        <resources>
            <resource ref="anonymous" />
        </resources>
    </route>
</routes>

For admin level access define by <resource ref="Magento_Catalog::manage" />. And you route by <route url="/V1/view" method="GET">

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.