How to execute API in Magento 2

Here are the following steps which help you how to execute API in Magento 2:

  1. Announce new Magento 2 API function in xml
  2. Announce the API Inteface
  3. Activate the interface StaffRepositoryInterface
  4. Announce the interface & model in DI file

It Supports Magento REST (Representative State Transfer) and SOAP (Simple Object Access Protocol) API, which allows them to obtain, create, update & delete such as Product, customer, sales order, cms Module, etc.. This Magento 2 API permits you to easily connect to third-party application for Magento.

In some cases, in the 3rd application we need to activate further APIs in Magento to allow us to control the data of our volumes, or to rewrite the Magento Default API. How can we do that?

The following steps is used to activate new API in Magento 2

Announce new Magento 2 API function in webapi.xml

I announce the API which permits to get list in my module in the config file:

<?xml version="1.0"?>

<routes xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">

   <route url="/V1/staffs" method="GET">

       <service class="[NameSpace]\[ModuleName]\Api\StaffRepositoryInterface" method="getList"/>


           <resource ref="[NameSpace]_[ModuleName]:staffs" />




Announce the API Inteface

Form interface  StaffRespositoryInterface


namespace [NameSpace]\[ModuleName]\Api;

use Magento\Framework\Api\SearchCriteriaInterface;

interface StaffRepositoryInterface



* Retrieve staffs matching the specified criteria.


* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria

* @return \[NameSpace]\[ModuleName]\Model\ResourceModel\Staff\Collection

* @throws \Magento\Framework\Exception\LocalizedException


public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);


Activate the interface StaffRepositoryInterface

I activate the interface StaffRepositoryInterface in my model:


namespace [NameSpace]\[ModuleName]\Model;

use [NameSpace]\[ModuleName]\Api\StaffRepositoryInterface;

class StaffRepository implements StaffRepositoryInterface



* Load Block data collection by given search criteria


* @SuppressWarnings(PHPMD.CyclomaticComplexity)

* @SuppressWarnings(PHPMD.NPathComplexity)

* @param \Magento\Framework\Api\SearchCriteriaInterface $criteria

* @return \[NameSpace]\[ModuleName]\Model\ResourceModel\Staff\Collection


public function getList(\Magento\Framework\Api\SearchCriteriaInterface $criteria)


    /* Implement code to get the list of staffs here */



Announce the interface & model in DI file

Insert line below to Di file:

<preference for="[NameSpace]\[ModuleName]\Api\BlockRepositoryInterface" type="[NameSpace]\[ModuleName]\Model\BlockRepository" />






Leave a Reply

Your email address will not be published. Required fields are marked *